预测与评估

这一课在哪

模型训完了。这一课看它到底多好、错在哪。

二分类的评估比后面的翻译任务简单得多——翻译要用 BLEU, 这里只需要准确率和混淆矩阵。

测试集

model.eval()
correct, total = 0, 0
confusion = torch.zeros(2, 2, dtype=torch.int)

with torch.no_grad():
    for ids, labels, lengths in test_loader:
        ids = ids.to(device)
        labels = labels.to(device)

        preds = model(ids, lengths).argmax(dim=1)
        correct += (preds == labels).sum().item()
        total += labels.size(0)

        for true_label, pred_label in zip(labels.cpu(), preds.cpu()):
            confusion[int(true_label), int(pred_label)] += 1

print(f"测试集 {100 * correct / total:.2f}%")
print(confusion)
测试集 83.50%
tensor([[507,  91],
        [107, 495]])

读混淆矩阵

真实 \ 预测

负面(0)

正面(1)

合计

负面

507

91

598

正面

107

495

602

合计

614

586

1200

三个指标:

指标

算法

值

准确率

(507+495)/1200

83.50%

负面召回

507/598

84.8%

正面召回

495/602

82.2%

两类差不多,没有偏。这是好事—— 说明模型没学会「全猜一个类」这种偷懒策略。

tp = confusion[1, 1].item()      # 正面判对
fp = confusion[0, 1].item()      # 负面被判成正面
fn = confusion[1, 0].item()      # 正面被判成负面

precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)

print(f"精确率 {precision:.3f}   召回 {recall:.3f}   F1 {f1:.3f}")
精确率 0.845 召回 0.822 F1 0.833

找几个错例看

光看数字不知道问题在哪。把判错的捞出来:

def find_errors(model, samples, stoi, n=10):
    model.eval()
    errors = []

    for label, text in samples:
        ids = encode(text, stoi, max_len=128)
        tensor = torch.tensor([ids], dtype=torch.long, device=device)
        lengths = torch.tensor([len(ids)])

        with torch.no_grad():
            pred = model(tensor, lengths).argmax(dim=1).item()

        if pred != label and len(errors) < n:
            errors.append((label, pred, text))

    return errors

for label, pred, text in find_errors(model, test_raw, stoi):
    print(f"真 {label} 判 {pred}  {text[:50]}")

为什么停在 83%

三个原因,按影响排序:

原因

说明

怎么改

① 只看最后一步

一句话最后几个字往往是「还行吧」「不怎么样」, 但前面的详细描述全丢了

用 attention 加权,或双向 RNN

② 单层 RNN 记不住

长评论前 100 个字的信息,到末尾基本没了

LSTM / GRU(下一章)

③ 按字切

「不」「错」分开是两个 token,模型要自己学「不错 = 好」

用分词,或用 BERT 这类预训练模型

第三条最要命

情感分析里否定词是关键:「好」和「不好」只差一个字。

按字切的话,模型看到「不」和「好」两个独立 token, 必须靠 h 把「不」记住一整个词的距离。

单层 RNN 记这么远很吃力——这就是为什么 83% 上不去。

单句预测

训练完之后,实际用起来是这样:

def predict(model, text, stoi, device, max_len=128):
    model.eval()

    ids = encode(text, stoi, max_len=max_len)
    tensor = torch.tensor([ids], dtype=torch.long, device=device)
    lengths = torch.tensor([len(ids)])

    with torch.no_grad():
        logits = model(tensor, lengths)
        probs = torch.softmax(logits, dim=1)

    positive = probs[0, 1].item()
    label = "正面" if positive > 0.5 else "负面"
    return label, positive

for text in [
    "这家酒店太棒了,服务很好,下次还来",
    "房间又小又脏,再也不会来了",
    "还行吧,没什么特别的",
]:
    label, score = predict(model, text, stoi, device)
    print(f"{label}  {score:.3f}   {text}")
正面  0.912   这家酒店太棒了,服务很好,下次还来
负面  0.887   房间又小又脏,再也不会来了
正面  0.541   还行吧,没什么特别的

输入

输出

看什么

明显正面

0.912

很自信

明显负面

0.887

很自信

「还行吧」

0.541

接近 0.5,模型自己也不确定

0.541 这个数很有信息量

「还行吧」本来就是中性的,人也不好判断。

模型给出接近 0.5 的概率,说明它学到了「模棱两可」这件事。

如果它给出 0.99,反而说明模型太自信、可能在瞎猜。

三个调用时的坑

① 忘了 model.eval()

model.eval()          # ← 别忘
with torch.no_grad():  # ← 也别忘
    logits = model(tensor, lengths)

不设 eval(),dropout 还开着,同一个句子每次预测结果都不一样。

② batch 维度

# ✗ 错:shape (L,)
tensor = torch.tensor(ids)

# ✓ 对:shape (1, L)
tensor = torch.tensor([ids])

模型期望 (B, L),少一个维度直接报错或者形状错乱。

③ 词表必须和训练时一致

# 训练时保存
torch.save({
    "state_dict": model.state_dict(),
    "itos": itos,              # ← 词表也要存
    "config": {"embed_dim": 128, "hidden_size": 64},
}, "sentiment.pt")

# 预测时加载
ckpt = torch.load("sentiment.pt", map_location=device)
itos = ckpt["itos"]
stoi = {c: i for i, c in enumerate(itos)}

词表不存 = 模型废了

模型里的 embedding 是按索引存的。

如果加载时重新建了一个词表,「的」的索引从 12 变成 15, 那第 12 行权重对应的就是另一个字。

不会报错,但输出全是垃圾。

这一课的三个数

数

值

含义

测试准确率

83.50%

二分类,瞎猜 50%

两类召回

84.8% / 82.2%

没有偏向某一类

「还行吧」

0.541

模型知道自己不确定

下一课

习题:数词表大小的影响、判断该不该用 packing、找出训练代码里的三个错。