社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  机器学习算法

深度学习连载8:使用RNN对电影评论进行分类

Y叔 余光创 • 2 月前 • 155 次点击  

上一篇《深度学习连载7:循环神经网络RNN》就是我看视频学习的笔记,里面的图,都是视频的截图。学习之后,就要进入实战了,而这一篇,正是我的一次实践。


数据

下载和读入

下载自以下网址:

  • https://media.geeksforgeeks.org/wp-content/uploads/20250520152942314935/IMDB-Dataset.csv
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
import reimport pandas as pddf = pd.read_csv("data/IMDB-Dataset.csv", header=0, names=["text", "label"])
def tokenize(text: str):    text = text.lower()    text = re.sub(r"
"
, " ", text)
    text = re.sub(r"[^a-z0-9']+", " ", text)    return text.split()
df['text'] = df['text'].apply(tokenize)
df.head()

数据读进来后,先统一转成小写,并做一点简单清洗(比如把 
 去掉、把标点当作分隔符),然后再切分成单词,最终大概是这样子的:





text
label
0
[one, of, the, other, reviewers, has, mentioned...
positive
1
[a, wonderful, little, production, the, filming...
positive
2
[i, thought, this, was, a, wonderful, way, to, ...
positive
3
[basically, there's, a, family, where, a, littl...
negative
4
[petter, mattei's, love, in, the, time, of, mon...
positive

我们将positive转成1,把negative转成0,这样子进行编码:

  • 1
  • 2
  • 3
from sklearn.preprocessing import LabelEncoderle = LabelEncoder()df['label'] = le.fit_transform(df['label'])

整个文件有5万行,正面和负面评价各占一半,我们使用RNN将对电影评论进行正面和负面的分类。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
import matplotlib.pyplot as pltimport seaborn as snssns.set()
sns.countplot(x = "label", data=df)plt.show()

预处理

切分成训练集、测试集和验证集,这里使用stratify=df["label"],以保证类别比例严格一致。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
from sklearn.model_selection import train_test_split
train_data, test_data = train_test_split(    df, test_size=0.2, random_state= 42, stratify=df["label"])train_data, val_data = train_test_split(    train_data, test_size=0.1, random_state=42, stratify=train_data["label"])

因为神经网络要处理数字,而不是字符,所以我们要将字符搞成数字。首先是压缩一下数据,不把所有词都拿来用,先计算一下词的频率:

  • 1
  • 2
from collections import Countercounter = Counter(word for phrase in df["text"] for word in phrase)

我再按照频率进行排序,只用频率最高的前10万个词:

  • 1
  • 2
  • 3
  • 4
  • 5
N = 100000vocab = [w for w, _ in counter.most_common(N)]
PAD_IDX = 0UNK_IDX = 1

每个词给一个位置的下标,用一个词典来存。这里把 0 留给 padding,把 1 留给 unknown word(不在词表里的词)。

  • 1
word_to_index = {word: idx for idx, word in enumerate(vocab, start=2)}

这样子可以把一串单词的句子变成一串数字(下标),定义一个函数来干这个事情:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
def encode_and_pad(text, word_to_index, max_length, unk_idx=UNK_IDX, pad_idx=PAD_IDX):    encoded = [word_to_index.get(word, unk_idx) for word in text]    if len(encoded) > max_length:        encoded = encoded[:max_length]    else:        encoded += [pad_idx] * (max_length - len(encoded))
    return encoded
  1. 因为我们只用了前 10 万个词,所以句子里会出现“不在词表里”的词。这里用 UNK_IDX=1 来表示 unknown word。
  2. 句子设定一个统一的长度,如果太长,截断;如果太短,填0。
  • 1
  • 2
  • 3
  • 4
max_length = 200train_data['text'] = train_data['text'].apply(encode_and_pad, word_to_index=word_to_index, max_length=max_length)val_data['text'] = val_data['text'].apply(encode_and_pad, word_to_index=word_to_index, max_length=max_length)test_data['text'] = test_data['text'].apply(encode_and_pad, word_to_index=word_to_index, max_length=max_length)

这里设定长度为200,然后把句子转换成数字列表。

数据集和数据加载器

首先要定义一个DataSet的类来存储我们的数据,再传入DataLoader方便训练里加载数据。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
import torchfrom torch.utils.data import Dataset, DataLoader
class SentimentDataSet(Dataset):    def __init__(self, data):        self.texts = data['text'].values        self.labels = data['label'].values
    def __len__(self):        return len(self.texts)
    def __getitem__(self, idx):        text = self.texts[idx]        label = self.labels[idx]
        return torch.tensor(text, dtype=torch.long), torch.tensor(label, dtype=torch.long)        train_ds = SentimentDataSet(train_data) val_ds = SentimentDataSet(val_data)test_ds = SentimentDataSet(test_data)
bs = 64train_dl = DataLoader(train_ds, batch_size=bs, shuffle=True)val_dl = DataLoader(val_ds, batch_size=bs, shuffle=False)test_dl = DataLoader(test_ds, batch_size=bs, shuffle=False)
  • __init__:把数据存起来。
  • __len__:有多少样本。
  • __getitem__:把编码的文本和标签以tensor返回。

模型

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
import torch.nn as nn
class SentimentRNN(nn.Module):    def __init__(self, vocab_size, embed_size, hidden_size, output_size,                  num_layers=2, dropout=0.3, bidirectional=True, padding_idx=0):        super().__init__()        self.padding_idx = padding_idx        self.embedding = nn.Embedding(vocab_size, embed_size, padding_idx=padding_idx)        self.rnn = nn.RNN(embed_size, hidden_size, num_layers=num_layers,                           dropout=dropout if num_layers > 1 else 0.0,                          bidirectional=bidirectional, batch_first=True)        self.dropout = nn.Dropout(dropout)        self.fc = nn.Linear(hidden_size * (2 if bidirectional else 1),                             output_size)        self._init_weights()
    def _init_weights(self ):        for name, param in self.rnn.named_parameters():            if 'weight' in name:                nn.init.xavier_uniform_(param)            elif 'bias' in name:                nn.init.zeros_(param)        nn.init.xavier_uniform_(self.fc.weight)        nn.init.zeros_(self.fc.bias)                def forward(self, x):        embedded = self.embedding(x)        output, _ = self.rnn(embedded)        mask = (x != self.padding_idx).unsqueeze(-1)        output = output * mask        denom = mask.sum(dim=1).clamp(min=1)        pooled = output.sum(dim=1) / denom        dropped = self.dropout(pooled)        return self.fc(dropped)
  • nn.Embedding:把word index映射为长度为embed_size的向量,padding_idx=0告诉它在训练时可以忽略padding tokens。
  • nn.RNN:处理embedding序列来捕获依赖关系。
    • hidden_size:控制隐藏状态的大小
    • num_layers=2:堆两个RNN层
    • bidirectional=True:使用双向RNN
    • batch_first=True:表示输入的形状是(batch_size, seq_len, embed_size)
  • nn.Dropout(0.3):表示在训练时随机把30%的单元清零,以防止过拟合
  • nn.Linear:全连接层把RNN的输出映射到2个logits(positive/negative)
  • _init_weights():使用Xavier均匀分布初始化
    • 特别适合S型激活函数(Sigmoid、TanH)
    • 能有效维持各层激活层的方差,从而避免在前向传播和反向传播过程中出现梯度消失或爆炸的问题

初始化模型

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
vocab_size = len(vocab) + 2embed_size = 50 hidden_size = 64 output_size = 2
model = SentimentRNN(vocab_size, embed_size, hidden_size, output_size)

得到的模型是这样子的:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
SentimentRNN(


    
  (embedding): Embedding(100002, 50, padding_idx=0)  (rnn): RNN(50, 64, num_layers=2, batch_first=True, dropout=0.3, bidirectional=True)  (dropout): Dropout(p=0.3, inplace=False)  (fc): Linear(in_features=128, out_features=2, bias=True))

损失、优化器、调度器和准确率

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
loss_fn = nn.CrossEntropyLoss()
optim = torch.optim.Adam(model.parameters(), lr = 0.005)scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optim, mode='min', factor=0.5, patience=3)
def acc_fn(pred, y):    total, correct = 0, 0    predicted = pred.argmax(dim=1)    total += y.size(0)    correct += torch.eq(predicted, y).sum().item()
    return correct / total * 100
  • nn.CrossEntropyLoss:基本上是做分类计算损失的标准了。
  • Adam优化器:能够调整学习率,实现快速收敛。
  • scheduler调度器:在深度学习中主要用来动态调整学习率,前期使用较大的学习率快速收敛,后期减小学习率精细调参。调度器有预定义固定策略、自适应调度策略和自定义调度三种类型。这里用的ReduceLROnPlateau(基于验证损失的调度)属于自适应调度策略,mode参数决定监控指标的方向,min是当指标(如损失)停止下降时降低学习率;factor是学习率衰减的因子,new_lr = current_lr * factor;patience参数决定等待多少个epoch没有改善后才调整学习率。
  • 准确率:比较一下预测标签和实际标签相同的百分比。

训练模型

训练步骤

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train_step(model: torch.nn.Module,               data_loader,               loss_fn,               optimizer,               acc_fn,               device = device,               max_grad_norm=5.0):
    train_loss, train_acc = 0, 0    model.train()        # for batch, (X, y) in enumerate(data_loader):    for X, y in data_loader:        X, y = X.to(device), y.to(device)                optimizer.zero_grad()        y_pred = model(X)        loss = loss_fn(y_pred, y)
        loss.backward()        torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)        optimizer.step()                train_loss += loss.item()        train_acc += acc_fn(y_pred, y)
    train_loss /= len(data_loader)    train_acc /= len(data_loader)
    return train_loss, train_acc

和之前写的代码差不多,这次我返回值了,方便记录训练过程中的损失和准确率。另一个是使用了torch.nn.utils.clip_grad_norm_进行梯度裁剪。max_grad_norm是梯度裁剪的阈值,如果梯度范数超过此值,将对所有梯度进行缩放。计算梯度范数的类型可通过norm_type指定,默认是2,使用L2范数, ,如果total_norm > max_norm,则进行缩放:gradient = gradient * (max_norm / total_norm),否则梯度保持不变。

梯度裁剪能够防止梯度爆炸,特别是在RNN/LSTM等递归网络中,避免参数更新步长过大,能够稳定训练过程,使训练更加平滑。max_norm的参数选择范围一般在0.1-10之间,对于Transformer模型,常用1.0;对于RNN,常用5.0或10.0。

测试/评估步骤

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
def test_step(model,              data_loader,              loss_fn,              acc_fn,              device = device):
    test_loss, test_acc=0, 0    model.eval()    with torch.inference_mode():        for X, y in data_loader:            X, y = X.to(device), y.to(device)                        test_pred = model(X)            loss = loss_fn(test_pred, y)            test_loss += loss.item()            test_acc += acc_fn(test_pred, y)                    test_loss /= len(data_loader)        test_acc /= len(data_loader)
    return test_loss, test_acc

训练

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
from timeit import default_timer as timer device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
train_loss = []train_acc = []test_loss = []test_acc = []
epochs = 5
for epoch in range(epochs):    print(f"Epoch: {epoch}\n---")    start_time = timer()
    trloss, tracc = train_step(model=model,         data_loader=train_dl,         loss_fn=loss_fn,         optimizer=optim,        acc_fn=acc_fn,         device=device)    train_loss.append(trloss)    train_acc.append(tracc)    print(f"Train loss: {trloss:.5f} | Train accuracy: {tracc:.2f}")        teloss, teacc = test_step(model=model,         data_loader=val_dl,        loss_fn=loss_fn,        acc_fn=acc_fn,        device=device)    test_loss.append(teloss)    test_acc.append(teacc)        scheduler.step(teloss)    end_time = timer()        print(f"Val loss: {teloss:.5f} | Val accuracy: {teacc:.2f}\n")    print(f"Time elapsed: {end_time-start_time:.3f} seconds\n")

跑了5个epochs,训练效果还不错:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
Epoch: 0---Train loss: 0.42456 | Train accuracy: 79.85 Val loss: 0.33948 | Val accuracy: 85.29Time elapsed: 5.322 seconds
Epoch: 1---Train loss: 0.23394 | Train accuracy: 90.94 Val loss: 0.29529 | Val accuracy: 87.10Time elapsed: 5.055 seconds
Epoch: 2---Train loss: 0.14509 | Train accuracy: 94.65 Val loss: 0.33786 | Val accuracy: 86.33Time elapsed: 5.125 seconds
Epoch: 3---Train loss: 0.09957 | Train accuracy: 96.44  Val loss: 0.42086 | Val accuracy: 85.71Time elapsed: 4.966 seconds
Epoch: 4---Train loss: 0.06780 | Train accuracy: 97.57 Val loss: 0.46061 | Val accuracy: 86.09Time elapsed: 5.027 seconds

最后在验证集上的准确率有 86% 左右。

训练完成后,可以再跑一次测试集,得到最终的 test 指标:

  • 1
  • 2
  • 3
  • 4
  • 5
test_loss_value, test_acc_value = test_step(    model=model, data_loader=test_dl, loss_fn=loss_fn, acc_fn=acc_fn, device=device)print(f"Test loss: {test_loss_value:.5f} | Test accuracy: {test_acc_value:.2f}")# Test loss: 0.47108 | Test accuracy: 86.32

可视化

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
import numpy as npN = np.arange(epochs)
plt.style.use("ggplot")plt.figure(figsize = [10,8])plt.plot(N, train_loss, label="train_loss")plt.plot(N, test_loss, label="val_loss")plt.title("RNN: Training & Validation Loss")plt.xlabel("Epoch #", weight="bold")plt.ylabel("Loss", weight="bold")plt.legend()plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
plt.figure(figsize = [10,8])plt.plot(N, train_acc, label="train_acc")plt.plot(N, test_acc, label="val_acc")plt.title("RNN: Training & Validation Accuracy")plt.xlabel("Epoch #", weight="bold")plt.ylabel("Accuracy", weight="bold")plt.legend()plt.show()

通过可视化,感觉这个模型有点过拟合了。如果要进一步再做的话,可以 1)调小学习率,并且把ReduceLROnPlateau 的 patience 从 3 调到 1~2(因为现在只有5个epochs);2)加强正则化,一方面可以 提到dropout,另一方面可以在embedding层额外加一层nn.Dropout,也可以在Adam里加weight_decay=1e4;3)还可以换更稳的结构,把nn.RNN 换成 nn.LSTM 或 nn.GRU。所谓调参师嘛,调一调,试一试。

补充:更丰富的评估指标

除了 accuracy,实际更常用的还有 confusion matrix、precision/recall/F1。下面给一个最小可用的写法(把所有 batch 的预测收集起来再算):

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
import numpy as npfrom sklearn.metrics import classification_report, confusion_matrix
def collect_preds(model, data_loader, device):    model.eval()    y_true, y_pred = [], []    with torch.inference_mode():        for X, y in data_loader:            X, y = X.to(device), y.to(device)            logits = model(X)            pred = logits.argmax(dim=1)            y_true.append(y.cpu().numpy())            y_pred.append(pred.cpu().numpy())     return np.concatenate(y_true), np.concatenate(y_pred)
y_true, y_pred = collect_preds(model, test_dl, device=device)print(confusion_matrix(y_true, y_pred))print(classification_report(y_true, y_pred, target_names=["negative", "positive"]))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
[[4358  642] [ 730 4270]]              precision    recall  f1-score   support
    negative       0.86      0.87      0.86      5000    positive       0.87      0.85      0.86      5000
    accuracy                           0.86     10000   macro avg       0.86      0.86      0.86     10000weighted avg       0.86      0.86      0.86     10000

预测

现在训练了一个模型,我们就可以写一点影评的句子,然后用模型来预测是正面评价还是负面评价。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
def predict_sentiment(model, sentence):    text = tokenize(sentence)    encoded = encode_and_pad(text, word_to_index, max_length)    x = torch.tensor(encoded, dtype=torch.long)    x = x.to(device)    model.eval()    y = model(x.unsqueeze(0))    pred = torch.nn.functional.softmax(y, dim=1)    predicted = pred.argmax(dim=1)    res = 'positive' if predicted。item() == 1 else 'negative'


    
    prob = pred.squeeze(0)[predicted.item()].item()    print(f"Result: {res}, with probability of {prob:.4f}\n")    return res, prob

句子一样的处理,最终转成tensor,然后丢给模型,就可以实现预测。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
predict_sentiment(model, "I really hate this movie. It is really bad and sucks!")# Result: negative, with probability of 0.9980# # ('negative', 0.9979572296142578)
predict_sentiment(model, "This is such an awesome movie, I really love it!")# Result: positive, with probability of 1.0000# # ('positive', 1.0)

参考资料

  • https://www.geeksforgeeks.org/deep-learning/implementing-recurrent-neural-networks-in-pytorch/
  • https://medium.com/@jainilgosalia/building-an-rnn-for-sentiment-analysis-with-pytorch-5b80d9142bb8
  • https://www.kaggle.com/code/yogeshrampariya/imdb-classification-using-rnn-lstm-on-pytorch
  • https://medium.com/@jainilgosalia/optimizing-rnn-a-step-by-step-guide-7b61a8004349

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/200904