NLP——电影评论情感分析

python-tensorflow2.0
numpy 1.19.1
tensorflow 2.0.0

导入库

数据加载

数据处理

构建模型

训练

评估

预测

1.基于2层dropout神经网络

2.基于LSTM的网络

#导入需要用到的库
import os
import tarfile
import urllib. request
import tensorflow as tf
import numpy as np
import re
import string
from random import randint
数据地址
ur1="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
#数据存放路径
filepath="D:\\课程学习\\深度学习\\深度学习应用开发-TensorFlow实践_浙江大学\\data\\aclImdb_v1.tar.gz"
#如果当前目录下不存在data文件夹,则建立
if not os. path.exists("D:\\课程学习\\深度学习\\深度学习应用开发-TensorFlow实践_浙江大学\\data"):
    os.makedirs("D:\\课程学习\\深度学习\\深度学习应用开发-TensorFlow实践_浙江大学\\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('D:\\课程学习\\深度学习\\深度学习应用开发-TensorFlow实践_浙江大学\\data"):
    tfile=tarfile.open (filepath,"r:gz" )
    print('extracting...' )
    result=tfile.extractall("D:\\课程学习\\深度学习\\深度学习应用开发-TensorFlow实践_浙江大学\\data\\")
    print("extraction completed")
else:
    print("data/aclImdb is existed!")

在这里插入图片描述

#将文本中不需要的字符清除,如html标签<br />
def remove_tags(text) :
    re_tag = re.compile(r'<[^>]+>')
    return re_tag.sub ('',text)
#读取文件
def read_files(filetype) :
    path ="D:\\课程学习\\深度学习\\深度学习应用开发-TensorFlow实践_浙江大学\\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_texts=read_files("test" )

在这里插入图片描述

#查看数据、标签
print ("训练数据")
print("正面评价:")
print(train_texts[0])
print (train_labels[0])
print("负面评价:")
print (train_texts[12500])
print (train_labels[12500])
print ("测试数据")
print("正面评价:")
print(test_texts[0])
print (test_labels[0])
print("负面评价:")
print (test_texts[12500])
print (test_labels[12500])

在这里插入图片描述

数据处理

#建立词汇词典Token
#建立Token
token =tf.keras.preprocessing.text.Tokenizer(num_words=4000)
token.fit_on_texts(train_texts)
#查看token读取了多少文档
token.document_count

#将单词(字符串)映射为它们的排名或者索引
print(token.word_index)
#将单词(字符串)映射为它们在训练期间所出现的文档或文本的数量
token.word_docs

在这里插入图片描述

#查看Token中词汇出现的频次排名
print (token.word_counts)

在这里插入图片描述

#文字转数字列表
train_sequences = token.texts_to_sequences(train_texts)
test_sequences = token.texts_to_sequences(test_texts)
print (train_texts[0])
print (train_sequences[0])
print (len(train_sequences[0]))

在这里插入图片描述

#让转换后的数字列表长度相同 
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)
x_train.shape

在这里插入图片描述

#填充后的数字列表
print(x_train[0])
print(len(x_train[0]))

在这里插入图片描述

y_train=np.array(train_labels)
y_test=np.array(test_labels)
print(y_train.shape)
print(y_test.shape)

在这里插入图片描述

构建模型

model = tf.keras.models.Sequential()
model.add (tf.keras.layers.Embedding (output_dim=32,## 输出词向量的维度
                                    input_dim=4000,## 输入词汇表的长度,最大词汇数+1
                                    input_length=400))# 输入Tensor的长度
model.add (tf.keras.layers.Flatten())
#用GlobalAveragePoolingID也起到平坦化的效果
# mode1. add (keras. layers. GlobalAveragePoolingIDO)
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()

在这里插入图片描述

#模型设置与训练
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)

在这里插入图片描述

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 accuracy' )
plt.xlabel('Epochs' )
plt.ylabel('Accuracy' )
plt.legend()
plt.show()

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

#评估模型准确率
test_1oss,test_acc = model.evaluate(x_test, y_test,verbose=1)
print(' Test accuracy:',test_acc)

在这里插入图片描述

#执行模型预测
predictions = model.predict(x_test)
predictions[0]

在这里插入图片描述

#定义预测结果显示函数
sentiment_dict = {0:'pos', 1:'neg' }
def display_test_sentiment(i) :
    print(test_texts[i])
    print('label value:', sentiment_dict[np.argmax(y_test[i])],'predict value:' , sentiment_dict[np.argmax(predictions[i])])

#查看预测结果
display_test_sentiment(0)

在这里插入图片描述

#文本情感分析模型应用
review_text="So much amazing action and beautiful cinematography makes for such an enlightening experience! In The Empire Strikes Back you know who everyone is which is great plus Yoda is introduced! I love this movie the music is soothing, there's romance, more of Darth Vader, and introduces Emperor Palpatine what more can you ask for? A lot to relish and get excited about; it's such a classic gem."

input_seq = token.texts_to_sequences([review_text])
pad_input_seq =tf.keras.preprocessing.sequence.pad_sequences(input_seq,
                                                            padding='post',
                                                            truncating='post' ,
                                                            maxlen=400)
pred = model.predict (pad_input_seq)
print('predict value:', sentiment_dict[np.argmax(pred)])

在这里插入图片描述

sentiment_dict = {0:' pos',1:'neg' }
def display_text_sentiment (text):
    print(text)
    input_seq = token.texts_to_sequences([text])
    pad_input_seq =tf.keras.preprocessing.sequence.pad_sequences(input_seq, 
                                                                padding='post',
                                                                truncating='post' ,
                                                                maxlen=400)
    pred = model.predict(pad_input_seq)
    print('predict value:', sentiment_dict[np.argmax(pred)])
display_text_sentiment(review_text) 

在这里插入图片描述

基于LSTM结构的模型构建

#建立模型
model = tf.keras.models.Sequential()
model.add (tf.keras.layers.Embedding (output_dim=32,
                                    input_dim=4000,
                                    input_length=400) )
#用RNN,不用把词嵌入层平坦化
# mode1. add (keras. layers. SimpleRNV(units=16))
model.add (tf.keras.layers.Bidirectional (tf.keras.layers.LSTM(units=8)))
model.add (tf.keras.layers.Dense (units=32,activation='relu' ))
model.add (tf.keras.layers.Dropout (0.3))
model.add (tf.keras.layers.Dense (units=2, activation='softmax' ))
model.summary()

在这里插入图片描述

#模型设置与训练
#标签是One -Hot编码的多分类模型,损失函数用categorical crossentropy
#标签不是0ne -Hot编码的多分类模型,损失函数用sparse. categorical .crossentropy
#标签是二分类,损失函数用binary_ crossentropy
model.compile(optimizer='adam',
            loss='categorical_crossentropy', #二二 分类
            metrics=['accuracy' ])
history = model.fit(x_train, y_train,
                    validation_split=0.2,
                    epochs=6,
                    batch_size=128,
                    verbose=1)

在这里插入图片描述

#评估模型准确率
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 accuracy' )
plt.xlabel('Epochs' )
plt.ylabel('Accuracy' )
plt.legend()
plt.show()

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

#评估模型准确率
test_1oss,test_acc = model.evaluate(x_test, y_test,verbose=1)
print(' Test accuracy:',test_acc)

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/696417.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

使用Python批量处理Excel的内容

正文共&#xff1a;1500 字 10 图&#xff0c;预估阅读时间&#xff1a;1 分钟 在前面的文章中&#xff08;如何使用Python提取Excel中固定单元格的内容&#xff09;&#xff0c;我们介绍了如何安装Python环境和PyCharm工具&#xff0c;还利用搭好的环境简单测试了一下ChatGPT提…

小程序名片怎么生成?AI名片生成器源码系统 为企业店铺创建自己的数字名片

在数字化时代&#xff0c;小程序名片已经成为企业店铺展示自身形象、推广产品和服务的重要工具。分享一个AI名片生成器源码系统春哥AI雷达智能名片小程序系统企业商业运营版&#xff0c;含完整代码包和详细的图文安装部署搭建教程&#xff0c;新手也能轻松使用&#xff0c;源码…

MySQL: 索引与事务

文章目录 1. 索引 (Index)1.1 概念1.2 作用1.3 使用场景1.4 索引的使用1.5 索引的使用案例 (不要轻易尝试)1.6 索引背后的数据结构1.7 重点总结 2.事务2.1 为什么要使用事务2.2 事务的概念2.3 事务的使用2.4 对事务的理解2.5 事务的基本特性 1. 索引 (Index) 1.1 概念 索引是…

Python Requests库详解

大家好&#xff0c;在现代网络开发中&#xff0c;与Web服务器进行通信是一项至关重要的任务。Python作为一种多才多艺的编程语言&#xff0c;提供了各种工具和库来简化这一过程。其中&#xff0c;Requests库作为Python中最受欢迎的HTTP库之一&#xff0c;为开发人员提供了简单而…

12-Gateway网关-网关作用介绍

12-Gateway网关-网关作用介绍 1.为什么需要网关&#xff1a; 网关功能&#xff1a; ​ 1.身份认证和权限校验 ​ 2.服务路由、负载均衡 ​ 3.请求限流 2.网关的技术实现&#xff1a; 在SpringCloud中网关的实现包括两种“ ​ gateway ​ zuul Zuul是基于Servlet的实…

node-mysql的批量插入

此前我批量插入都是用类似这样的命令&#xff1a; sqlcmdinsert into table(field1,field2,...) values ? indata[["f1v1","f2v1"],["f1v2","f2v2"],...] mysqlconn.query(sqlcmd,[indata],(err,res)>{...})但是感觉不太舒服&…

VueRouter3学习笔记

文章目录 1&#xff0c;入门案例2&#xff0c;一些细节高亮效果非当前路由会被销毁 3&#xff0c;嵌套路由4&#xff0c; 传递查询参数5&#xff0c;命名路由6&#xff0c;传递路径参数7&#xff0c;路径参数转props8&#xff0c;查询参数转props9&#xff0c;replace模式10&am…

Vue--》从零开始打造交互体验一流的电商平台(二)

今天开始使用 vue3 + ts 搭建一个电商项目平台,因为文章会将项目的每处代码的书写都会讲解到,所以本项目会分成好几篇文章进行讲解,我会在最后一篇文章中会将项目代码开源到我的github上,大家可以自行去进行下载运行,希望本文章对有帮助的朋友们能多多关注本专栏,学习更多…

SAP Build 1-工作流表单开发

1. BTP SAP Build环境配置 1.1 启用试用账号 访问BTP trial&#xff0c;启用试用账号&#xff0c;没有的话注册一个即可 https://account.hanatrial.ondemand.com/trial/#/home/trial 注册完之后就会让选择区域&#xff0c;要选US的区域才有自动化相关的功能 然后就开始生成…

什么是Java?

什么是Java&#xff1f;java是什么&#xff1f;下面我们来总结一下。 java是什么&#xff1f; java是一个静态编程语言&#xff0c;具有强大的多线程特征&#xff0c;目前java不仅采用c语言的优点&#xff0c;还去掉了一些多继承指针&#xff0c;等复杂的概念&#xff0c;我们…

跟着大佬学RE(六)

findKey 嗯&#xff0c;就是一个窗口程序&#xff0c;没有输入&#xff0c;flag 应该就藏在程序里面 第一遍自己直接莽做&#xff0c;在string窗口&#xff0c;找到 flag{} 看到标红直接 nop 然后&#xff0c;然后就不知道怎么搞了 这串字符提示不能随便 nop &#xff0c;重新…

优设AI导航

1、优设AI导航 优设AI导航

13. UDP协议与RTP协议

UDP协议 UDP协议比较简单&#xff1a; UDP的长度是固定的&#xff0c;用总长度-UDP长度就是数据长度。 UDP是不保证他的有序性和可靠性的。对于音频和视频是这样是比较好的&#xff0c;因为这段丢了&#xff0c;我们可以从下一段在开始解码。 RTP RTP 协议概述 RTP&#x…

【前端】详解JavaScript事件代理(事件委托)

&#x1f60e; 作者介绍&#xff1a;我是程序员洲洲&#xff0c;一个热爱写作的非著名程序员。CSDN全栈优质领域创作者、华为云博客社区云享专家、阿里云博客社区专家博主。 &#x1f913; 同时欢迎大家关注其他专栏&#xff0c;我将分享Web前后端开发、人工智能、机器学习、深…

简单了解java中的异常

异常 1、异常的概述 1.1、概述 异常就是程序出现了不正常的情况&#xff0c;程序在执行过程中&#xff0c;数据导致程序不正常&#xff0c;最终导致JVM的非正常停止。语句错误不算在异常体系中。 1.2、异常的存在形式 异常有类型之分&#xff0c;比如我们比较熟悉的数组越…

安装golang

官网:All releases - The Go Programming Language (google.cn) 下载对应的版本安装即可

数据结构初阶 · 链式二叉树的部分问题

目录 前言&#xff1a; 1 链式二叉树的创建 2 前序 中序 后序遍历 3 树的节点个数 4 树的高度 5 树的叶子节点个数 6 树的第K层节点个数 前言&#xff1a; 链式二叉树我们在C语言阶段已经实现了&#xff0c;这里介绍的是涉及到的部分问题&#xff0c;比如求树的高度&am…

liquibase做数据库版本管理

通过这个配置就会自动启动liquibase 比对 https://www.cnblogs.com/ludangxin/p/16676701.html https://zhuyizhuo.github.io/2020/07/04/spring-boot/spring-boot-liquibase-database-version-control/

如何理解与学习数学分析——第二部分——数学分析中的基本概念——第10章——实数

第2 部分&#xff1a;数学分析中的基本概念 (Concepts in Analysis) 10. 实数(The Real Numbers) 本章介绍比率数(rational numbers)和非比数(irrational numbers)及其与十进制展开的关系。讨论了实数的公理&#xff0c;并解释了完备性公理对于区分实数和比率数为何必不可少&…

IDEA启动项目报java.lang.OutOfMemoryError: GC overhead limit exceeded

idea编译项目时报j ava.lang.OutOfMemoryError: GC overhead limit exceeded错误&#xff0c;教你两步搞定&#xff01; 第一步&#xff1a;打开help -> Edit Custom VM Options ,修改xms和xmx的大小&#xff0c;如下图&#xff1a; 第二步&#xff1a;File -> Settings…