【自然语言处理(NLP)实战】LSTM网络实现中文文本情感分析(手把手与教学超详细)

目录

引言:

1.所有文件展示:

1.中文停用词数据(hit_stopwords.txt)来源于:

2.其中data数据集为chinese_text_cnn-master.zip提取出的文件。点击链接进入github,点击Code、Download ZIP即可下载。

2.安装依赖库:

3.数据预处理(data_set.py):

train.txt-去除停用词后的训练集文件:

test.txt -去除停用词后的测试集文件:

4. 模型训练以及保存(main.py)

1.LSTM模型搭建:

2.main.py代价展示 :

 3.模型保存

4.训练结果 

5.LSTM模型测试(test.py) 

 1.测试结果:

2.测试结果:

6.完整代码展示:

1.data_set.py

2.mian.py

3.test.py 


引言:

在当今数字化时代,人们在社交媒体、评论平台以及各类在线交流中产生了海量的文本数据。这些数据蕴含着丰富的情感信息,从而成为了深入理解用户态度、市场趋势,甚至社会情绪的宝贵资源。自然语言处理(NLP)的发展为我们提供了强大的工具,使得对文本情感进行分析成为可能。在这个领域中,长短时记忆网络(LSTM)凭借其能够捕捉文本序列中长距离依赖关系的能力,成为了情感分析任务中的一项重要技术。

本篇博客将手把手地教你如何使用LSTM网络实现中文文本情感分析。我们将从数据预处理开始,逐步构建一个端到端的情感分析模型。通过详细的步骤和示例代码,深入了解如何处理中文文本数据、构建LSTM模型、进行训练和评估。

1.所有文件展示:

1.中文停用词数据(hit_stopwords.txt)来源于:

项目目录预览 - stopwords - GitCode

2.其中data数据集为chinese_text_cnn-master.zip提取出的文件。点击链接进入github,点击Code、Download ZIP即可下载。

2.安装依赖库:

pip install torch # 搭建LSTM模型
pip install gensim # 中文文本词向量转换
pip install numpy # 数据清洗、预处理
pip install pandas

3.数据预处理(data_set.py):

# -*- coding: utf-8 -*-
# @Time : 2023/11/15 10:52
# @Author :Muzi
# @File : data_set.py
# @Software: PyCharm
import pandas as pd
import jieba# 数据读取
def load_tsv(file_path):data = pd.read_csv(file_path, sep='\t')data_x = data.iloc[:, -1]data_y = data.iloc[:, 1]return data_x, data_ytrain_x, train_y = load_tsv("./data/train.tsv")
test_x, test_y = load_tsv("./data/test.tsv")
train_x=[list(jieba.cut(x)) for x in train_x]
test_x=[list(jieba.cut(x)) for x in test_x]with open('./hit_stopwords.txt','r',encoding='UTF8') as f:stop_words=[word.strip() for word in f.readlines()]print('Successfully')
def drop_stopword(datas):for data in datas:for word in data:if word in stop_words:data.remove(word)return datasdef save_data(datax,path):with open(path, 'w', encoding="UTF8") as f:for lines in datax:for i, line in enumerate(lines):f.write(str(line))# 如果不是最后一行,就添加一个逗号if i != len(lines) - 1:f.write(',')f.write('\n')if __name__ == '__main':train_x=drop_stopword(train_x)test_x=drop_stopword(test_x)save_data(train_x,'./train.txt')save_data(test_x,'./test.txt')print('Successfully')

train.txt-去除停用词后的训练集文件:

 

test.txt -去除停用词后的测试集文件:

4. 模型训练以及保存(main.py)

1.LSTM模型搭建:

不同的数据集应该有不同的分类标准,我这里用到的数据模型属于二分类问题

# 定义LSTM模型
class LSTMModel(nn.Module):def __init__(self, input_size, hidden_size, output_size):super(LSTMModel, self).__init__()self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)self.fc = nn.Linear(hidden_size, output_size)def forward(self, x):lstm_out, _ = self.lstm(x)output = self.fc(lstm_out[:, -1, :])  # 取序列的最后一个输出return output# 定义模型
input_size = word2vec_model.vector_size
hidden_size = 50  # 你可以根据需要调整隐藏层大小
output_size = 2  # 输出的大小,根据你的任务而定model = LSTMModel(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()  # 交叉熵损失函数
optimizer = torch.optim.Adam(model.parameters(), lr=0.0002)

2.main.py代价展示 :

# -*- coding: utf-8 -*-
# @Time : 2023/11/13 20:31
# @Author :Muzi
# @File : mian.py.py
# @Software: PyCharm
import pandas as pd
import torch
from torch import nn
import jieba
from gensim.models import Word2Vec
import numpy as np
from data_set import load_tsv
from torch.utils.data import DataLoader, TensorDataset# 数据读取
def load_txt(path):with open(path,'r',encoding='utf-8') as f:data=[[line.strip()] for line in f.readlines()]return datatrain_x=load_txt('train.txt')
test_x=load_txt('test.txt')
train=train_x+test_x
X_all=[i for x in train for i in x]_, train_y = load_tsv("./data/train.tsv")
_, test_y = load_tsv("./data/test.tsv")
# 训练Word2Vec模型
word2vec_model = Word2Vec(sentences=X_all, vector_size=100, window=5, min_count=1, workers=4)# 将文本转换为Word2Vec向量表示
def text_to_vector(text):vector = [word2vec_model.wv[word] for word in text if word in word2vec_model.wv]return sum(vector) / len(vector) if vector else [0] * word2vec_model.vector_sizeX_train_w2v = [[text_to_vector(text)] for line in train_x for text in line]
X_test_w2v = [[text_to_vector(text)] for line in test_x for text in line]# 将词向量转换为PyTorch张量
X_train_array = np.array(X_train_w2v, dtype=np.float32)
X_train_tensor = torch.Tensor(X_train_array)
X_test_array = np.array(X_test_w2v, dtype=np.float32)
X_test_tensor = torch.Tensor(X_test_array)
#使用DataLoader打包文件
train_dataset = TensorDataset(X_train_tensor, torch.LongTensor(train_y))
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_dataset = TensorDataset(X_test_tensor,torch.LongTensor(test_y))
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=True)
# 定义LSTM模型
class LSTMModel(nn.Module):def __init__(self, input_size, hidden_size, output_size):super(LSTMModel, self).__init__()self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)self.fc = nn.Linear(hidden_size, output_size)def forward(self, x):lstm_out, _ = self.lstm(x)output = self.fc(lstm_out[:, -1, :])  # 取序列的最后一个输出return output# 定义模型
input_size = word2vec_model.vector_size
hidden_size = 50  # 你可以根据需要调整隐藏层大小
output_size = 2  # 输出的大小,根据你的任务而定model = LSTMModel(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()  # 交叉熵损失函数
optimizer = torch.optim.Adam(model.parameters(), lr=0.0002)if __name__ == "__main__":# 训练模型num_epochs = 10log_interval = 100  # 每隔100个批次输出一次日志loss_min=100for epoch in range(num_epochs):model.train()for batch_idx, (data, target) in enumerate(train_loader):outputs = model(data)loss = criterion(outputs, target)optimizer.zero_grad()loss.backward()optimizer.step()if batch_idx % log_interval == 0:print('Epoch [{}/{}], Batch [{}/{}], Loss: {:.4f}'.format(epoch + 1, num_epochs, batch_idx, len(train_loader), loss.item()))# 保存最佳模型if loss.item()<loss_min:loss_min=loss.item()torch.save(model, 'model.pth')# 模型评估with torch.no_grad():model.eval()correct = 0total = 0for data, target in test_loader:outputs = model(data)_, predicted = torch.max(outputs.data, 1)total += target.size(0)correct += (predicted == target).sum().item()accuracy = correct / totalprint('Test Accuracy: {:.2%}'.format(accuracy))

 3.模型保存

 # 保存最佳模型if loss.item()<loss_min:loss_min=loss.item()torch.save(model, 'model.pth')

4.训练结果 

5.LSTM模型测试(test.py) 

# -*- coding: utf-8 -*-
# @Time : 2023/11/15 15:53
# @Author :Muzi
# @File : test.py.py
# @Software: PyCharm
import torch
import jieba
from torch import nn
from gensim.models import Word2Vec
import numpy as npclass LSTMModel(nn.Module):def __init__(self, input_size, hidden_size, output_size):super(LSTMModel, self).__init__()self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)self.fc = nn.Linear(hidden_size, output_size)def forward(self, x):lstm_out, _ = self.lstm(x)output = self.fc(lstm_out[:, -1, :])  # 取序列的最后一个输出return output# 数据读取
def load_txt(path):with open(path,'r',encoding='utf-8') as f:data=[[line.strip()] for line in f.readlines()]return data#去停用词
def drop_stopword(datas):# 假设你有一个函数用于预处理文本数据with open('./hit_stopwords.txt', 'r', encoding='UTF8') as f:stop_words = [word.strip() for word in f.readlines()]datas=[x for x in datas if x not in stop_words]return datasdef preprocess_text(text):text=list(jieba.cut(text))text=drop_stopword(text)return text# 将文本转换为Word2Vec向量表示
def text_to_vector(text):train_x = load_txt('train.txt')test_x = load_txt('test.txt')train = train_x + test_xX_all = [i for x in train for i in x]# 训练Word2Vec模型word2vec_model = Word2Vec(sentences=X_all, vector_size=100, window=5, min_count=1, workers=4)vector = [word2vec_model.wv[word] for word in text if word in word2vec_model.wv]return sum(vector) / len(vector) if vector else [0] * word2vec_model.vector_sizeif __name__ == '__main__':# input_text = "这个车完全就是垃圾,又热又耗油"input_text = "这个车我开了好几年,还是不错的"label = {1: "正面情绪", 0: "负面情绪"}model = torch.load('model.pth')# 预处理输入数据input_data = preprocess_text(input_text)# 确保输入词向量与模型维度和数据类型相同input_data=[[text_to_vector(input_data)]]input_arry= np.array(input_data, dtype=np.float32)input_tensor = torch.Tensor(input_arry)# 将输入数据传入模型with torch.no_grad():output = model(input_tensor)predicted_class = label[torch.argmax(output).item()]print(f"predicted_text:{input_text}")print(f"模型预测的类别: {predicted_class}")

 1.测试结果:

2.测试结果:

6.完整代码展示:

1.data_set.py

import pandas as pd
import jieba# 数据读取
def load_tsv(file_path):data = pd.read_csv(file_path, sep='\t')data_x = data.iloc[:, -1]data_y = data.iloc[:, 1]return data_x, data_ywith open('./hit_stopwords.txt','r',encoding='UTF8') as f:stop_words=[word.strip() for word in f.readlines()]print('Successfully')
def drop_stopword(datas):for data in datas:for word in data:if word in stop_words:data.remove(word)return datasdef save_data(datax,path):with open(path, 'w', encoding="UTF8") as f:for lines in datax:for i, line in enumerate(lines):f.write(str(line))# 如果不是最后一行,就添加一个逗号if i != len(lines) - 1:f.write(',')f.write('\n')if __name__ == '__main':train_x, train_y = load_tsv("./data/train.tsv")test_x, test_y = load_tsv("./data/test.tsv")train_x = [list(jieba.cut(x)) for x in train_x]test_x = [list(jieba.cut(x)) for x in test_x]train_x=drop_stopword(train_x)test_x=drop_stopword(test_x)save_data(train_x,'./train.txt')save_data(test_x,'./test.txt')print('Successfully')

2.mian.py

import pandas as pd
import torch
from torch import nn
import jieba
from gensim.models import Word2Vec
import numpy as np
from data_set import load_tsv
from torch.utils.data import DataLoader, TensorDataset# 数据读取
def load_txt(path):with open(path,'r',encoding='utf-8') as f:data=[[line.strip()] for line in f.readlines()]return datatrain_x=load_txt('train.txt')
test_x=load_txt('test.txt')
train=train_x+test_x
X_all=[i for x in train for i in x]_, train_y = load_tsv("./data/train.tsv")
_, test_y = load_tsv("./data/test.tsv")
# 训练Word2Vec模型
word2vec_model = Word2Vec(sentences=X_all, vector_size=100, window=5, min_count=1, workers=4)# 将文本转换为Word2Vec向量表示
def text_to_vector(text):vector = [word2vec_model.wv[word] for word in text if word in word2vec_model.wv]return sum(vector) / len(vector) if vector else [0] * word2vec_model.vector_sizeX_train_w2v = [[text_to_vector(text)] for line in train_x for text in line]
X_test_w2v = [[text_to_vector(text)] for line in test_x for text in line]# 将词向量转换为PyTorch张量
X_train_array = np.array(X_train_w2v, dtype=np.float32)
X_train_tensor = torch.Tensor(X_train_array)
X_test_array = np.array(X_test_w2v, dtype=np.float32)
X_test_tensor = torch.Tensor(X_test_array)
#使用DataLoader打包文件
train_dataset = TensorDataset(X_train_tensor, torch.LongTensor(train_y))
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_dataset = TensorDataset(X_test_tensor,torch.LongTensor(test_y))
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=True)
# 定义LSTM模型
class LSTMModel(nn.Module):def __init__(self, input_size, hidden_size, output_size):super(LSTMModel, self).__init__()self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)self.fc = nn.Linear(hidden_size, output_size)def forward(self, x):lstm_out, _ = self.lstm(x)output = self.fc(lstm_out[:, -1, :])  # 取序列的最后一个输出return output# 定义模型
input_size = word2vec_model.vector_size
hidden_size = 50  # 你可以根据需要调整隐藏层大小
output_size = 2  # 输出的大小,根据你的任务而定model = LSTMModel(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()  # 交叉熵损失函数
optimizer = torch.optim.Adam(model.parameters(), lr=0.0002)if __name__ == "__main__":# 训练模型num_epochs = 10log_interval = 100  # 每隔100个批次输出一次日志loss_min=100for epoch in range(num_epochs):model.train()for batch_idx, (data, target) in enumerate(train_loader):outputs = model(data)loss = criterion(outputs, target)optimizer.zero_grad()loss.backward()optimizer.step()if batch_idx % log_interval == 0:print('Epoch [{}/{}], Batch [{}/{}], Loss: {:.4f}'.format(epoch + 1, num_epochs, batch_idx, len(train_loader), loss.item()))# 保存最佳模型if loss.item()<loss_min:loss_min=loss.item()torch.save(model, 'model.pth')# 模型评估with torch.no_grad():model.eval()correct = 0total = 0for data, target in test_loader:outputs = model(data)_, predicted = torch.max(outputs.data, 1)total += target.size(0)correct += (predicted == target).sum().item()accuracy = correct / totalprint('Test Accuracy: {:.2%}'.format(accuracy))

3.test.py 

import torch
import jieba
from torch import nn
from gensim.models import Word2Vec
import numpy as npclass LSTMModel(nn.Module):def __init__(self, input_size, hidden_size, output_size):super(LSTMModel, self).__init__()self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)self.fc = nn.Linear(hidden_size, output_size)def forward(self, x):lstm_out, _ = self.lstm(x)output = self.fc(lstm_out[:, -1, :])  # 取序列的最后一个输出return output# 数据读取
def load_txt(path):with open(path,'r',encoding='utf-8') as f:data=[[line.strip()] for line in f.readlines()]return data#去停用词
def drop_stopword(datas):# 假设你有一个函数用于预处理文本数据with open('./hit_stopwords.txt', 'r', encoding='UTF8') as f:stop_words = [word.strip() for word in f.readlines()]datas=[x for x in datas if x not in stop_words]return datasdef preprocess_text(text):text=list(jieba.cut(text))text=drop_stopword(text)return text# 将文本转换为Word2Vec向量表示
def text_to_vector(text):train_x = load_txt('train.txt')test_x = load_txt('test.txt')train = train_x + test_xX_all = [i for x in train for i in x]# 训练Word2Vec模型word2vec_model = Word2Vec(sentences=X_all, vector_size=100, window=5, min_count=1, workers=4)vector = [word2vec_model.wv[word] for word in text if word in word2vec_model.wv]return sum(vector) / len(vector) if vector else [0] * word2vec_model.vector_sizeif __name__ == '__main__':input_text = "这个车完全就是垃圾,又热又耗油"# input_text = "这个车我开了好几年,还是不错的"label = {1: "正面情绪", 0: "负面情绪"}model = torch.load('model.pth')# 预处理输入数据input_data = preprocess_text(input_text)# 确保输入词向量与模型维度和数据类型相同input_data=[[text_to_vector(input_data)]]input_arry= np.array(input_data, dtype=np.float32)input_tensor = torch.Tensor(input_arry)# 将输入数据传入模型with torch.no_grad():output = model(input_tensor)# 这里只一个简单的示例predicted_class = label[torch.argmax(output).item()]print(f"predicted_text:{input_text}")print(f"模型预测的类别: {predicted_class}")

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

<C++> 优先级队列

目录 前言 一、priority_queue的使用 1. 成员函数 2. 例题 二、仿函数 三、模拟实现 1. 迭代器区间构造函数 && AdjustDown 2. pop 3. push && AdjustUp 4. top 5. size 6. empty 四、完整实现 总结 前言 优先级队列以及前面的双端队列基本上已经脱离了队列定…

场景图形管理 - (2)

裁剪平面示例(二) 裁剪平面(osg::Scissor)示例(二)的代码如程序清单8-2所示 // 裁剪平面测试&#xff08;2&#xff09; void scissor_8_2(const string strDataFolder) { osg::ref_ptr<osgViewer::Viewer> viewer new osgViewer::Viewer(); osg::ref_ptr<osg::Gra…

原力CEO赵锐:ToDesk是国内唯一适合高精远程办公需求的解决方案

随着数字办公在各行业的渗透&#xff0c;远程办公也逐渐成为一种常态。2000多名艺术家员工遍布全球各地的江苏原力数字科技股份有限公司&#xff08;下称&#xff1a;原力&#xff09;&#xff0c;是一家国内业务范围、规模均遥遥领先的数字业务内容提供商。一直以来&#xff0…

在webstorm中配置sass编译环境

1.下载ruby 下载地址&#xff1a;ruby下载 2.安装ruby 下载之后&#xff0c;有一个exe安装包 双击exe文件 &#xff0c;并选择自己的安装位置&#xff08;这个位置一定要记得&#xff0c;需要在webstorm中使用&#xff09;。其他的步骤默认安装即可。 3.安装sass ruby安装成功后…

【MATLAB源码-第75期】基于模拟退火算法(SA)的栅格路径规划,输出做短路径图和适应度曲线。

操作环境&#xff1a; MATLAB 2022a 1、算法描述 模拟退火算法是一种启发式优化算法&#xff0c;通常用于解决组合优化问题&#xff0c;例如旅行商问题和图着色问题。它模拟了固体材料在退火过程中逐渐冷却达到稳定状态的行为&#xff0c;以寻找问题的全局最优解。 以下是模…

故障演练的关键要素及重要性

故障演练是一种有计划的、模拟真实生产环境故障的活动。通过故意引入故障、模拟系统组件失效或模拟其他异常条件&#xff0c;团队可以观察并评估系统在这些情况下的反应。这有助于发现潜在的问题、改进应急响应和提高系统整体的可用性。 一、故障演练的关键要素 计划性&#xf…

异常--Java

cry…catch使用 /*需求&#xff1a;测试除法器&#xff08;try...catch&#xff09;* 测试人&#xff1a;小王* 测试日期&#xff1a;2023/11/15* */ package yichang_test1;import java.util.InputMismatchException; import java.util.Scanner;public class TestException2 …

【ROS导航Navigation】四 | SLAM与导航 | 自主移动的地图构建 (更新ing)

致谢&#xff1a;ROS赵虚左老师 Introduction Autolabor-ROS机器人入门课程《ROS理论与实践》零基础教程 参考赵虚左老师的实战教程 实现比较简单&#xff0c;步骤如下: 编写launch文件&#xff0c;集成SLAM与move_base相关节点&#xff1b;执行launch文件并测试。 <la…

无人机内存卡数据恢复

1.插入内存卡 2.选择对应的品牌 3.点击恢复 建议&#xff1a;发现数据打不开或者丢失情况&#xff0c;建议及时断电&#xff0c;以免影响数据的正常恢复&#xff01; #无人机##数据恢复##储存卡#

刚开始测试自动化? 这些错误不要犯,一定要看!别踩坑!!

我经常与一些客户打交道&#xff0c;他们的测试自动化能力要么刚刚开始&#xff0c;要么正在努力成长&#xff0c;而且他们常常都犯同样的致命错误。 虽然他们可能了解测试自动化的基础知识&#xff0c;但是他们仍然认为脚本化测试的价值在于通过自动执行脚本而不是手工执行来…

如何在Windows 10中进行屏幕截图

本文介绍如何在Windows 10中捕获屏幕截图&#xff0c;包括使用键盘组合、使用Snipping Tool、Snipp&Sketch Tool或Windows游戏栏。 使用打印屏幕在Windows 10中捕获屏幕截图 在Windows 10中捕获屏幕截图的最简单方法是按下键盘上的PrtScWindows键盘组合。你将看到屏幕短暂…

linux 网络 cat /proc/net/dev 查看测试网络丢包情况

可以通过 cat /proc/net/dev 查看测试网络丢包情况&#xff0c;drop关键字&#xff0c;查看所有网卡的丢包情况 还可以看其他数据&#xff0c; /proc/net/下面有如下文件