Keras NLP——文檔編碼

一.Python代碼

#!/usr/bin/env python
# encoding: utf-8
'''
@file: keras_data_prepare.py
@time: 2020/6/30 14:05
@author: Jack
@contact:[email protected]
'''
import string
import re
from os import listdir
from numpy import array
from nltk.corpus import stopwords
from keras.preprocessing.text import Tokenizer


def load_doc(filename):
    file = open(filename, 'r')
    text = file.read()
    file.close()
    return text


def clean_doc(doc):
    tokens = doc.split()
    re_punc = re.compile('[%s]' % re.escape(string.punctuation))
    tokens = [re_punc.sub('', w) for w in tokens]
    tokens = [w for w in tokens if w.isalpha()]
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    tokens = [w for w in tokens if len(w) > 1]
    return tokens


def doc_to_line(filename, vocab):
    doc = load_doc(filename)
    tokens = clean_doc(doc)
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)


def process_docs(directory, vocab, is_train):
    lines = list()
    for filename in listdir(directory):
        if is_train and filename.startswith('cv9'):
            continue
        if not is_train and not filename.startswith('cv9'):
            continue

        path = directory + '/' + filename
        line = doc_to_line(path, vocab)
        lines.append(line)
    return lines


def load_clean_dataset(vocab, is_train):
    neg = process_docs('txt_sentoken/neg', vocab, is_train)
    pos = process_docs('txt_sentoken/pos', vocab, is_train)
    docs = neg + pos
    labels = array([0 for _ in range(len(neg))] + [1 for _ in range(len(pos))])
    return docs, labels


def create_tokenizer(lines):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(lines)
    return tokenizer


vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = set(vocab.split())

train_docs, ytrain = load_clean_dataset(vocab, True)
test_docs, ytest = load_clean_dataset(vocab, False)
tokenizer = create_tokenizer(train_docs)

Xtrain = tokenizer.texts_to_matrix(train_docs, mode='freq')
Xtest = tokenizer.texts_to_matrix(test_docs, mode='freq')
print(Xtrain.shape, Xtest.shape)

二.代碼說明

該部分將把每個評論文檔轉換爲多層感知器模型可以處理的數據表示形式。詞袋模型就是一種從文本中提取特徵的方法,因此經過詞袋模型處理後的文本就可以輸入給神經網絡等機器學習算法使用了。每個文檔被轉換爲矢量表示,表示文檔的向量中的元素數量對應於詞彙表中的單詞數,詞彙量越大,矢量維度越高,因此詞彙表大小會影響輸入數據的大小,我們需要找個平衡點選擇詞彙表的大小,一般建議在能解決問題的情況下,詞彙表越小越好。
1.根據詞彙表將評論轉成限定詞彙行表示
doc_to_line()函數完成文檔加載、文檔清洗、過濾掉不在詞彙表中的詞彙,最後將文檔轉成一串空白分隔的token序列。
process_docs()函數用來處理目錄中的所有文檔(例如pos和neg)以將文檔轉換爲行。load_clean_dataset()函數調用process_docs()處理正面和負面評論,構建評論文本及其相關輸出標籤的數據集,0表示負面,1表示正面。
2.電影評論到詞袋向量
使用Keras創建Tokenizer,然後fit訓練數據集中的文本文檔,得到特定的tokenizer,然後用text_to_matrix()將評論通過編碼轉換爲固定長度的文檔向量。可以通過mode來指定對單詞進行評分的方法。

三.結果輸出

(1800, 25778) (200, 25778)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章