Advanced level · Module 1: Neural Networks for NLP · Lesson 2 of 3
An Embedding-Based Text Classifier
Learners build a fast neural classifier with nn.EmbeddingBag (averaged learned embeddings followed by a linear layer) and train it with cross-entropy loss.
In this lesson you will
- Build a neural text classifier in PyTorch
- Write and run a training loop
Key concepts
nn.EmbeddingBagnn.LinearCrossEntropyLossoptimizer (Adam)epochs and validation
The lesson
nn.EmbeddingBag(vocab_size, 64, mode='mean') looks up a vector for each token and averages them, giving one vector per text; nn.Linear(64, n_classes) turns it into class scores. This is a neural version of bag of words with learned word vectors.
A training loop repeats: forward pass, loss = CrossEntropyLoss()(scores, labels), loss.backward(), optimizer.step(), optimizer.zero_grad(). Evaluate on validation data after each epoch and keep the best model.
Small models like this train in minutes on a CPU, which makes them practical for Rescue Academy labs and for organisations without GPUs.
Step by step
- Define the model class with EmbeddingBag and Linear layers.
- Train for ten epochs on the Intermediate project's news data.
- Plot training and validation loss.
- Report validation macro F1 for the best epoch.
Practice activity
Train and evaluate an EmbeddingBag classifier on the news categorisation task.
Expected result: A trained model with loss curves and a validation F1 score.
Check your understanding
-
What does EmbeddingBag with mode='mean' produce?
Show answer
One averaged embedding vector per text.
-
Why evaluate on validation data each epoch?
Show answer
To detect overfitting and keep the best model.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.