目录
1.中文停用词数据(hit_stopwords.txt)来源于:
2.其中data数据集为chinese_text_cnn-master.zip提取出的文件。点击链接进入github,点击Code、Download ZIP即可下载。
引言:
在当今数字化时代,人们在社交媒体、评论平台以及各类在线交流中产生了海量的文本数据。这些数据蕴含着丰富的情感信息,从而成为了深入理解用户态度、市场趋势,甚至社会情绪的宝贵资源。自然语言处理(NLP)的发展为我们提供了强大的工具,使得对文本情感进行分析成为可能。在这个领域中,长短时记忆网络(LSTM)凭借其能够捕捉文本序列中长距离依赖关系的能力,成为了情感分析任务中的一项重要技术。
本篇博客将手把手地教你如何使用LSTM网络实现中文文本情感分析。我们将从数据预处理开始,逐步构建一个端到端的情感分析模型。通过详细的步骤和示例代码,深入了解如何处理中文文本数据、构建LSTM模型、进行训练和评估。
1.所有文件展示:
1.中文停用词数据(hit_stopwords.txt)来源于:
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_y
# 改成你自己的tsv文件路径
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]
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 datas
def 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 #