第7章 项目: 开发神经网络用于情感分析的词袋模型

电影评论可以被分类为喜爱或者不喜爱,电影评论文本的分类问题通常称为情感分析。用于开发情感分析模型的流行技术是词袋模型,词袋模型将文档转换为向量,文档中的每个单词被分配一个数。在本教程中,您将了解如何使用词袋模型来开发深度学习预测模型,以用于电影评论情感分类。完成本教程后,您将了解:

  • 如何准备评论文本数据以使用受限词汇表进行建模。
  • 如何使用词袋模型来准备训练和测试数据。
  • 如何开发一个多层感知器词袋模型,并用它来预测新的评论文本数据。

7.1 教程概述

本教程分为以下几部分:

  1. 电影评论数据集
  2. 数据准备
  3. 词袋表示
  4. 情感分析模型
  5. 比较单词评分方法
  6. 给新评论的分类

7.2 电影评论数据集

在本教程中,我们将使用Movie Review数据集。这个为情感分析设计的数据集在前面的第9章中有描述。您可以从这里下载数据集:

解压缩文件后,您将拥有一个名为txt_sentoken的目录,其中包含两个子目录neg和pos,分别存放负面和正面评论。neg和pos目录中的每个文件存储一个评论,命名规则为cv000到cv999。接下来,我们来看看加载文本数据。

7.3 数据准备

注意:电影评论数据集的预处理工作已经在第9章中介绍了。在本节中,我们将介绍接下来的准备工作:

  1. 将数据分成训练和测试集。
  2. 加载和清理数据以删除标点符号和数字。
  3. 定义首选词汇的词汇。

7.3.1 拆分成训练和测试数据集

我们假装正在开发一个系统,可以预测电影评论的情绪是正面还是负面的,这意味着在开发模型之后,我们会使用模型对新的文本评论进行预测,这就要求对这些新评论也要进行和训练数据一样的预处理。

我们在任何数据准备之前要将数据集拆分为训练和测试集,这个约束一直贯穿与我们整个模型评估的过程中。这意味着在准备数据和模型训练期间,测试集中任何知识对我们来说都是未知的,而且在训练过程中都是不可用的。我们将使用最后100个正面评论和100个负面评论作为测试集(200条评论),其余1,800条评论作为训练数据集。数据集的90%的用于训练,10%的数据用于测试。通过评论的文件名可以轻松实现拆分,其中评论为000至899的评论用于训练,而评论为900以上的评论用于测试模型。

7.3.2 装载和清洗评论

文本数据已经相当干净,因此不需要太多准备工作。在不了解细节的情况下,我们将使用以下方法准备数据:

  • 以空格为分隔符分词。
  • 从单词中删除所有标点符号。
  • 删除所有不完全由字母字符组成的单词。
  • 删除所有已知停用词。
  • 删除长度≤1个字符的所有单词。

我们可以将所有这些步骤放入一个名为clean_doc()的函数中,该函数将从文件加载的原始文本作为参数,并返回已清理的分词列表。我们还可以定义一个函数load_doc,它从文件中加载文档,以便与clean_doc()函数一起使用。下面列出了预处理第一个正面评价的示例。

from nltk.corpus import stopwords
import string
import re
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r' )
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
    # turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile( '[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub( '' , w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words( 'english' ))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load the document
filename = 'txt_sentoken/pos/cv000_29590.txt'
text = load_doc(filename)
tokens = clean_doc(text)
print(tokens)

清单7.1:清理电影评论的示例。

运行该示例会打印一长串干净的分词。我们可能想要尝试更多的清洗步骤,并将其作为进一步的练习。我很想知道你能想出什么。

……

'depp', 'turning', 'typically', 'strong', 'performance', 'deftly', 'handling', 'british', 'accent', 'ians', 'holm', 'joe', 'goulds', 'secret', 'richardson', 'dalmatians', 'log', 'great', 'supporting', 'roles', 'big', 'surprise', 'graham', 'cringed', 'first', 'time', 'opened', 'mouth', 'imagining', 'attempt', 'irish', 'accent', 'actually', 'wasnt', 'half', 'bad', 'film', 'however', 'good', 'strong', 'violencegore', 'sexuality', 'language', 'drug', 'content']

代码7.2:清洗电影评论的示例输出

7.3.3 定义词汇表

在使用词袋模型时,定义已知单词的词汇表很重要。单词越多,文档的表示越大,因此将单词限制为仅被认为具有明显态度的单词是很重要的。这很难事先知道,并且重要的是我们需要测试不同的关于文本的猜测来确定如何构建有用词汇表。在上一节的示例中我们已经知道了如何从词汇表中删除标点符号和数字,我们可以对所有文档重复此操作,并构建一组所有已知单词。

我们可以使用Counter类来构建一个词汇表,它是一个单词及其计数的字典映射,可以让我们轻松更新和查询。每个文档都可以添加到Counter(通过add_doc_to_vocab()函数)中,我们可以先处理负面评论的目录中的所有评论,然后是正面评价的目录额的所有评论(通过process_docs()函数)。下面列出了完整的示例。

import string
import re
from os import listdir
from collections import Counter
from nltk.corpus import stopwords
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r' )
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile( '[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub( '' , w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words( 'english' ))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc and add to vocab
def add_doc_to_vocab(filename, vocab):
    # load doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # update counts
    vocab.update(tokens)
# load all docs in a directory
def process_docs(directory, vocab):
    # walk through all files in the folder
    for filename in listdir(directory):
        # skip any reviews in the test set
        if filename.startswith( 'cv9' ):
          continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # add doc to vocab
        add_doc_to_vocab(path, vocab)
# define vocab
vocab = Counter()
# add all docs to vocab
process_docs( 'txt_sentoken/pos' , vocab)
process_docs( 'txt_sentoken/neg' , vocab)
# print the size of the vocab
print(len(vocab))
# print the top words in the vocab
print(vocab.most_common(50))

代码清单7.3:为数据集选择词汇表的示例

运行该示例表明我们的词汇量为44276个单词。我们还可以看到电影评论中前50个最常用单词的样本。请注意,此词汇表仅基于训练数据集中的那些评论构建。

44276

[('film', 7983), ('one', 4946), ('movie', 4826), ('like', 3201), ('even', 2262), ('good', 2080), ('time', 2041), ('story', 1907), ('films', 1873), ('would', 1844), ('much', 1824), ('also', 1757), ('characters', 1735), ('get', 1724), ('character', 1703), ('two', 1643), ('first', 1588), ('see', 1557), ('way', 1515), ('well', 1511), ('make', 1418), ('really', 1407), ('little', 1351), ('life', 1334), ('plot', 1288), ('people', 1269), ('bad', 1248), ('could', 1248), ('scene', 1241), ('movies', 1238), ('never', 1201), ('best', 1179), ('new', 1140), ('scenes', 1135), ('man', 1131), ('many', 1130), ('doesnt', 1118), ('know', 1092), ('dont', 1086), ('hes', 1024), ('great', 1014), ('another', 992), ('action', 985), ('love', 977), ('us', 967), ('go', 952), ('director', 948), ('end', 946), ('something', 945), ('still', 936)]

代码清单7.4:为数据集选择词汇表的示例输出

我们可以逐步浏览词汇表并删除所有发生率较低的单词,例如仅在所有评论中使用一次或两次。例如,以下代码段将仅检索在所有评论中出现2次或更多次的token。

# keep tokens with a min occurrence
min_occurrence = 2
tokens = [k for k,c in vocab.items() if c >= min_occurrence]
print(len(tokens))

代码清单7.5:按出现次数过滤词汇表的示例

最后,词汇表可以保存到一个名为vocab.txt的新文件中,以后我们可以加载并使用它来过滤电影评论,然后再对其进行编码以进行建模。我们定义了一个名为save_list()的函数,它将词汇表保存到文件中,每行一个单词。例如:

# save list to file
def save_list(lines, filename):
    # convert lines to a single blob of text
    data = '\n' .join(lines)
    # open file
    file = open(filename, 'w' )
    # write text
    file.write(data)
    # close file
    file.close()
# save tokens to a vocabulary file
save_list(tokens, 'vocab.txt' )

代码清单7.6:保存过滤词汇表的示例

将所有这些结合在一起,下面列出了完整的示例。

import string
import re
from os import listdir
from collections import Counter
from nltk.corpus import stopwords
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r' )
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile( '[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub( '', w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words( 'english' ))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc and add to vocab
def add_doc_to_vocab(filename, vocab):
    # load doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # update counts
    vocab.update(tokens)
# load all docs in a directory
def process_docs(directory, vocab):
    # walk through all files in the folder
    for filename in listdir(directory):
    # skip any reviews in the test set
        if filename.startswith( 'cv9' ):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # add doc to vocab
        add_doc_to_vocab(path, vocab)
# save list to file
def save_list(lines, filename):
    # convert lines to a single blob of text
    data = '\n' .join(lines)
    # open file
    file = open(filename, 'w' )
    # write text
    file.write(data)
    # close file
    file.close()
    # define vocab
vocab = Counter()
# add all docs to vocab
process_docs( 'txt_sentoken/pos' , vocab)
process_docs( 'txt_sentoken/neg' , vocab)
# print the size of the vocab
print(len(vocab))
# keep tokens with a min occurrence
min_occurrence = 2
tokens = [k for k,c in vocab.items() if c >= min_occurrence]
print(len(tokens))
# save tokens to a vocabulary file
save_list(tokens, 'vocab.txt' )

代码清单7.7:过滤数据集词汇表的示例

运行上述示例表明,词汇量大小略大于其大小的一半,从大约44,000缩减到大约25,000个单词。

44276

25767

代码清单7.8:按最小值出现过滤词汇表的示例输出

在词汇表上运行最小出现过滤器并将其保存到文件,您现在应该有一个名为vocab.txt的新文件,其中只包含我们感兴趣的词。

文件中的单词顺序会有所不同,但应如下所示:

……

tomita

lana

perados

munsters

jerichos

lillianna

hudsons

sewage

wrightpenn

garret

garrets

arraki

turteltaub

mcgruder

brynner

代码清单7.9:词汇表文件vocab.txt的示例

我们现在准备好从准备建模的评论中提取特征。

7.4 词袋表示

在本节中,我们将介绍如何将每个评论转换为多层感知器模型可以处理的数据表示形式。词袋模型就是一种从文本中提取特征的方法,因此经过词袋模型处理后的文本就可以输入给神经网络等机器学习算法使用了。每个文档(在这种情况下是评论)被转换为矢量表示,表示文档的向量中的元素数量对应于词汇表中的单词数,词汇量越大,矢量表示越长,因此词汇表词汇表额大小会影响输入数据的大小,我们应该找个平衡点选择很是的词汇表的大小,一般建议在能解决问题的情况下,词汇表越小越好。这个之前在第8章中介绍过。

对文档中的单词进行评分,并将分数放在表示中的相应位置。我们将在下一节中介绍不同的单词评分方法。在本节中,我们关注的是将评论转换为准备用于训练第一神经网络模型的向量。本节分为两个步骤:

  1. 将评论转换为分词行(token)。
  2. 使用词袋模型编码评论。

7.4.1 根据词汇把评论转成转成限定词汇行表示

在我们将评论转换为矢量进行建模之前,我们必须对它们进行清洗,这包括加载它们,执行上面定义的清理操作,过滤掉不在所选词汇表中的单词,并将剩余的标记转换为单个字符串或行准备编码。首先,我们需要一个函数来准备一个文档。下面列出了doc_to_line()的函数的代码,它完成加载文档、清洗文档、过滤掉不在词汇表中的词汇,然后将文档转成一串空白分隔的分词(token)返回

# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)

代码清单7.10:通过预定义词汇表过滤评论的功能

接下来,我们需要一个函数来处理目录中的所有文档(例如pos和neg)以将文档转换为行。下面列出了完成这个一系列动作的process_docs()函数,函数的参数包含评论文件的目录名及选择的词汇表,处理完后返回已处理文档的列表。

# load all docs in a directory
def process_docs(directory, vocab):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
        # skip any reviews in the test set
        if filename.startswith( 'cv9' ):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines

代码清单7.11:按词汇过滤所有电影评论的功能

我们调用process_docs()处理正面和负面评论,构建评论文本及其相关输出标签的数据集,0表示负面,1表示正面。我们把这个处理过程定义为load_clean_dataset函数。

# load and clean a dataset
def load_clean_dataset(vocab):
    # load documents
    neg = process_docs( 'txt_sentoken/neg' , vocab)
    pos = process_docs( 'txt_sentoken/pos' , vocab)
    docs = neg + pos
    # prepare labels
    labels = [0 for _ in range(len(neg))] + [1 for _ in range(len(pos))]
    return docs, labels

代码清单7.12:加载电影评论和准备输出标签的功能

最后,我们需要加载词汇表并将其转换为用于清理评论的集合。

# load the vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = set(vocab.split())

代码清单7.13:加载预定义的单词词汇表

我们可以将所有这些放在一起,重复使用前面部分中定义的加载和清理功能。下面列出了完整的示例,演示了如何从训练数据集准备正面和负面评论。

import string
import re
from os import listdir
from nltk.corpus import stopwords
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r' )
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile( '[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub( '' , w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words( 'english' ))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' ' .join(tokens)
# load all docs in a directory
def process_docs(directory, vocab):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
    # skip any reviews in the test set
        if filename.startswith('cv9'):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines
# load and clean a dataset
def load_clean_dataset(vocab):
    # load documents
    neg = process_docs('txt_sentoken/neg' , vocab)
    pos = process_docs('txt_sentoken/pos' , vocab)
    docs = neg + pos
    # prepare labels
    labels = [0 for _ in range(len(neg))] + [1 for _ in range(len(pos))]
    return docs, labels
# load the vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = vocab.split()
vocab = set(vocab)
# load all training reviews
docs, labels = load_clean_dataset(vocab)
# summarize what we have
print(len(docs), len(labels))

代码清单7.14:按预定义的词汇表过滤所有电影评论。

运行此示例将加载并清洗评论文本并返回标签。

1800 1800

代码清单7.15:通过约束词汇表加载,清理和过滤电影评论数据的示例输出。

7.4.2 电影评论到词袋向量

我们将使用Keras API将评论转换为编码的文档向量。Keras提供了Tokenizer类,它可以执行我们在上一节中处理的一些清理和词汇定义任务。建议最好自己这个清洗准备流程,以确切知道做了什么以及为什么做。然而,Tokenizer类很方便,很容易将文档转换为编码向量。首先,创建Tokenizer,然后fit训练数据集中的文本文档。在这种情况下,这些是前一节中开发的positive_lines和negative_lines的聚合。

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

代码清单7.16:在清晰和过滤的电影评论中使用Tokenizer的功能。

此过程确定将词汇表转换为具有25,768个元素的固定长度向量,这是词汇表文件vocab.txt中的单词总数。接下来,可以调用Tokenizer的texts_to_matrix()函数来编码文档。该函数参数是编码的文档列表和mode,mode选项决定文档中的单词进行评分的方法,在这里,指定freq根据文档中的频率对单词进行评分。可同时用于编码加载的训练和测试数据,例如:

# encode data
Xtrain = tokenizer.texts_to_matrix(train_docs, mode= 'freq' )
Xtest = tokenizer.texts_to_matrix(test_docs, mode= 'freq' )

代码清单7.17:编码训练数据

这将编码训练数据集中的所有正面和负面评论。

接下来,需要修改上一节中的流程docs()函数,以便可以选择性地处理测试或训练数据集中的评论。我们通过添加is_train参数来决定要跳过哪些评论文件名来支持加载训练和测试数据集。

# load all docs in a directory
def process_docs(directory, vocab, is_train):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
        # skip any reviews in the test se
        if is_train and filename.startswith( 'cv9' ):
            continue
        if not is_train and not filename.startswith( 'cv9' ):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines

代码清单7.18:更新的流程文档功能可以加载所有评论。

同样,修改load_clean_dataset()函数以加载train或test数据集并确保它以NumPy数组形式返回数据。

# load and clean a dataset
def load_clean_dataset(vocab, is_train):
    # load documents
    neg = process_docs( 'txt_sentoken/neg' , vocab, is_train)
    pos = process_docs( 'txt_sentoken/pos' , vocab, is_train)
    docs = neg + pos
    # prepare labels
    labels = array([0 for _ in range(len(neg))] + [1 for _ in range(len(pos))])
    return docs, labels

代码清单7.19:加载文本数据和标签的函数

我们可以将所有这些代码放在一起。

import string
import re
from os import listdir
from numpy import array
from nltk.corpus import stopwords
from keras.preprocessing.text import Tokenizer
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r' )
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile( '[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub( '' , w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words( 'english' ))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)
# load all docs in a directory
def process_docs(directory, vocab, is_train):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
        # skip any reviews in the test set
        if is_train and filename.startswith( 'cv9' ):
        
            continue
        if not is_train and not filename.startswith('cv9'):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines
# load and clean a dataset
def load_clean_dataset(vocab, is_train):
    # load documents
    neg = process_docs( 'txt_sentoken/neg' , vocab, is_train)
    pos = process_docs( 'txt_sentoken/pos' , vocab, is_train)
    docs = neg + pos
    # prepare labels
    labels = array([0 for _ in range(len(neg))] + [1 for _ in range(len(pos))])
    return docs, labels
# fit a tokenizer
def create_tokenizer(lines):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(lines)
    return tokenizer
# load the vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = set(vocab.split())
# load all reviews
train_docs, ytrain = load_clean_dataset(vocab, True)
test_docs, ytest = load_clean_dataset(vocab, False)
# create the tokenizer
tokenizer = create_tokenizer(train_docs)
# encode data
Xtrain = tokenizer.texts_to_matrix(train_docs, mode= 'freq' )
Xtest = tokenizer.texts_to_matrix(test_docs, mode= 'freq' )
print(Xtrain.shape, Xtest.shape)

代码清单7.20:准备训练和测试数据的完整示例

运行示例分别打印编码的训练数据集和测试数据集的形状,分别具有1,800和200个文档,每个文档具有相同大小的编码词汇表(矢量长度)。

 (1800, 25768) (200, 25768)

代码清单7.21:加载和准备数据集的示例输出

7.5  情感分析模型

在本节中,我们将开发多层感知器(MLP)模型,将编码文档分类为正面或负面,模型是使用了Keras中的Dense全连接层构建的简单的前馈网络。本节分为3个部分:

  1. 第一个情感分析模型
  2. 比较单词评分模式
  3. 预测新的评论

7.5.1 第一情感分析模型

我们可以开发一个简单的MLP模型来预测编码评论的情绪。模型的输入层的大小等于词汇表中的单词数即输入文档的长度。我们可以将它存储在一个名为n_words的新变量中,如下所示:

n_words = Xtest.shape[1]

代码清单7.22:计算单词数的示例

我们现在开始定义网络模型,观察Keras的Dense的API发现所有模型可配置的参数不多,和使用的时候出错可能也不多,所以我们不过细的考虑模型层的参数配置问题,除了明确指定,其他的均是默认参数值。我们定义一个具有50个神经元和使用relu()激活函数的隐藏层。输出层是使用sigmoid激活函数的单个神经元,用于预测最终评论的类别:0为负面评价,1为正面评价。因为二元分类问题,我们训练过程梯度下降使用Adam算法和损失函数选择二元交叉熵(binary_crossentropy),在训练和评估模型时,我们将跟踪模型准确性数据。

# define the model
def define_model(n_words):
    # define network
    model = Sequential()
    model.add(Dense(50, input_shape=(n_words,), activation= 'relu' ))
    model.add(Dense(1, activation= 'sigmoid' ))
    # compile network
    model.compile(loss= 'binary_crossentropy' , optimizer= 'adam' , metrics=[ 'accuracy' ])
    # summarize defined model
    model.summary()
    plot_model(model, to_file= 'model.png' , show_shapes=True)
    return model

代码7.23:为bag-of-words模型定义MLP的示例

接下来,在训练数据上训练模型;模型很小,10个epoch很快就训练完了。

# fit network
model.fit(Xtrain, ytrain, epochs=10, verbose=2)

代码清单7.24:拟合定义模型的示例

最后,一旦模型训练完成,我们就可以使用测试数据集对模型进行预测并打印精度来评估其性能。

# evaluate
loss, acc = model.evaluate(Xtest, ytest, verbose=0)
print( ' Test Accuracy: %f ' % (acc*100))

代码清单7.25:评估拟合模型的示例

下面列出了完整的示例。

import string
import re
from os import listdir
from numpy import array
from nltk.corpus import stopwords
from keras.preprocessing.text import Tokenizer
from keras.utils.vis_utils import plot_model
from keras.models import Sequential
from keras.layers import Dense

# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile('[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub('', w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)
# load all docs in a directory

def process_docs(directory, vocab, is_train):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
        # skip any reviews in the test set
        if is_train and filename.startswith('cv9'):
            continue
        if not is_train and not filename.startswith('cv9'):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines
# load and clean a dataset
def load_clean_dataset(vocab, is_train):
    # load documents
    neg = process_docs('txt_sentoken/neg', vocab, is_train)
    pos = process_docs('txt_sentoken/pos', vocab, is_train)
    docs = neg + pos
    # prepare labels
    labels = array([0 for _ in range(len(neg))] + [1 for _ in range(len(pos))])
    return docs, labels
# fit a tokenizer
def create_tokenizer(lines):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(lines)
    return tokenizer
# define the model
def define_model(n_words):
    # define network
    model = Sequential()
    model.add(Dense(50, input_shape=(n_words,), activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    # compile network
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    # summarize defined model
    model.summary()
    plot_model(model, to_file='model.png', show_shapes=True)
    return model
# load the vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = set(vocab.split())
# load all reviews
train_docs, ytrain = load_clean_dataset(vocab, True)
test_docs, ytest = load_clean_dataset(vocab, False)
# create the tokenizer
tokenizer = create_tokenizer(train_docs)
# encode data
Xtrain = tokenizer.texts_to_matrix(train_docs, mode='freq')
Xtest = tokenizer.texts_to_matrix(test_docs, mode='freq')
# define the model
n_words = Xtest.shape[1]
model = define_model(n_words)
# fit network
model.fit(Xtrain, ytrain, epochs=10, verbose=2)
# evaluate
loss, acc = model.evaluate(Xtest, ytest, verbose=0)
print('Test Accuracy: %f' % (acc * 100))

代码清单7.26:培训和评估MLP词袋模型的完整示例

首先运行该示例将打印已定义模型的摘要。

_________________________________________________________________

Layer (type)                 Output Shape              Param #   

=================================================================

dense_1 (Dense)              (None, 50)                1288450   

_________________________________________________________________

dense_2 (Dense)              (None, 1)                 51        

=================================================================

Total params: 1,288,501

Trainable params: 1,288,501

Non-trainable params: 0

_________________________________________________________________

代码7.27:定义模型的摘要

然后将定义的模型的图表保存到名为model.png的文件中。

图7.1:定义的词袋模型的图。

我们可以看到该模型很轻松的在训练数据上训练了10个epoch,达到接近100%的准确度。在测试数据集上评估模型,我们可以看到模型表现良好,达到87%以上的准确率,完全超越了上个世纪80年代中期原始论文的最好记录。虽然这不能像一个苹果与另一个苹果的对比一样,但是我们可以看到原始论文使用10倍交叉验证来估计模型,才得到了那个结果,而使用前馈神经网络做的仅仅是把划分成训练/测试集。

注意:鉴于神经网络的随机性,您的具体结果可能会有所不同。考虑运行几示例。

……

Epoch 6/10

 - 0s - loss: 0.5330 - acc: 0.9439

Epoch 7/10

 - 0s - loss: 0.4850 - acc: 0.9461

Epoch 8/10

 - 0s - loss: 0.4391 - acc: 0.9556

Epoch 9/10

 - 1s - loss: 0.3931 - acc: 0.9628

Epoch 10/10

 - 0s - loss: 0.3518 - acc: 0.9717

Test Accuracy: 87.500000

代码7.28:培训和评估MLP模型的示例输出

接下来,让我们看看为词袋模型测试不同的单词评分方法。

7.6 比较单词评分方法

Keras API中Tokenizer的text_to_matrix()函数提供了4种不同的评分方法;他们是:

  • binary  单词被标记为存在(1)或不存在(0)。
  • count 每个单词的出现次数。
  • tfidf  每个单词根据其频率进行评分,其中所有文档中常见的单词都会受到惩罚。
  • freq  根据文档中出现的频率对单词进行评分。

我们使用4种单词评分模式中的每一种来评估上一节中开发的模型。首先定义一个函数,以基于所选择的评分模型来创建所加载文档的编码,该函数创建tokenizer,将其在训练文档上fit,然后使用所选模型创建训练和测试编码。该函数为prepare_data()在给定训练和测试文档列表上实现这个过程。

# prepare bag-of-words encoding of docs
def prepare_data(train_docs, test_docs, mode):
    # create the tokenizer
    tokenizer = Tokenizer()
    # fit the tokenizer on the documents
    tokenizer.fit_on_texts(train_docs)
    # encode training data set
    Xtrain = tokenizer.texts_to_matrix(train_docs, mode=mode)
    # encode training data set
    Xtest = tokenizer.texts_to_matrix(test_docs, mode=mode)
    return Xtrain, Xtest

代码清单7.29:更新了数据准备,将编码模式作为参数。

我们接着定义一个函数根据指定编码的数据拟合MLP。因为神经网络是随机的,当相同的模型拟合(fit)相同的数据时,它们也有可能产生不同的结果,这主要是两个原因造成的:一模型的权重参数的数值初始化是随机的,二训练过程中数据随机打乱的。这意味着模型的任何一个评分都是不可靠的,我们应该根据多次运行的平均值来估计模型好坏。下面的函数名为evaluate_mode(),它以编码后的训练集和测试集为参数,在训练集上训练10个epoch,然后使用测试集评估模型性能,把这一轮的训练得到的准确率添加到分数列表中,最后返回所有这些运行中的准确度分数列表。

# evaluate a neural network model
def evaluate_mode(Xtrain, ytrain, Xtest, ytest):
    scores = list()
    n_repeats = 30
    n_words = Xtest.shape[1]
    for i in range(n_repeats):
        # define network
        model = Sequential()
        model.add(Dense(50, input_shape=(n_words,), activation='relu'))
        model.add(Dense(1, activation='sigmoid'))
        # compile network
        model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
        # fit network
        model.fit(Xtrain, ytrain, epochs=10, verbose=2)
        # evaluate
        loss, acc = model.evaluate(Xtest, ytest, verbose=0)
        scores.append(acc)
        print('%d accuracy: %s' % ((i + 1), acc))
    return scores

代码清单7.30:多次创建,拟合和评估模型的函数

接下来评估4种单词评分方法的表现。将所有这些代码在一起,下面列出了完整的示例。

%matplotlib inline
import string
import re
from os import listdir
from numpy import array
from nltk.corpus import stopwords
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense
from pandas import DataFrame
from matplotlib import pyplot
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file10.6. Comparing Word Scoring Methods
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile('[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub('', w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)
# load all docs in a directory
def process_docs(directory, vocab, is_train):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
        # skip any reviews in the test set
        if is_train and filename.startswith('cv9'):
            continue
        if not is_train and not filename.startswith('cv9'):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines
# load and clean a dataset
def load_clean_dataset(vocab, is_train):
    # load documents
    neg = process_docs('txt_sentoken/neg', vocab, is_train)
    pos = process_docs('txt_sentoken/pos', vocab, is_train)
    docs = neg + pos
    # prepare labels
    labels = array([0 for _ in range(len(neg))] + [1 for _ in range(len(pos))])
    return docs, labels
# define the model
def define_model(n_words):
    # define network
    model = Sequential()
    model.add(Dense(50, input_shape=(n_words,), activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    # compile network
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model
# evaluate a neural network model
def evaluate_mode(Xtrain, ytrain, Xtest, ytest):
    scores = list()
    n_repeats = 10
    n_words = Xtest.shape[1]
    for i in range(n_repeats):
        # define network
        model = define_model(n_words)
        # fit network
        model.fit(Xtrain, ytrain, epochs=10, verbose=0)
        # evaluate
        _, acc = model.evaluate(Xtest, ytest, verbose=0)
        scores.append(acc)
        print('%d accuracy: %s' % ((i + 1), acc))
    return scores
# prepare bag of words encoding of docs
def prepare_data(train_docs, test_docs, mode):
    # create the tokenizer
    tokenizer = Tokenizer()
    # fit the tokenizer on the documents
    tokenizer.fit_on_texts(train_docs)
    # encode training data set
    Xtrain = tokenizer.texts_to_matrix(train_docs, mode=mode)
    # encode training data set
    Xtest = tokenizer.texts_to_matrix(test_docs, mode=mode)
    return Xtrain, Xtest
# load the vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = set(vocab.split())
# load all reviews
train_docs, ytrain = load_clean_dataset(vocab, True)
test_docs, ytest = load_clean_dataset(vocab, False)
# run experiment
modes = ['binary', 'count', 'tfidf', 'freq']
results = DataFrame()
for mode in modes:
    # prepare data for mode
    Xtrain, Xtest = prepare_data(train_docs, test_docs, mode)
    # evaluate model on data for mode
    results[mode] = evaluate_mode(Xtrain, ytrain, Xtest, ytest)
# summarize results
print(results.describe())
# plot results
results.boxplot()
pyplot.show()

代码清单7.31:比较文档编码方案的完整示例

在运行结束时,提供每个单词评分方法的摘要统计,总结每个模式的10次运行中的每一次的模型性能分数的分布。我们可以看到count和binary方法的平均得分似乎比freq和tfidf更好。

注意:鉴于神经网络的随机性,您的具体结果可能会有所不同。考虑运行几次示例。

            binary        count       tfidf              freq

count  10.00000  10.000000  10.000000  10.000000

mean    0.92900   0.899000   0.879000   0.866500

std     0.01075   0.005164   0.015951   0.007091

min     0.91000   0.895000   0.845000   0.855000

25%     0.92125   0.895000   0.875000   0.865000

50%     0.93500   0.897500   0.882500   0.867500

75%     0.93500   0.900000   0.885000   0.870000

max     0.94000   0.910000   0.905000   0.875000

代码清单7.32:比较文档编码方案的示例输出

 

 
 

还给出了结果的盒子和须状图,总结了每种配置的准确度分布。我们可以看到binary模式通过适度的扩展获得了最佳结果,并且是这个数据集的首选方法。

图7.2:使用不同单词评分方法的模型精度的框和晶须图。

7.7 预测新评论的情感

最后,我们开发最终模型并使用其来预测新的电影评论的类别。首先,使用所有可用数据训练最终模型。,通过上一节的对比我们发现,在这个问题中,binary模式获得的性能是最好的,因此构建词袋模型是选择binary模式对进行每个单词进行评分。

预测新评论的情感分类同样也要遵循准备测试数据的相同步骤。具体来说,加载文本,清理文档,通过所选词汇过评论的分词,将剩余词汇转换为行,使用Tokenizer对其进行编码,然后进行预测。我们可以通过调用predict()来直接使用拟合模型预测分类值,对于负面评论返回 0,对于正面评论返回 1 。这个过程定义为predict_sentiment(),函数参数为评论文本、词汇表、tokenizer和模型,并返回预测的情绪和该分类在两个分类中的百分比。

# classify a review as negative or positive
def predict_sentiment(review, vocab, tokenizer, model):
    # clean
    tokens = clean_doc(review)
    # filter by vocab7.7. Predicting Sentiment for New Reviews
    109
    tokens = [w for w in tokens if w in vocab]
    # convert to line
    line =' '.join(tokens)
    # encode
    encoded = tokenizer.texts_to_matrix([line], mode='binary')
    # predict sentiment
    yhat = model.predict(encoded, verbose=0)
    # retrieve predicted percentage and label
    percent_pos = yhat[0, 0]
    if round(percent_pos) == 0:
        return (1 - percent_pos), 'NEGATIVE'
    return percent_pos, 'POSITIVE'

代码清单7.33:为新评论做出预测的功能

我们现在可以对新的评论文本进行预测了,下面是使用词频评分模式的MLP模型进行明确肯定和明显否定评论预测的示例。

# test positive text
text = 'Best movie ever! It was great, I recommend it.'
percent, sentiment = predict_sentiment(text, vocab, tokenizer, model)
print(' Review: [%s] \n Sentiment: %s (%.3f%%) ' % (text, sentiment, percent * 100))
# test negative text
text = 'This is a bad movie.'
percent, sentiment = predict_sentiment(text, vocab, tokenizer, model)
print(' Review: [%s] \n Sentiment: %s (%.3f%%) ' % (text, sentiment, percent * 100))

代码清单7.34:对新评论进行预测的示例。

将这些全部拉到一起,下面列出了为新评论做出预测的完整示例。

import string
import re
from os import listdir
from numpy import array
from nltk.corpus import stopwords
from keras.preprocessing.text import Tokenizer
from keras.utils.vis_utils import plot_model
from keras.models import Sequential
from keras.layers import Dense

# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # prepare regex for char filtering
    re_punc = re.compile('[%s]' % re.escape(string.punctuation))
    # remove punctuation from each word
    tokens = [re_punc.sub('', w) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)
# load all docs in a directory
def process_docs(directory, vocab):
    lines = list()
    # walk through all files in the folder
    for filename in listdir(directory):
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines
# load and clean a dataset
def load_clean_dataset(vocab):
    # load documents
    neg = process_docs('txt_sentoken/neg', vocab)
    pos = process_docs('txt_sentoken/pos', vocab)
    docs = neg + pos
    # prepare labels
    labels = array([0 for _ in range(len(neg))] + [1 for _ in range(len(pos))])
    return docs, labels
# fit a tokenizer
def create_tokenizer(lines):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(lines)
    return tokenizer
# define the model
def define_model(n_words):
    # define network
    model = Sequential()
    model.add(Dense(50, input_shape=(n_words,), activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    # compile network
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    # summarize defined model
    model.summary()
    plot_model(model, to_file='model.png', show_shapes=True)
    return model
# classify a review as negative or positive
def predict_sentiment(review, vocab, tokenizer, model):
    # clean
    tokens = clean_doc(review)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    # convert to line
    line = ' '.join(tokens)
    # encode
    encoded = tokenizer.texts_to_matrix([line], mode='binary')
    # predict sentiment
    yhat = model.predict(encoded, verbose=0)
    # retrieve predicted percentage and label
    percent_pos = yhat[0, 0]
    if round(percent_pos) == 0:
        return (1 - percent_pos), 'NEGATIVE'
    return percent_pos, 'POSITIVE'
# load the vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = set(vocab.split())
# load all reviews
train_docs, ytrain = load_clean_dataset(vocab)
test_docs, ytest = load_clean_dataset(vocab)
# create the tokenizer
tokenizer = create_tokenizer(train_docs)
# encode data
Xtrain = tokenizer.texts_to_matrix(train_docs, mode='binary')
Xtest = tokenizer.texts_to_matrix(test_docs, mode='binary')
# define network
n_words = Xtrain.shape[1]
model = define_model(n_words)
# fit network
model.fit(Xtrain, ytrain, epochs=10, verbose=2)
# test positive text
text = 'Best movie ever! It was great, I recommend it.'
percent, sentiment = predict_sentiment(text, vocab, tokenizer, model)
print(' Review: [%s]\nSentiment: %s (%.3f%%) ' % (text, sentiment, percent * 100))
# test negative text
text = 'This is a bad movie.'
percent, sentiment = predict_sentiment(text, vocab, tokenizer, model)
print(' Review: [%s]\nSentiment: %s (%.3f%%) ' % (text, sentiment, percent * 100))

代码清单7.35:为新评论数据做出预测的完整示例

运行示例会对这些评论进行分类:

Review: [Best movie ever! It was great, I recommend it.]

Sentiment: POSITIVE (56.405%)

 Review: [This is a bad movie.]

Sentiment: NEGATIVE (67.533%)

代码清单7.36:为新评论做出预测的示例输出

理想情况下,我们将模型放在所有可用数据(训练和测试)上训练创建最终模型并将模型和词汇表保存到文件中,以后我们就可以在新软件中加载和使用这个模型和词汇表。


0 条 查看最新 评论

没有评论
暂时无法发表评论