A small incident classifier
Build an Embedding → masked mean → Linear model, then check shapes, PAD, UNK and a short CPU training run.
Lesson contents
From tokens to indices
In the NumPy lesson, we chose features by hand: counts of characters, words and distinct words. They helped us learn numeric tables. The final classifier uses a different representation: the model learns a set of numbers for each token instead of receiving fixed length counts.
Here, a token means a word extracted from text. The vocabulary assigns an
integer to each known token. UNK handles unknown words, while PAD fills
short sequences to a common length. In this project, the PAD index is 0
and the UNK index is 1.
An encoding example:
"api медленно отвечает" → [17, 42, 8, PAD, PAD]
"новый_термин" → [UNK, PAD, PAD, PAD, PAD]
PAD and UNK must have different indices. An unknown word carries a signal;
padding is a technical placeholder.
Embedding
Here, a vector is a list of numbers. The nn.Embedding layer stores a trainable
vector for every index. A token's number selects a row in this table: index 42
doesn't mean its word is "greater" than the word at index 8.
A batch is several texts processed together. With embedding_dim=8, an input
batch of shape [B, L] becomes [B, L, 8]. Store indices as integers with type
torch.long. In the example, the vocabulary has 50 entries, and the input
contains two texts with five positions each:
import torch
PAD_ID = 0
vocab_size = 50
token_ids = torch.tensor(
[[17, 42, 8, 0, 0], [1, 0, 0, 0, 0]],
dtype=torch.long,
)
embedding = torch.nn.Embedding(vocab_size, 8, padding_idx=0)
vectors = embedding(token_ids)
print(vectors.shape) # torch.Size([2, 5, 8])
Here, B is the number of texts in the batch, and L is the bounded
sequence length.
The padding mask
An ordinary mean includes zero positions and changes the result for a short
text. A mask excludes PAD from both the sum and the denominator:
mask = token_ids.ne(PAD_ID).unsqueeze(-1)
masked = vectors * mask
lengths = mask.sum(dim=1).clamp_min(1)
pooled = masked.sum(dim=1) / lengths
print(pooled.shape) # torch.Size([2, 8])
ne(PAD_ID) marks positions that aren't PAD. unsqueeze(-1) adds a final
dimension so that each mark applies to every number in the vector.
sum(dim=1) sums the positions for each text, and clamp_min(1) prevents
the denominator from becoming zero.
Two inputs with the same tokens and different amounts of PAD should produce
the same representation before the linear layer.
Linear and logits
nn.Linear converts the averaged embedding into four numbers. These numbers
are called logits, and they can be negative:
classifier = torch.nn.Linear(8, 4)
logits = classifier(pooled) # shape [B, 4]
CrossEntropyLoss takes logits directly. Don't call softmax before the loss;
the loss function already performs the required conversion in a numerically
stable way.
train and eval
During training, put the model into model.train() mode. For evaluation,
use model.eval() and a context that doesn't build a graph:
from incident_classifier.model import IncidentClassifier
model = IncidentClassifier(vocab_size, 4, embedding_dim=8)
model.eval()
with torch.no_grad():
logits = model(token_ids)
print(logits.shape) # torch.Size([2, 4])
The current architecture has no dropout, but explicitly changing modes is still part of a correct pipeline and will be needed as the model develops.
Task
Implement this factory in exercises/lesson07.py:
def build_classifier(vocab_size, num_classes, embedding_dim=8):
...
It returns an IncidentClassifier instance. The class is already implemented
in incident_classifier.model and imported in the starter file. Pass it
vocab_size, num_classes and embedding_dim. The model accepts indices
of shape [batch, length] and returns logits of shape [batch, num_classes].
Requirements:
- parameters are on the CPU and use
float32; PADis excluded from the mean;UNKis a regular trainable index;- empty text is rejected before the model is called;
- input length is bounded by the pipeline configuration;
- the parameter count stays well below one million;
- a short training loop produces a finite loss.
Hints
Open src/incident_classifier/model.py and read the IncidentClassifier
constructor. The exercise checks that you create the model correctly,
rather than implement the class a second time.
After the test passes, trace forward: the mask has shape [B, L, 1],
and lengths are clamped to a minimum of one.
Check
python -m pytest -q tests/test_exercises.py --student exercises -k lesson07
The tests check shape and dtype, unchanged results when PAD is added,
UNK handling, and a short CPU training loop.
Where to find the solution
The reference is in solutions/lesson07.py. Compare how the denominator
is calculated: non-padding tokens are counted separately for each batch item.
python -m pytest -q tests/test_exercises.py --student solutions -k lesson07
Common mistake
Softmax inside forward prevents CrossEntropyLoss from working with logits.
The model should return the linear layer's output without prior normalization.
Done reading?
Mark the lesson as read to move your track progress forward.
Lesson marked as done.
Practice
Fix a local lab. The agent checks your work and gives hints if you get stuck.
Full access to all labs
One payment, no auto-renewal · Terms
Progress saved in this browser
Clear your history or open this on your phone, and the marks will be gone. Leave your email and they'll move to your account. No password needed.
Done. moved to your account. You can see your progress on any device. My progress