训练文本分类器
进行嵌入、池化并预测情感
训练文本分类器 是 CoddyKit 上的免费 Deep Learning Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Deep Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Deep Learning Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Goal: Predict a Label
A text classifier reads a sentence and predicts a label, like positive or negative sentiment for a movie review. 🎬
Step One: Encode the Text
Reuse your pipeline: tokenize each review and map tokens to ids, turning every sentence into a list of integers.
Step Two: Embed the Ids
Feed those ids into an embedding layer. Each review becomes a sequence of dense word vectors the model can process.
self.emb = nn.Embedding(vocab_size, 32)Step Three: Pool the Vectors
A sentence has many vectors but you need one. Pooling, often a mean over the words, collapses them into a single vector.
pooled = vecs.mean(dim=1) # average over the sequenceStep Four: A Linear Head
Send the pooled vector through a linear layer to produce one score per class. These raw scores are called logits.
self.fc = nn.Linear(32, num_classes)Assemble the Model
Stack embed, pool, and the linear head in a forward method. That is a complete, tiny text classifier.
def forward(self, ids):
x = self.emb(ids).mean(dim=1)
return self.fc(x)Pick the Loss
For multiclass labels use cross-entropy loss. It expects raw logits and the integer class index as the target.
loss_fn = nn.CrossEntropyLoss()Choose an Optimizer
An optimizer like Adam updates the embedding and linear weights together as it minimizes the loss.
opt = torch.optim.Adam(model.parameters(), lr=1e-3)The Training Loop
For each batch: forward, compute loss, backward, and step. Repeat over the data for several epochs.
logits = model(ids)
loss = loss_fn(logits, labels)
loss.backward()
opt.step()Make a Prediction
At inference, take the class with the highest logit using argmax to get the predicted label for new text.
pred = model(ids).argmax(dim=1)Measure Accuracy
Compare predictions to true labels to compute accuracy. Watch it climb as the embedding learns sentiment patterns.
Quick Check
In this classifier, what turns a sequence of word vectors into one vector?
Recap
You embed ids, pool them into one vector, classify with a linear head, and train with cross-entropy to label text. ✅
常见问题解答
「训练文本分类器」课时是免费的吗?
是的 — 「训练文本分类器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Deep Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Deep Learning Academy 课程共包含 4 节课。
「训练文本分类器」这节课中我会学到什么?
进行嵌入、池化并预测情感 你通过在浏览器中直接运行的动手代码来练习 Deep Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Deep Learning Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Deep Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「训练文本分类器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Deep Learning Academy 课中编写并运行代码吗?
能。每节 Deep Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。