自己写词表

这一课在哪

上一课说了 embedding 是「按索引查表」。那索引从哪来?

这一课写那个对照表:词 → 编号。 这是整个项目里代码最绕的一块,但只有几百行里的几十行。

词表要解决的三个问题

问题

不解决会怎样

没见过的词怎么办

索引越界,直接报错

十万个只出现一次的词要不要收

词表爆炸,embedding 撑不下

句子长短不一怎么凑成一批

拼不成张量

四个特殊符号

这些是约定俗成的,占住编号 0、1、2、3:

符号

编号

作用

<pad>

0

填充,把短句补到一样长

<unk>

1

unknown,没见过的词

<bos>

2

begin of sentence,句子开头

<eos>

3

end of sentence,句子结尾

为什么 pad 一定要是 0

PyTorch 的 nn.Embedding 有一个参数 padding_idx=0, 意思是第 0 行的向量永远是 0,且不参与梯度更新。

这样 padding 的位置在计算里就是「什么都不贡献」。

把 pad 放在别的编号上,就得改 padding_idx。

分词:中文怎么切

英文按空格切就行。中文没有空格,三种做法:

做法

怎么做

词表大小

效果

按字切

每个汉字一个 token

几千

够用,最简单

按词切

用 jieba 之类的分词库

几万到几十万

更好,但多一个依赖

BPE / 子词

学出来的

几万

现在的主流(GPT 用的就是这个)

这一章按字切——不用装任何库,而且够用。

text = "这个电影太好看了"
print(list(text))
# ['这', '个', '电', '影', '太', '好', '看', '了']

按字切的代价

「电影」被拆成「电」和「影」两个 token,模型得自己学出它们合起来的意思。

好处是词表小、不会遇到未登录词——任何一个汉字都在表里。

坏处是序列变长:一句话 20 个字就是 20 步,RNN 得跑 20 次。

第一步:统计词频

import csv
from collections import Counter

def read_tsv(path):
    """读 ChnSentiCorp 格式:label \t text"""
    samples = []
    with open(path, encoding="utf-8") as f:
        reader = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
        next(reader)                          # 跳过表头
        for row in reader:
            if len(row) < 2:
                continue
            label = row[0].strip()
            text = row[1].strip()
            if label in ("0", "1") and text:
                samples.append((int(label), text))
    return samples

train = read_tsv("D:/main/AIchallenger2017/sentiment/train.tsv")
print(len(train))            # 9600
print(train[0][0], train[0][1][:30])

然后数每个字出现多少次:

counter = Counter()
for label, text in train:
    counter.update(text)

print(len(counter))                       # 多少个不同的字
print(counter.most_common(10))            # 最常见的 10 个
6000 多个不同的字
[('的', 21043), (',', 18044), ('了', 11532), ('。', 11366), ...]

第二步:按频率建表

PAD, UNK, BOS, EOS = "<pad>", "<unk>", "<bos>", "<eos>"

def build_vocab(samples, min_freq=2, max_size=10000):
    """
    min_freq: 出现少于这么多次的字,全部归到 <unk>
    max_size: 词表最多这么大,超出的也归到 <unk>
    """
    counter = Counter()
    for label, text in samples:
        counter.update(text)

    # 先放四个特殊符号
    itos = [PAD, UNK, BOS, EOS]

    # 按频率从高到低取
    for char, freq in counter.most_common():
        if freq < min_freq:
            break                          # most_common 已排序,后面更少
        if len(itos) >= max_size:
            break
        itos.append(char)

    stoi = {char: index for index, char in enumerate(itos)}
    return itos, stoi

itos, stoi = build_vocab(train)
print(len(itos))              # 词表大小
print(itos[:10])              # ['<pad>', '<unk>', '<bos>', '<eos>', ...]
print(stoi["的"])

min_freq 是干什么的

那个 6000 个字里,一半只出现一两次——多半是人名、错别字、生僻字。

每个都建一个 embedding 行,它们各自只会被更新一两次,学不到任何东西, 还白占参数。

min_freq=2 就是「只出现 1 次的全部扔掉,当成 <unk>」。

参数是怎么算的

词表 V = 6000,维度 d = 128
embedding 参数 = 6000 × 128 = 768,000

如果降到 V = 3000:3000 × 128 = 384,000
省了一半

所以 min_freq 和 max_size 是在「覆盖率」和「参数量」之间取舍。

第三步:编码

把一句话变成一个整数列表:

def encode(text, stoi, max_len=None):
    """句子 → 索引列表,自动加 <bos> 和 <eos>"""
    ids = [stoi[BOS]]
    for char in text:
        ids.append(stoi.get(char, stoi[UNK]))
    ids.append(stoi[EOS])

    if max_len is not None:
        ids = ids[:max_len]
    return ids

s = "这个电影太好看了"
print(encode(s, stoi))
# [2, 5, 12, 88, 301, 44, 7, 9, 3]

看三件事:

位置

是什么

开头 2

<bos>

中间

每个字的编号,没见过的变成 1

结尾 3

<eos>

第四步:padding 成一批

这是最容易写错的一步。一堆长度不同的句子要拼成一个矩阵:

def pad_batch(batch_ids, pad_id=0):
    """把一批长度不同的索引列表补到一样长"""
    max_len = max(len(ids) for ids in batch_ids)
    padded = []
    for ids in batch_ids:
        padded.append(ids + [pad_id] * (max_len - len(ids)))
    return padded

batch = [
    [2, 5, 12, 3],
    [2, 88, 3],
    [2, 5, 12, 88, 301, 3],
]
for row in pad_batch(batch):
    print(row)
[2, 5, 12, 3, 0, 0]
[2, 88, 3, 0, 0, 0]
[2, 5, 12, 88, 301, 3]

补在后面,不是前面

RNN 是从左往右读的,补在后面意味着模型先读完真内容, 再读到一串 0。

如果补在前面,模型一开始就吃 0,等于把开头的信息推远了。

约定:padding 一律补在末尾。

第五步:打包成一个 Dataset

import torch
from torch.utils.data import Dataset

class SentimentDataset(Dataset):
    def __init__(self, samples, stoi, max_len=128):
        self.samples = samples
        self.stoi = stoi
        self.max_len = max_len

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, index):
        label, text = self.samples[index]
        ids = encode(text, self.stoi, max_len=self.max_len)
        return torch.tensor(ids, dtype=torch.long), torch.tensor(label, dtype=torch.long)

注意 max_len=128——超过 128 个字的评论直接截断。

为什么要有它:

不截断

截断到 128

有一条 2000 字的评论时,整批都要补到 2000

最多 128

显存爆掉

可控

RNN 跑 2000 步,梯度早没了

128 步勉强能传

collate_fn:真正补 padding 的地方

DataLoader 默认会把每个样本堆成张量, 但长度不一样就堆不起来。所以要自己写一个 collate_fn:

from torch.nn.utils.rnn import pad_sequence

def collate_fn(batch):
    sequences, labels = zip(*batch)
    padded = pad_sequence(sequences, batch_first=True, padding_value=0)
    labels = torch.stack(labels)
    return padded, labels

loader = DataLoader(
    dataset,
    batch_size=32,
    shuffle=True,
    collate_fn=collate_fn,      # ← 关键
)

参数

作用

batch_first=True

输出 (B, L, ...),不是 (L, B)

padding_value=0

补 0,和 <pad> 的编号对上

这四行是整章最容易卡住的地方

不写 collate_fn,报错是 stack expects each tensor to be equal size。

写了但忘了 batch_first=True,形状变成 (L, B),后面接 nn.RNN 时整个错位, 而且不一定报错。

完整代码

import csv
from collections import Counter

import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset, DataLoader

PAD, UNK, BOS, EOS = "<pad>", "<unk>", "<bos>", "<eos>"


def read_tsv(path):
    samples = []
    with open(path, encoding="utf-8") as f:
        reader = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
        next(reader)
        for row in reader:
            if len(row) < 2:
                continue
            label, text = row[0].strip(), row[1].strip()
            if label in ("0", "1") and text:
                samples.append((int(label), text))
    return samples


def build_vocab(samples, min_freq=2, max_size=10000):
    counter = Counter()
    for _, text in samples:
        counter.update(text)

    itos = [PAD, UNK, BOS, EOS]
    for char, freq in counter.most_common():
        if freq < min_freq or len(itos) >= max_size:
            break
        itos.append(char)

    return itos, {c: i for i, c in enumerate(itos)}


def encode(text, stoi, max_len=128):
    ids = [stoi[BOS]]
    ids += [stoi.get(c, stoi[UNK]) for c in text]
    ids.append(stoi[EOS])
    return ids[:max_len]


class SentimentDataset(Dataset):
    def __init__(self, samples, stoi, max_len=128):
        self.samples = samples
        self.stoi = stoi
        self.max_len = max_len

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, index):
        label, text = self.samples[index]
        ids = encode(text, self.stoi, self.max_len)
        return torch.tensor(ids, dtype=torch.long), torch.tensor(label, dtype=torch.long)


def collate_fn(batch):
    sequences, labels = zip(*batch)
    padded = pad_sequence(sequences, batch_first=True, padding_value=0)
    return padded, torch.stack(labels)


base = "D:/main/AIchallenger2017/sentiment"
train = read_tsv(f"{base}/train.tsv")
itos, stoi = build_vocab(train, min_freq=2, max_size=10000)

print(f"词表大小 {len(itos)}")

dataset = SentimentDataset(train, stoi)
loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn)

for ids, labels in loader:
    print(ids.shape)       # torch.Size([32, 变长])
    print(labels.shape)    # torch.Size([32])
    break

这一课留下的三个数

数

值

含义

不同汉字

6000 多个

训练集里出现过的

词表大小

约 3000

min_freq=2 过滤之后

特殊符号

4 个

pad=0 / unk=1 / bos=2 / eos=3

下一课

数据能喂了。下一课手写一个 RNN 层—— 不用 nn.RNN,自己写那五行公式,看清里面到底发生了什么。