NLP——电影评论情感分析

news2024/7/6 20:32:03

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.coloradmin.cn/o/1809971.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

W25Q64简介

W25Q64介绍 本节使用的是&#xff1a;W25Q64&#xff1a; 64Mbit / 8MByte。存储器分为易失性存储器和非易失性存储器&#xff0c;易失性存储器一般是SRAM&#xff0c;DRAM。非易失性存储器一般是E2PROM&#xff0c;Flash等。非易失性存储器&#xff0c;掉电不丢失。 字库存储…

单片机嵌入式计算器(带程序EXE)

单片机嵌入式计算器 主要功能&#xff1a;完成PWM占空比计算&#xff0c;T溢出时间&#xff08;延时&#xff09;&#xff1b; [!NOTE] 两个程序EXE&#xff1b; [!CAUTION] 百度网盘链接&#xff1a;链接&#xff1a;https://pan.baidu.com/s/1VJ0G7W5AEQw8_MiagM7g8A?pwdg8…

java线程生命周期介绍

Java线程的生命周期包含以下几个状态&#xff1a; 1.新建(New)&#xff1a;线程对象被创建&#xff0c;但是还没有调用start()方法。 1.运行(Runnable)&#xff1a;线程正在运行或者是就绪状态&#xff0c;等待CPU时间片。 1.阻塞(Blocked)&#xff1a;线程暂时停止执行&…

Nginx 精解:正则表达式、location 匹配与 rewrite 重写

一、常见的 Nginx 正则表达式 在 Nginx 配置中&#xff0c;正则表达式用于匹配和重写 URL 请求。以下是一些常见的 Nginx 正则表达式示例&#xff1a; 当涉及正则表达式时&#xff0c;理解各个特殊字符的含义是非常重要的。以下是每个特殊字符的例子&#xff1a; ^&#xff1…

修复损坏的Excel文件比你想象的要简单,这里提供几种常见的修复方法

打开重要的Excel文件时遇到问题吗?Microsoft Excel是否要求你验证文件是否已损坏?Excel文件可能由于各种原因而损坏,从而无法打开。但不要失去希望;你可以轻松修复损坏的Excel文件。 更改Excel信任中心设置 Microsoft Excel有一个内置的安全功能,可以在受限模式下打开有…

Failed to start gdm.servide - GNOME Display manager

启动虚拟机时&#xff0c;卡在Failed to start gdm.servide - GNOME Display manager不动。 解决方法: 1.重新启动Ubuntu&#xff0c;在进度条未结束之前&#xff0c;长按shift直到界面跳转到选项菜单。 2.选择第二个&#xff0c;按enter进入 3.选择最新版本&#xff08;后面…

MySQL时间和日期类型详解(零基础入门篇)

目录 1. DATE 2. DATETIME 3. TIMESTAMP 4. TIME 5. YEAR 6. 日期和时间的使用示例 以下SQL语句的测试可以使用命令行&#xff0c;或是使用SQL工具比如MySQL Workbench或SQLynx等。 在 MySQL 中&#xff0c;时间和日期数据类型用于存储与时间相关的数据&#xff0c;如何…

摄影软件使用小技巧

记录摄影过程中使用一些软件的技巧&#xff0c;方便后续查阅。 摄影软件使用小技巧 Pr制作延时视频用PS批量转换RAW照片Lightroom批量处理照片月亮后期堆栈——RegiStax6 Pr制作延时视频 新建序列 选择需要的格式 用PS批量转换RAW照片 Lightroom批量处理照片 按 Shfit&#xf…

解决Spark流处理产生的小文件问题

做流批一体&#xff0c;湖仓一体的大数据架构&#xff0c;常见的做法就是&#xff1a; 数据源->spark Streaming->ODS&#xff08;数据湖&#xff09;->spark streaming->DWD&#xff08;数据湖&#xff09;->... 那么数据源->spark Streaming->ODS&…

档案数字化管理的工具有哪些

档案数字化管理的工具可以包括以下几种&#xff1a; 1. 扫描仪/数字拍摄仪&#xff1a;用于将纸质文件数字化为电子文件的工具。 2. OCR&#xff08;光学字符识别&#xff09;软件&#xff1a;用于将扫描或拍摄的图像文件转换为可编辑的文本文件。 3. 文件管理系统/专久智能电子…

英语国际音标 - DJ 音标 - KK 音标

英语国际音标 - DJ 音标 - KK 音标 1. 国际音标 (International Phonetic Alphabet&#xff0c;IPA)1.1. 记音类型1.2. 48 个国际音标发音表1.2.1. 元音 (vowel)1.2.1.1. 单元音 (monophthong)1.2.1.2. 双元音 (diphthong) 1.2.2. 辅音 (consonant)1.2.2.1. 清音 (voiceless so…

企业内网安全软件分享,有什么内网安全软件

内网安全&#xff1f; 其实就是网络安全的一种。 什么是内网安全软件&#xff1f; 内网安全软件是企业保障内网安全的一种重要工具。 它主要帮助企业实现对网络设备、应用程序、用户行为等方面的监控和管理&#xff0c;以预防和应对各种网络攻击。 这类软件主要用于对内网中…

入侵报警系统的智慧核心——ARMxy工控机深度应用

智能安防领域高清视频监控、人脸识别门禁系统以及入侵报警系统的智能化升级&#xff0c;正以前所未有的速度推动着行业的变革。在这场变革中&#xff0c;ARMxy工业计算机以其卓越的性能、高度的灵活性及强大的集成能力&#xff0c;成为了众多安防解决方案中的核心组件。 高清视…

CorelDRAW2024破解激活码序列号一步到位

亲们&#xff0c;今天给大家种草一个神奇的软件——CorelDRAW破解2024最新版&#xff01;&#x1f3a8;这是一款专业级的矢量图形设计软件&#xff0c;无论你是平面设计师、插画师还是设计师&#xff0c;都能在这个软件中找到你需要的工具和功能。✨ 让我来给大家介绍一下这款软…

MySQL事务,视图,用户管理学习笔记【事务概念 | 事务隔离级别 | 设置级别 | 视图 | 用户管理】

博客主页&#xff1a;花果山~程序猿-CSDN博客 文章分栏&#xff1a;MySQL之旅_花果山~程序猿的博客-CSDN博客 关注我一起学习&#xff0c;一起进步&#xff0c;一起探索编程的无限可能吧&#xff01;让我们一起努力&#xff0c;一起成长&#xff01; 目录 一&#xff0c;事务初…

现代x86汇编-环境安装

今天端午节&#xff0c;独自在家&#xff0c;翻阅了张银奎老师编写的《现代x86汇编语言程序设计》一书&#xff0c;前言部分说明书中示例代码都是用微软visual C工具编写并使用微软宏汇编&#xff08;著名的MASM&#xff09;编译的&#xff0c;好久没有用微软vc了&#xff0c;假…

48岁冻龄女神性感现身。

千禧台湾性感女神林熙蕾&#xff0c;昔日凭《赌侠大战拉斯维加斯》、《千王之王2000》等作品成名&#xff0c;成为港产片一代女神&#xff0c;今年林熙蕾惊喜参演王家卫执导剧集《繁花》&#xff0c;再度于华语影视坛受注目。6月6日于台湾现身品牌活动&#xff0c;以一袭银色超…

大数据解决方案案例:电商平台日志分析

个人名片 &#x1f393;作者简介&#xff1a;java领域优质创作者 &#x1f310;个人主页&#xff1a;码农阿豪 &#x1f4de;工作室&#xff1a;新空间代码工作室&#xff08;提供各种软件服务&#xff09; &#x1f48c;个人邮箱&#xff1a;[2435024119qq.com] &#x1f4f1…

Android 蓝牙profile的配置

在做BQB认证之前&#xff0c;我们需要确认那些profile之前&#xff0c;我们需要查看profile的配置情况 Android13版本前蓝牙profile的配置 MTK的项目代码如下 vendor\mediatek\proprietary\packages\modules\Bluetooth\android\app\res\values\config.xml 高通的项目代码如…

【漏洞复现】宏景eHR openFile.jsp 任意文件读取漏洞

0x01 产品简介 宏景eHR人力资源管理软件是一款人力资源管理与数字化应用相融合&#xff0c;满足动态化、协同化、流程化、战略化需求的软件。 0x02 漏洞概述 宏景eHR openFile.jsp 接口处存在任意文件读取漏洞&#xff0c;未经身份验证攻击者可通过该漏洞读取系统重要文件(如…