跳到正文

题解

B3759 [信息与未来 2021] 文本分类

GoodCoder666约 33 分钟
原文
文章信息与版本

文章信息

发布
2025年3月17日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 33 分钟
获赞
26
题目
B3759

版本

  1. v1当前

本题直接计算单词最大长度即可通过,然而我想借此题给各位介绍一些自然语言处理 (NLP) 的基本概念和方法。

于是,我们将借助 循环神经网络 (RNN) 模型来完成文本分类任务。

楼上 @FastIO_DP 的做法也使用了基于机器学习的方法,可惜这种方法只能解决非常简单的任务,对通用型任务无能为力。可以证明,将所有嵌入向量平均的方法等价于对字母出现概率的逻辑回归,也就是说,它仅对词频进行了建模,并没有考虑到前后字词的关联性。

基础知识 & 问题形式化

我们用 监督学习 的方法来解决此问题。它可以描述为:通过训练集 {(x1,y1),…,(xN,yN)}\{(x_1,y_1),\dots,(x_N,y_N)\} 进行学习,建立从输入空间 XX 到输出空间 YY 的映射 f:X→Yf : X\to Y。在此题中,XX 为所有合法句子的集合,Y={English,Pinyin}Y=\{\text{English}, \text{Pinyin}\}(后面分别用 00 和 11 替代)。找到的映射 ff 就是我们的模型。

在机器学习中,模型通常是固定形式的,而其中不确定的参数 θ\boldsymbol \theta 通过学习算法得到,这种称为 参数化模型,记作 fθf_{\boldsymbol \theta}。

上面讲的可能有点抽象,我们举个例子,用 y=kx+by=kx+b 去拟合数据点 {(x1,y1),…,(xN,yN)}\{(x_1,y_1),\dots,(x_N,y_N)\}:

  • 需要的映射:f:R→Rf : \R \to \R。

  • 参数:θ=(k,b)\boldsymbol \theta = (k,b)。

  • 模型:fθ(x)=kx+bf_{\boldsymbol \theta}(x)=kx+b,即 fθ(x)=θ1x+θ2f_{\boldsymbol \theta}(x)=\boldsymbol \theta_1 x+\boldsymbol \theta_2。

  • 根据 最小二乘法1 的原理,我们希望最小化:

    L=1N∑i=1N(f(xi)−yi)2\mathcal{L} = \frac{1}{N} \sum_{i=1}^N (f(x_i)-y_i)^2

    显然,在数据集确定的情况下,L\mathcal{L} 的取值只跟 θ\boldsymbol \theta 有关。它表示对于每个训练数据点,模型预测与实际值的误差的平方的平均值。这个数越小,说明模型整体越能反映数据的实际趋势。

  • 使用梯度下降法找到最优的 θ\boldsymbol \theta,具体可以参考我的博客。

  • 损失函数(目标函数):均方误差 (MSE) 函数。

  • 学习算法(优化器):梯度下降法 (GD)。

  • 其中一些不能被自动优化的数值称为超参数,例如 θ\boldsymbol \theta 中共有 22 个参数,22 这个值无法在学习过程中改变。这些需要用人类智慧进行设定,通常凭借经验即可获得不错的结果。

大家可以尝试动手实现上面的例子,相信会对理解监督学习的过程有很大帮助。

我们从中获得几点启发:

  • 数据集必须有效。 高质量的数据才能驱动模型学习到正确的“知识”。
  • 损失函数必须连续。 反之,梯度下降法将无法正常工作。
  • 模型要适合数据。 例如不能用一个线性模型拟合指数数据(欠拟合),或者用一个高次多项式拟合带噪声的二次函数数据点(过拟合)。2

以上知识对大语言模型 (LLM) 同样适用,希望能对各位理解 AI 原理有所启发。

回到题目,我们要解决的问题称为 二分类问题。模型将输出其认为样本属于正类(Pinyin\text{Pinyin})的概率:

f(x)=P(x∈Pinyin)∈[0,1]f(x)=P(x \in \text{Pinyin}) \in [0, 1]

当 f(x)>0.5f(x)>0.5 时就判定为正类,反之亦然。

一般来说,此类任务中我们会使用 Binary Cross Entropy(BCE,二元交叉熵) 损失函数:

L=−1N∑i=1N[yilog⁡f(xi)+(1−yi)log⁡(1−f(xi))]\mathcal{L} = -\frac{1}{N} \sum_{i=1}^N \left[y_i \log f(x_i) + (1-y_i) \log (1-f(x_i))\right]

请读者自行思考三个问题:

  • BCE 的式子在表达什么?
  • BCE 相比 MSE 有什么好处?
  • 为什么不将模型的预测准确率作为训练目标?

本部分到此为止!下面我们使用 PyTorch 训练模型,并使用 NumPy/C++ 进行推理。请确保你的 Python 环境中包含 torch、datasets 和 tqdm 库。限于篇幅,本题解不介绍这些工具库的具体使用方法,如果不会用可以让 AI 解释我的示例代码。

准备数据

对于此题,我们可以考虑手动构造一个较小的语料库3供训练,但为了方法的通用性,我们从大型公开语料库中合成数据:

  • 英文:采用 WikiText,来自维基百科的英文词条。

  • 中文:采用 SogouNews,来自搜狗新闻,且全部提前转换成了拼音,减少预处理难度。

二者数据量都很大,我们只取其中一小部分用于训练模型。

词元化 (Tokenization)

一般来说,我们会在 NLP 任务中将文本分割为 词元 (Token) 以减小模型学习难度。大多数任务中,一个单词被作为一个词元。但由于此题任务难度小,且不适合使用大型的词元库,所以将一个字符(小写英文字母或空格)作为一个词元,仅有 2727 个,以减小模型复杂度。

语料库整理

两个语料库都由多段连续的文本或句子组成。此处为了简单起见,我们直接将来自不同位置的文本用一个空格连接,以便减小训练代码难度。(这样做也是因为此任务无需关注上下文关系)

Python
# loader.py
import os

os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com/'

import re

import numpy as np
from datasets import load_dataset
from tqdm import tqdm

def load_wikitext(num_lines=10000):
    ds = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1', split='train')[:num_lines]['text']
    with tqdm(ds, desc='Loading wikitext') as pbar:
        res = []
        for line in pbar:
            line = line.strip()
            if not line or line.startswith('='):
                continue
            words = line.lower().split()
            res.extend(word for word in words if word.isalpha() and word.isascii())
        res = ' '.join(res)
        print(f'Loaded {len(res)} chars from wikitext')
        return res

pinyin_pattern = re.compile(r'[a-z]+\d[a-z]*')
def load_sgn(num_lines=1000):
    ds = load_dataset('community-datasets/sogou_news', split='test')[:num_lines]['content']
    with tqdm(ds, desc='Loading sogou_news') as pbar:
        res = []
        for line in pbar:
            words = line.split()
            for word in words:
                if pinyin_pattern.fullmatch(word):
                    word = ''.join(ch for ch in word if ch.isalpha())
                    res.append(word)
        res = ' '.join(res)
        print(f'Loaded {len(res)} chars from sogou_news')
        return res

def tokenize(text):
    arr = np.frombuffer(text.encode('ascii'), dtype=np.uint8)
    return np.where(arr == 32, 0, arr - 96).astype(np.uint32)

def build_dataset():
    en, zh = load_wikitext(), load_sgn()
    en, zh = tokenize(en), tokenize(zh)
    en_pos = np.flatnonzero(en[:-260] == 0) + 1
    zh_pos = np.flatnonzero(zh[:-260] == 0) + 1
    return en, zh, en_pos.tolist(), zh_pos.tolist()

数据集会从 Hugging Face Hub 上下载,第一次导入需要等待一段时间。

对外提供的接口为 tokenize 和 build_dataset。前者将文本转换为数字序列(词元化),后者将英文和拼音语料库分别加载到内存中,并返回它们的词元化结果和分隔符位置。

选择模型

RNN4 是最简单的语言模型。它通过循环结构处理序列数据,每个时间步5 tt 的隐藏状态 ht\boldsymbol{h}_t 由当前输入 xt\boldsymbol{x}_t 和前一状态 ht−1\boldsymbol{h}_{t-1} 共同决定:

ht=tanh⁡(Wxhxt+Whhht−1+bh)\boldsymbol{h}_t = \tanh(\boldsymbol{W}_{xh} \boldsymbol{x}_t + \boldsymbol{W}_{hh} \boldsymbol{h}_{t-1} + \boldsymbol{b}_h)

输出正类(Pinyin\text{Pinyin})概率:

y=σ(WhyhT+by)y = \sigma(\boldsymbol{W}_{hy} \boldsymbol{h}_T + \boldsymbol{b}_y)

其中 σ\sigma 为 sigmoid 函数:

σ(x)=11+e−x\sigma(x) = \frac {1} {1+e^{-x}}

直观上,这类模型的设计很符合人类的阅读方式。你想想,你理解一个句子过程大体上是不是这样的:

  • 从前往后,依次读取每个字(x1→⋯→xT\boldsymbol{x}_1 \to \dots \to \boldsymbol{x}_T)。
  • 分别根据读到字的含义,迭代地基于原来的理解(ht−1\boldsymbol{h}_{t-1})和新的字(xt\boldsymbol{x}_t)更新对整个句子的理解(ht\boldsymbol{h}_t)。
  • 根据最终的理解(hT\boldsymbol{h}_T),得出需要的信息(yy)。

于是有模型部分代码:

Python
# net.py
import torch
from torch import nn

class MiniTextRNN(nn.Module):
    def __init__(self, embed_size=4, hidden_size=4, num_layers=1):
        super().__init__()
        self.embedding = nn.Embedding(27, embed_size)
        self.rnn = nn.RNN(embed_size, hidden_size, num_layers=num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        x = self.embedding(x)
        out, _ = self.rnn(x)
        out = self.fc(out)
        return out.squeeze(-1)

    def predict(self, x):
        with torch.inference_mode():
            x = self.embedding(x)
            _, h = self.rnn(x)
            out = self.fc(h)
            return torch.sigmoid(out)

这里 forward 返回对所有时间步中隐藏状态分别应用预测层的结果,predict 返回最终状态(hT\boldsymbol{h}_T)的预测结果。

训练

训练的流程非常简单,从数据集中反复获得采样并对样本进行梯度下降即可。这里采样的方法较为简单,从语料库中随机获得 NN 个长度为 LL 的字串(确保开头不是空格),构成一批样本(batch)。

一些超参数的选择主要凭经验(也需要少量实验):

  • 批大小(batch size):N=256N=256
  • 采样长度(sample length):L=64L=64
  • 训练轮数(epochs):50005000
  • 优化器(optimizer):Adam
  • 学习率(learning rate):初始 10−210^{-2},每 10001000 轮减半
  • 权重衰减(weight decay,类似于 L2 正则化):λ=2×10−4\lambda = 2\times 10^{-4}

如果直接按上述方法训练模型,可以通过此题。然而,它容易误判一些短句,比如 i sing a song、see you again 等。

合理推测这种问题是模型过度依赖句子长度(L=64L = 64),从而忽略一些语言特征导致的。为了提升它在短句上的表现,我们作出如下修改:

  • 训练目标改为:对句子的每个前缀(而不是只有整句)分类,最小化加权总损失(仍采用 BCE)。

  • 权重计算:i∈[0,L)i\in [0,L) 表示句中位置,wiw_i 表示位置权重,mim_i 是中间量

    mi=exp⁡(−0.04i)wi=mi∑mim_i = \exp(-0.04i) \\ w_i = \frac {m_i} {\sum m_i}

这样,通过给短前缀赋予更高权重,模型能学会通过更有限的信息完成任务,提升了泛化能力。下面给出完整训练代码实现。

Python
# train.py
import random

import torch
from torch import nn, optim
import torch.nn.functional as F

from loader import build_dataset
from net import MiniTextRNN

torch.manual_seed(42)
random.seed(42)

en_set, zh_set, en_pos, zh_pos = build_dataset()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
en_set, zh_set = torch.LongTensor(en_set), torch.LongTensor(zh_set)

def _sample_from_dataset(dataset, start_positions, batch_size, sample_len):
    return torch.stack([
        dataset[i: i + sample_len]
        for i in random.sample(start_positions, batch_size)
    ])

epochs = 5000
batch_size = 256
sample_len = 64

def sample():
    half_b = batch_size // 2
    en_samples = _sample_from_dataset(en_set, en_pos, half_b, sample_len)
    zh_samples = _sample_from_dataset(zh_set, zh_pos, half_b, sample_len)
    samples = torch.cat([en_samples, zh_samples], dim=0)
    labels = torch.zeros(batch_size, dtype=torch.float32)
    labels[half_b:] = 1
    return samples, labels

model = MiniTextRNN().to(device).train()
optimizer = optim.Adam(model.parameters(), lr=1e-2, weight_decay=2e-4)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1000, gamma=0.5)

weights = F.softmax(-0.04 * torch.arange(sample_len, dtype=torch.float32, device=device), dim=0)
weights = weights.unsqueeze(0).expand(batch_size, -1)
weights.requires_grad_(False)

loss = nn.BCEWithLogitsLoss(weight=weights, reduction='sum')

for epoch in range(epochs):
    inputs, targets = sample()
    inputs, targets = inputs.to(device), targets.to(device)
    optimizer.zero_grad()
    outputs = model(inputs)
    targets = targets.unsqueeze(1).expand_as(outputs)
    l = loss(outputs, targets) / batch_size
    l.backward()
    optimizer.step()
    scheduler.step()
    print(f'Epoch {epoch + 1}/{epochs}, Loss: {l.item()}')

model.eval()
torch.save(model.state_dict(), 'model.pth')

在 CPU 上完整运行需要 1~2min 时间,若有可用 NVIDIA GPU 则会快很多。模型参数会以 PyTorch 格式保存在 model.pth 中。

推理(PyTorch)

推理 指使用训练好的模型进行预测,故不会修改模型参数。下面给出一个非常简单的交互式推理代码:

Python
# eval.py
import torch
from net import MiniTextRNN
from loader import tokenize

model = MiniTextRNN()
model.load_state_dict(torch.load('model.pth'))
model.eval()

while True:
    text = input('> ')
    seq = torch.LongTensor(tokenize(text)).unsqueeze(0)
    pred = model.predict(seq).item()
    if pred > 0.5:
        label = 'Pinyin'
    else:
        label = 'English'
        pred = 1 - pred
    print(f'{label} [P = {pred:.2f}]')

运行即可输入句子并验证结果(预测概率也会显示)。

导出参数

由于洛谷上不能使用 PyTorch,我们必须将参数导出为普通数组以便复制到其他推理方法中。

Python
# export_params.py
import torch
from net import MiniTextRNN

model = MiniTextRNN()
model.load_state_dict(torch.load('model.pth', map_location='cpu'))

params = [
    param.tolist()
    for param in model.parameters()
]

print(params)

推理(NumPy)

NumPy 作为通用且高效的科学计算库,非常适合实现神经网络推理(洛谷上也支持)。推理代码如下:

Python
# forward.py
import numpy as np

def predict(x, params):
    batch_size, seq_len = x.shape
    
    # Embedding
    embedding_weight = params[0]
    x_embedded = embedding_weight[x]
    
    W_ih = params[1].T
    W_hh = params[2].T
    b_total = params[3] + params[4]
    
    hidden_size = W_hh.shape[0]
    h = np.zeros((batch_size, hidden_size))
    
    # RNN
    for t in range(seq_len):
        x_t = x_embedded[:, t, :]
        h = np.tanh(x_t @ W_ih + h @ W_hh + b_total)
        
    fc_weight = params[5].T
    fc_bias = params[6]

    # Linear
    out = h @ fc_weight + fc_bias
    return 1 / (1 + np.exp(-out))

def tokenize(text):
    return [0 if c == ' ' else ord(c) - 96 for c in text]

params = ... # 把 export_params.py 的输出复制到这里
for i, param in enumerate(params):
    params[i] = np.array(param, dtype=np.float32)

T = int(input())
sentences = []
cutoff = 16

for _ in range(T):
    s = input()
    s = s[s.find(' ') + 1:]
    sentences.append(tokenize(s[:cutoff]))

batch = np.array(sentences, dtype=np.int32)
preds = predict(batch, params).flatten()

for p in preds:
    print('Pinyin' if p > 0.5 else 'English')

为了将所有输入数据塞进一个 batch 中,我们定义 cutoff = 16 表示只取每个句子的前 1616 个字符进行推理。受益于前面的短句训练,这样缩句已经足够了。

这份代码符合题目交互格式,可以直接提交并获得 AC。

推理(C++)

最后,是 OIer 最喜欢的 —— 原生 C++ 版本推理代码。同样,将 export_params.py 的输出复制到对应位置即可。这里给出带参数的版本:

C++
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;

const int cutoff = 16;

vector<int> tokenize(const string &text) {
    vector<int> tokens;
    for (char c : text) {
        tokens.push_back(c == ' '? 0 : c - 'a' + 1);
    }
    return tokens;
}

struct Params {
    vector<vector<float>> embedding;
    vector<vector<float>> W_ih;
    vector<vector<float>> W_hh;
    vector<float> b_total;
    vector<float> fc_weight;
    float fc_bias;
};

Params loadParams() {
    Params params;
    params.embedding = {{1.8028215169906616, 0.9283891916275024, 1.3205686807632446, -1.5752028226852417}, {0.13235650956630707, -0.49311327934265137, -0.9034576416015625, -1.172258973121643}, {0.488021582365036, 0.7543725371360779, -0.445336252450943, 0.6823800206184387}, {0.24799521267414093, -0.06231396645307541, -0.850423276424408, 0.47710537910461426}, {0.6099422574043274, -0.16763363778591156, -0.8439192175865173, 0.6677266359329224}, {0.8494492173194885, -0.13217075169086456, 0.6258174180984497, 1.569193720817566}, {0.30578163266181946, 0.6655067205429077, -0.21990719437599182, 0.6016054153442383}, {-0.5038883090019226, -0.5056541562080383, 0.05960218608379364, -0.12365201860666275}, {-1.088889241218567, -0.576884388923645, -0.0727449506521225, 1.2157354354858398}, {-0.5948517322540283, 0.09637022763490677, -0.2701537609100342, -0.6761443018913269}, {-0.404205858707428, -0.2761806547641754, 0.8516933917999268, -0.46787896752357483}, {0.6484190225601196, 0.5022299289703369, -0.0976589098572731, 0.669188916683197}, {0.4647216796875, 0.3021875023841858, -0.6405024528503418, 0.6796223521232605}, {0.3592414855957031, 0.18491922318935394, -0.6801095604896545, 0.5701507329940796}, {-0.9694885015487671, -0.14524048566818237, 0.03966279700398445, 0.16804799437522888}, {-0.740732729434967, 0.6608019471168518, -0.40265488624572754, -1.0690840482711792}, {0.10779128223657608, 0.6879157423973083, -0.2754943370819092, 0.9154365658760071}, {0.4958310127258301, -0.2278299331665039, 0.2521037757396698, 0.2962592542171478}, {0.7540019750595093, 0.8513333201408386, -0.46456143260002136, 0.36205658316612244}, {0.5148546099662781, -0.01420197356492281, -1.3858643770217896, 0.37393471598625183}, {0.4115105867385864, 1.4900071620941162, -1.0104691982269287, 0.8417065143585205}, {-0.4887521266937256, -0.022634167224168777, -0.3625696897506714, -0.8713006973266602}, {-0.839846670627594, 0.44619613885879517, -0.48624110221862793, -0.1636740118265152}, {0.2647571563720703, 0.693376362323761, -0.12427894026041031, 1.079669713973999}, {0.04795406758785248, -0.3749895393848419, 0.7033652663230896, 0.6426048874855042}, {-0.7549335956573486, 0.5020769238471985, 1.583930253982544, 1.0305057764053345}, {-0.31936517357826233, -0.5509432554244995, 0.5316606760025024, 0.46490678191185}};
    params.W_ih = {{-0.3061768114566803, -0.5796734690666199, -0.23363934457302094, -0.6856022477149963}, {0.8776503205299377, 0.2878395915031433, 0.4609214663505554, 0.3076168894767761}, {-0.3890216648578644, 0.415404349565506, -0.031227510422468185, -1.534371018409729}, {-0.7136509418487549, -0.6914500594139099, 0.7908886075019836, -0.7499666213989258}};
    params.W_hh = {{0.6976242065429688, 0.6702086925506592, -0.36442238092422485, 0.52286297082901}, {0.3029521107673645, 0.8078854084014893, -0.41114476323127747, 1.4449198246002197}, {0.9325374960899353, -2.2087032794952393, 1.3442336320877075, -0.17874063551425934}, {1.2263154983520508, -0.0513387992978096, -0.5691488981246948, 0.45193809270858765}};
    params.b_total = {0.634063720703125, -0.10535888373851776, -0.18860894441604614, -0.8973617553710938};
    params.fc_weight = {3.1700961589813232, 3.0720882415771484, -2.5844953060150146, 4.052948474884033};
    params.fc_bias = 1.1022119522094727;
    return params;
}

float sigmoid(float x) {
    return 1.0f / (1.0f + exp(-x));
}

float rnn_forward(const vector<int> &tokens, const Params &params) {
    int embed_dim = params.embedding[0].size();
    int hidden_size = params.b_total.size();
    int seq_len = min((int)tokens.size(), cutoff);

    vector<float> h(hidden_size, 0.0f);

    for (int t = 0; t < seq_len; t++) {
        // Embedding
        const vector<float> &embed = params.embedding[tokens[t]];

        // RNN cell
        vector<float> new_h(hidden_size, 0.0f);
        for (int j = 0; j < hidden_size; j++) {
            float s = params.b_total[j];
            for (int k = 0; k < embed_dim; k++) {
                s += embed[k] * params.W_ih[j][k];
            }
            for (int k = 0; k < hidden_size; k++) {
                s += h[k] * params.W_hh[j][k];
            }
            new_h[j] = tanh(s);
        }
        h = new_h;
    }

    // Linear
    float out = params.fc_bias;
    for (int j = 0; j < h.size(); j++) {
        out += h[j] * params.fc_weight[j];
    }
    return sigmoid(out);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    const Params params = loadParams();
    
    while (T--) {
        string s;
        getline(cin, s);
        size_t pos = s.find(' ');
        s = s.substr(pos + 1, cutoff);
        vector<int> tokens = tokenize(s);
        float pred = rnn_forward(tokens, params);
        cout << (pred > 0.5f ? "Pinyin" : "English") << '\n';
    }
    return 0;
}

总结

我希望能通过这篇题解抛砖引玉,期待更多大佬提出更优秀的做法~

脚注

  1. https://zh.wikipedia.org/wiki/%E6%9C%80%E5%B0%8F%E4%BA%8C%E4%B9%98%E6%B3%9 回到正文↩

  2. https://www.cnblogs.com/zhhfan/p/10476761.html 回到正文↩

  3. 由连续的自然语言文本组成的数据集一般称为“语料库”。 回到正文↩

  4. https://en.wikipedia.org/wiki/Recurrent_neural_network 回到正文↩

  5. 输入序列中的一个词元对应一个时间步。按顺序将输入序列中每个词元分别输入 RNN 即可迭代到最终的隐藏状态。 回到正文↩