Classification
Train neural networks to assign discrete labels — binary and multi-class classification with PyTorch.
Goal of the lesson
By the end of this 3-hour session you should be able to:
- explain the difference between regression and classification,
- generate synthetic 2-D datasets and visualize their decision regions,
- build a feed-forward neural network with non-linear activations,
- choose the right loss for binary and multi-class problems,
- track loss and accuracy during training,
- recognize underfitting and overfitting visually,
- handle real-world tabular data with mixed numerical and categorical features,
- solve the moons dataset as a capstone.
Suggested timing
| Block | Topic |
|---|---|
| 15 min | What classification is, logits vs. probabilities |
| 25 min | Generate the blobs dataset, build the model |
| 25 min | Training loop with accuracy, decision boundary |
| 15 min | Binary classification with BCEWithLogitsLoss |
| 55 min | Real-world example — heart-disease prediction |
| 45 min | Capstone — moons dataset and overfitting |
Regression vs. classification
| Task | Output | Loss | Final layer |
|---|---|---|---|
| Regression | A real number | MSELoss, L1Loss | Linear (no activation) |
| Binary classification | One of two classes | BCEWithLogitsLoss | Linear with 1 output (logit) |
| Multi-class classification | One of K classes | CrossEntropyLoss | Linear with K outputs (logits) |
The five-step workflow doesn’t change. We swap the dataset, the model’s output size, and the loss.
Setup
uv init --python 3.12 classification
cd classification
uv add torch matplotlib scikit-learn numpy
=
Multi-class — the blobs dataset
sklearn.datasets.make_blobs generates clusters of points in 2-D — perfect for visualizing what a classifier is doing.
= 4
= 2
, = =1000,
=,
=,
=1.5,
=42,
)
=
=
, , , =
A few details that matter:
- Features are
float32. Targets forCrossEntropyLossmust beint64(the dtype.long()produces). - Targets are class indices (
0,1,2,3), not one-hot vectors. PyTorch’s loss does the one-hot conversion internally.
Visualize:
You're reading a preview.
Sign in to read the full article. Any account opens 10 free articles a month; students and teachers read their course pages without limit.
Sign in