BILSTM实现情感二分类

源码地址:https://gitee.com/xxr007/BILSTM-sentimentAnalysis.git

数据探测

得到了数据第一步应该做什么?当然是摸清这批数据的底,这个步骤也叫数据分析。对于用于做情感分析的文本数据,数据分析大概需要如下几步:

  • 数据总量多少条

  • 标签有几种,他们的比例是多少

  • 每一条的评论的长度是多少
    句子长度分布直方图

  • 分词,去停用词后,每条评论的长度又是多少

  • 做一个简单的词云图
    词云

对于文本数据的分析用pandas这个库就够用了

import pandas as pd
import jieba
import seaborn as sea
import matplotlib.pyplot as plt
#导入词云和参数
import pyecharts.options as opts
from pyecharts.charts import WordCloud
# train = pd.read_csv('data/train.csv')
# print(train.head)
# print(train.shape)#数据规模
# print(pd.unique(train['label'].values))# 有哪几个标签
# print(len(train[train['label']==0])/len(train)) #标签为0所占比例
#
# sentence_length = train['data'].apply(lambda x:len(x))#统计每个句子的长短
# sentence_length_fenci = train['data'].apply(lambda x:len(jieba.lcut(x)))
# print(sentence_length)
# print(sentence_length_fenci)
# sea.displot(sentence_length_fenci) #画出直方图
# plt.show()

#导入停用词
with open('data/stopwords.txt',encoding='utf-8') as f:
    stopwords = []
    # print(f.readlines())
    for word in f.readlines():
        stopwords.append(word.strip('\n'))

#分词
def fenci(sentence):
    return [word for word in jieba.lcut(sentence) if word not in stopwords]

train_data = pd.read_csv('data/train.csv')
total_word = train_data['data'].apply(fenci)

#统计词频
word_dict = {
   }
for words in total_word:
    for word in words:
        flag = word_dict.get(word,0)
        if flag == 0:
            word_dict[word] = 1
        else:
            word_dict[word] += 1
# print(word_dict)
#按词频排序
word_dict = sorted(word_dict.items(),key=lambda x:x[1],reverse = True )
# print('new',word_dict)
#生成词云
c = WordCloud()
c.add(series_name='',data_pair=word_dict[10:1000])
c.render()#默认生成一个html文件

数据加载与封装

使用torchtext这个库

  1. 首先声明一个Filed对象,这个对象指定处理数据的方式。

    • tokenize传入分词的函数,将文本分割成token
    • sequential表示是否切分数据,如果数据已经是序列化的了而且是数字类型的,则应该传递参数use_vocab = False和sequential = False.如LABEL
      除了上面提到的关键字参数之外,Field类还允许用户指定特殊标记(用于标记词典外词语的unk_token,用于填充的pad_token,用于句子结尾的eos_token以及用于句子开头的可选的init_token)。设置将第一维是batch还是sequence(第一维默认是sequence),并选择是否允许在运行时决定序列长度还是预先就决定好
  2. 使用TabularDataset类告诉Filed需要处理那些数据。TabularDataset处理csv,tsv类文件很方面,使用TabularDataset.splits同时将训练集、验证集、测试集加载进来

  3. 建立词表,比如在训练集上建立词汇表,还可以将预训练的词向量加载到模型中。
    TEXT.build_vocab(train, vectors=“glove.6B.100d”)

输入:包含一行一行文本

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BiLSTM是一种常用的深度学习模型,可以用于文本分类任务。在情感分类任务中,可以利用BiLSTM对文本进行表示学习,进而进行情感分类。 以下是一种利用BiLSTM实现情感分类三分类的示例代码: 1. 准备数据 首先需要准备情感分类的数据集。假设数据集包含两个字段:text和label。其中text是一个字符串,表示文本内容;label是一个整数,表示文本的情感分类,取值为0、1、2。 可以使用pandas库读取数据集,并将text和label分别存储到两个列表中。 import pandas as pd data = pd.read_csv('sentiment.csv') texts = data['text'].tolist() labels = data['label'].tolist() 2. 分词和向量化 接下来需要对文本进行分词和向量化。可以使用分词工具jieba和词向量库gensim进行处理。 import jieba from gensim.models import Word2Vec # 分词 texts_cut = [jieba.lcut(text) for text in texts] # 训练词向量模型 model = Word2Vec(texts_cut, size=100, window=5, min_count=1) # 将文本转换为词向量序列 texts_vec = [] for text in texts_cut: vec = [] for word in text: if word in model.wv.vocab: vec.append(model[word]) texts_vec.append(vec) 3. 构建模型 构建BiLSTM模型,用于情感分类。 from keras.models import Sequential from keras.layers import Embedding, Bidirectional, LSTM, Dense # 定义模型 model = Sequential() model.add(Embedding(input_dim=len(model.wv.vocab), output_dim=100, input_length=None)) model.add(Bidirectional(LSTM(128, dropout=0.2, recurrent_dropout=0.2))) model.add(Dense(3, activation='softmax')) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 4. 训练模型 使用上一步中构建的模型对数据进行训练。 import numpy as np from keras.utils import to_categorical # 将标签转换为one-hot编码 labels_onehot = to_categorical(labels, num_classes=3) # 训练模型 model.fit(np.array(texts_vec), labels_onehot, batch_size=32, epochs=10, validation_split=0.2) 5. 预测结果 使用训练好的模型对新的文本进行情感分类。 # 对新文本进行分词和向量化 text_new = '这家餐厅很好吃' text_new_cut = jieba.lcut(text_new) text_new_vec = [] for word in text_new_cut: if word in model.wv.vocab: text_new_vec.append(model[word]) # 预测结果 result = model.predict(np.array([text_new_vec])) label_new = np.argmax(result) print('新文本的情感分类为:', label_new) 以上就是利用BiLSTM实现情感分类三分类的示例代码。需要注意的是,这只是一种示例代码,具体实现可能因数据集、模型结构等因素而有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值