深度学习应用13电影评论情感分析

具体代码见github

1IMDB数据集的获取与处理

在tf2.0里面装在了imdb数据集直接下载就可以
在这里插入图片描述
若是第一次下载,会在本地建立.kears文件夹下datasets并存储文件
在这里插入图片描述
在这里插入图片描述

1.1下载数据集

# 导入需要用的库
import os
import tarfile
# 软件包的解压
import urllib.request
#网络下载的请求
import tensorflow as tf
import numpy as np

import re
# 正则化
import string

from random import randint
# 数据地址
url='http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz'
filepath='data/aclImdb_v1.tar.gz'
# 如果当前目录下不存在data文件夹,则建立
if not os.path.exists('data'):
    os.makedirs('data')
# 下载数据,80兆左右
if not os.path.isfile(filepath):
    print('downloading...')
    result=urllib.request.urlretrieve(url,filepath)
    print('downloaded:',result)
else:
    print(filepath,'is existed')

在这里插入图片描述

# 解压数据
if not os.path.exists('data/aclImdb'):
    tfile=tarfile.open(filepath,'r:gz')
    print('extracting...')
    result=tfile.extractall('data/')
    print('extraction completed')
else:
    print('data/aclImdb is existed!')

在这里插入图片描述

1.2IMDB数据文件读取

有一些不太应该出现的词

<br>

文件由html转换所以有些问题
在这里插入图片描述
最好做些预处理去掉这些词
采用正则方式去除

# 将文本中不需要的字符清除,如html中的标签<br />
def remove_tags(text):
    re_tag=re.compile(r'<[^>]+>')
    return re_tag.sub('',text)

把文本文件转换为数据列表
在这里插入图片描述

def read_files(filetype):
    path='data/aclImdb/'
    file_list=[]
    # 读取正面评价的文件路径,存到file_list列表里
    positive_path=path+filetype+'/pos/'
    for f in os.listdir(positive_path):
        file_list+=[positive_path+f]
    pos_files_num=len(file_list)
    # 读取负面评价的文件的路径,存到file_list列表里
    negative_path=path+filetype+'/neg/'
    for  f in os.listdir(negative_path):
        file_list+=[negative_path+f]
    neg_files_num=len(file_list)-pos_files_num
    
    print('read',filetype,'files:',len(file_list))
    print(pos_files_num,'pos files in',filetype,'files')
    print(neg_files_num,'neg files in',filetype,'files')
    #得到所有标签。标签用one——hot编码,正面{1,0}负面[0,1]
    all_labels=([[1,0]]*pos_files_num+[[0,1]]*neg_files_num)
    
    # 得到所有文本
    all_texts=[]
    for fi in file_list:
        with open(fi,encoding='utf8') as file_input:
            #文本中有<br />这类html标签,将文本传入remove_tags函数
            #函数里用正则表达式将标签去除
            all_texts+=[remove_tags(''.join(file_input.readlines()))]
    return all_labels,all_texts
train_labels,train_texts=read_files("train")
test_labels,test_labels=read_files('test')

在这里插入图片描述
在这里插入图片描述

1.3数据处理

建立词汇词典

token=tf.keras.preprocessing.text.Tokenizer(num_words=4000)
# 分词器,把出现率最高的4000个词纳入分词器
token.fit_on_texts(train_texts)
# 查看token读取了多少文档
token.document_count

在这里插入图片描述

print(token.word_index)# 出现频率的排名

在这里插入图片描述

token.word_docs
# 将单词映射为他们在训练器出现的文档或文本的数量

在这里插入图片描述
查看每个词汇频次排名
在这里插入图片描述
文字转为数字列表

train_sequences=token.texts_to_sequences(train_texts)
test_sequences=token.texts_to_sequences(test_texts)

在这里插入图片描述
文字转为数字列表
在这里插入图片描述
让转换后数字列表长度相同

x_train=tf.keras.preprocessing.sequence.pad_sequences(train_sequences,padding='post',truncating='post',maxlen=400)
x_test=tf.keras.preprocessing.sequence.pad_sequences(test_sequences,padding='post',truncating='post',maxlen=400)
y_train=np.array(train_labels)
#要把标签改为ndarray格式
y_test=np.array(test_labels)
x_train.shape

要求输入大小都统一,维度相同,要去规范化评论长度,pad_sequece有截长补短的作用,不满足400填充0,填充截断有2种选择,截前面还是后400个,post是截后面的。post填后面的。
在这里插入图片描述

pad_sequece用法在这里插入图片描述
在这里插入图片描述

1.4构建模型

model=tf.keras.models.Sequential()
model.add(tf.keras.layers.Embedding(output_dim=32,
                                   input_dim=4000,
                                   input_length=400))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(units=256,activation='relu'))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(units=2,activation='softmax'))
model.summary()

在这里插入图片描述在这里插入图片描述

1.5训练模型

model.compile(optimizer='adam',
             loss='categorical_crossentropy',
             metrics=['accuracy'])
history=model.fit(x_train,y_train,
                 validation_split=0.2,
                 epochs=10,
                 batch_size=128,
                 verbose=1)

在这里插入图片描述

1.6可视化

在这里插入图片描述

import matplotlib.pyplot as plt
acc=history.history['accuracy']
val_acc=history.history['val_accuracy']
loss=history.history['loss']
val_loss=history.history['val_loss']
epochs=range(1,len(acc)+1)
plt.plot(epochs,loss,'r',label='Training loss')
plt.plot(epochs,val_loss,'b',label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.clf()# clear figure
acc_values=history.history['accuracy']
val_acc_values=history.history['val_accuracy']
plt.plot(epochs,acc,'r',label='Training acc')
plt.plot(epochs,val_acc,'b',label='Validation acc')
plt.title('Training and validation accutacy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

1.7评估准确率

test_loss,test_acc=model.evaluate(x_test,y_test,verbose=1)
print('Test Accuracy',test_acc)

在这里插入图片描述

1.8执行预测

predictions=model.predict(x_test)
predictions[0]

在这里插入图片描述

sentiment_dict={0:'pos',1:'neg'}
def display_test_sentiment(i):
    print(test_texts[i])
    print('label values:',sentiment_dict[np.argmax(y_test[i])],
          'predict value:',sentiment_dict[np.argmax(predictions[i])
display_test_sentiment(0)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
将过程封装函数就不用了上面的了结果如下
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了314 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_39289876/article/details/105112272