中文新闻数据集
负面文本:

正面文本:

数据文本都是用爬虫从网络上爬取的,由人工进行分类,在使用这些数据之前,需要先对文本进行预处理,预处理包括去除标点符号,停用词过滤和分词等,由于篇幅有限,这里就不放预处理代码了,处理完的数据如下:

使用循环神经网络(LSTM)
我们将应用预训练的词向量和含多个隐藏层的双向循环神经网络,来判断一段不定长的文本序列中包含的是正面还是负面的情绪。
首先导入所需的包或模块。
import collections
import os
import random
import time
import torch
from torch import nn
import torchtext.vocab as Vocab
import torch.utils.data as Data
from sklearn.model_selection import train_test_split
from tqdm import tqdm
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
读取数据
每个样本是一条评论及其对应的标签:1表示“正面”,0表示“负面”。
def load_data():
data = []
sample_num = 25000
with open('./data/positive_process.data', 'r', encoding='utf-8') as f:
sentences = f.readlines()
for sentence in sentences[:sample_num]:
words = [x for x in sentence.strip().split('\t')]
data.append([words, 0])
with open('./data/negative_process.data', 'r', encoding='utf-8') as f:
sentences = f.readlines()
for sentence in sentences[:sample_num]:
words = [x for x in sentence.strip().split('\t')]
data.append([words, 1])
random.shuffle(data)
return data
train_data, test_data = train_test_split(load_data(), test_size=0.2)
预处理数据
根据训练数据创建字典,这里过滤掉了出现次数少于5的词。
def get_vocab(data):
tokenized_data = [words for words, _ in data]
counter = collections.Counter([tk for st in tokenized_data for tk in st])
return Vocab.Vocab(counter, min_freq=5)
vocab = get_vocab(train_data)
print('# words in vocab:', len(vocab))
因为每条评论长度不一致所以不能直接组合成小批量,我们定义preprocess函数将每条文本中的词通过词典转换成词索引,然后通过截断或者补0来将每条文本长度固定成500。
def preprocess(data, vocab):
max_l = 500 # 将每条评论通过截断或者补0,使得长度变成500
def pad(x):
return x[:max_l] if len(x) > max_l else x + [0] * (max_l - len(x))
tokenized_data = [words for words, _ in data]
features = torch.tensor([pad([vocab.stoi[word] for word in words]) for words in tokenized_data])
labels = torch.tensor([score for _, score in data])
return features, labels
创建数据迭代器
现在,我们创建数据迭代器。每次迭代将返回一个小批量的数据。
batch_size = 64
train_set = Data.TensorDataset(*preprocess(train_data, vocab))
test_set = Data.TensorDataset(*preprocess(test_data, vocab))
train_iter = Data.DataLoader(train_set, batch_size, shuffle=True)
test_iter = Data.DataLoader(test_set, batch_size)
打印第一个小批量数据的形状以及训练集中小批量的个数。
for X, y in train_iter:
print('X', X.shape, 'y', y.shape)
break
print('#batches:', len(train_iter))
搭建循环神经网络模型
在这个模型中,每个词先通过嵌入层得到特征向量。然后,我们使用双向循环神经网络对特征序列进一步编码得到序列信息。最后,我们将编码的序列信息通过全连接层变换为输出。
class BiRNN(nn.Module):
def __init__(self, vocab, embed_size

本文介绍了一个基于中文新闻数据集的情感分析项目,利用预训练词向量和循环神经网络(LSTM),以及卷积神经网络(textCNN)进行文本分类,详细展示了数据预处理、模型搭建、训练和评估的全过程。
最低0.47元/天 解锁文章
6220

被折叠的 条评论
为什么被折叠?



