42. Deep learning with PyTorch
Deep learning trains models that are made of many simple layers. The same few ideas drive a churn model, a digit reader and a large language model: tensors hold the numbers, autograd computes the gradients, a model is a class, and a short loop improves it step by step. This module builds each idea with the course data and runs everything on a laptop CPU in seconds.
You also close the loop that Part 3 opened. In modules 18 to 22 you wrote minilearn, a small scikit-learn look-alike, and in module 34 you rebuilt it on scikit-learn’s base classes. A PyTorch model is the same kind of object: a class whose constructor holds the settings and the learned values, and whose forward method plays the role of predict.
What you will learn
Section titled “What you will learn”- Create tensors, control their
dtypeand shape, use broadcasting, and move data between NumPy and PyTorch. - Compute gradients with autograd (
requires_grad,backward(),.grad,torch.no_grad()) and check them against the analytic derivative. - Write a model as an
nn.Moduleclass and map it to theminilearnand scikit-learn classes you already know. - Write the training loop step by step:
TensorDataset,DataLoader, a loss, an optimizer,zero_grad(),backward()andstep(). - Train an MLP for the churn data and a small CNN for handwritten digits, and compare them with scikit-learn baselines.
- Fight overfitting with dropout, weight decay and early stopping, switch between train and eval mode, and save and load models safely.
Prerequisites
Section titled “Prerequisites”- Arrays,
dtype,axisand broadcasting: 23. NumPy. - Gradients, the chain rule, gradient descent, the sigmoid and log loss: 32. Math for ML.
- Classes,
__init__, inheritance and special methods such as__call__,__len__and__getitem__: 18. Classes and objects, 19. Inheritance and polymorphism and 20. The Python data model. - Train/test splits,
ColumnTransformerand the estimator API: 34. The scikit-learn workflow. - ROC-AUC, thresholds and class imbalance: 36. Classification. Overfitting and validation: 37. Model evaluation and tuning.
- PyTorch is in the course requirements as the CPU build: Install Python and Virtual environments. The datasets are described on the data dictionary page.
Concepts
Section titled “Concepts”What deep learning is
Section titled “What deep learning is”A neural network is a model built from layers. A layer takes a vector of numbers and returns a new vector. The simplest layer multiplies its input by a matrix of weights and adds a vector of biases: it is a linear model with several outputs. Each output of a layer is called a neuron (or a unit).
Between two linear layers sits an activation function: a fixed, non-linear function applied to every number. Without it, two linear layers would collapse into one linear layer. With it, the network can learn curves, thresholds and interactions, such as “churn rises steeply when tenure is short and the contract is monthly”.
Deep learning means training networks with several layers. The layers between the input and the output are hidden layers. A network made only of linear layers and activations is a multilayer perceptron (MLP).
flowchart LR
X["22 customer<br/>features"] --> H1["Linear 22→32<br/>+ ReLU"]
H1 --> H2["Linear 32→16<br/>+ ReLU"]
H2 --> O["Linear 16→1<br/>churn logit"]
Deep learning is not always the best tool. Use this table to decide:
| Data | Usual winner | Why |
|---|---|---|
tabular (rows and columns, like customers.csv) |
gradient boosting (module 38), then an MLP | trees handle mixed scales, thresholds and missing values with little tuning |
| images, audio, video | convolutional and other deep networks | layers learn local patterns (edges, strokes, sounds) from raw pixels or samples |
| text | transformer networks; TF-IDF + linear models for small data (module 41) | networks learn word meaning from context |
| very large data, many outputs, custom losses | deep learning | you control the architecture and the loss |
PyTorch is a Python library for deep learning. It gives you three things: tensors (fast arrays), autograd (automatic gradients) and building blocks for models, losses, optimizers and data loading. It runs on CPUs and GPUs. This course uses only the CPU.
Reproducible runs on the CPU
Section titled “Reproducible runs on the CPU”Training uses random numbers: the starting weights, the order of the rows and dropout (see below). Two settings make this page give the same numbers on every run, and on other machines with the same library versions:
import numpy as npimport torch
torch.set_num_threads(1) # one CPU thread: the same sums in the same ordertorch.manual_seed(42) # fixes PyTorch's random numbersrng = np.random.default_rng(42) # NumPy's generator, for NumPy codeprint(torch.get_num_threads())print(torch.rand(3))1tensor([0.8823, 0.9150, 0.3829])torch.manual_seed(42)fixes the global PyTorch random generator, asnp.random.default_rng(42)andrandom_state=42do for NumPy and scikit-learn.torch.set_num_threads(1)makes PyTorch use one CPU thread (one sequence of instructions; see module 15). With several threads, PyTorch splits a big sum into parts, one per thread, and then adds the parts. Float addition is not exactly associative ((a + b) + ccan differ froma + (b + c)in the last digit), so the result of a large matrix product can depend on the number of threads. On one machine with a fixed thread count, repeated runs give the same bits. But the default thread count depends on the machine (its number of cores and settings such as theOMP_NUM_THREADSenvironment variable). Fixing it at 1 gives the same additions in the same order everywhere this code runs.- One thread also avoids oversubscription: more busy threads than CPU cores. This happens when several processes (cross-validation jobs, data-loader workers, a web server) each start one thread per core. The threads then fight for the cores and everything slows down. For the small networks of this module, one thread is as fast as several: the matrices are too small for the split to pay off.
Different CPUs and library versions can still differ in the last digits. This page rounds every loss and metric to 3 or 4 decimals, so small last-digit differences usually do not show.
Tensors: arrays for deep learning
Section titled “Tensors: arrays for deep learning”A tensor is PyTorch’s array: a grid of numbers with one dtype and a shape, like a NumPy ndarray (module 23). Tensors add two abilities: they can record the operations done on them (for autograd) and they can live on a GPU.
readings = torch.tensor([21.5, 22.1, 23.4])tickets = torch.tensor([3, 0, 7])print(readings, readings.dtype, readings.shape)print(tickets, tickets.dtype)print(torch.zeros(2, 3))print(torch.arange(0, 10, 3), torch.linspace(0, 1, 5))tensor([21.5000, 22.1000, 23.4000]) torch.float32 torch.Size([3])tensor([3, 0, 7]) torch.int64tensor([[0., 0., 0.], [0., 0., 0.]])tensor([0, 3, 6, 9]) tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])| Create | Gives | Note |
|---|---|---|
torch.tensor(data) |
a copy of a list, a number or an array | the dtype is inferred |
torch.zeros(2, 3), torch.ones(2, 3), torch.full((2, 3), 7.0) |
filled tensors | the shape comes first |
torch.arange(0, 10, 3), torch.linspace(0, 1, 5) |
ranges | like np.arange and np.linspace |
torch.rand(2, 3), torch.randn(2, 3), torch.randint(0, 10, (2, 3)) |
random values | uniform on [0, 1), standard normal, integers |
torch.zeros_like(t), torch.ones_like(t) |
same shape and dtype as t |
|
torch.from_numpy(arr), torch.as_tensor(arr) |
a tensor from NumPy | see NumPy interop |
The dtype decides how each number is stored:
| dtype | Default for | Use |
|---|---|---|
torch.float32 |
Python floats | features, weights, losses: the standard for deep learning |
torch.float64 |
NumPy float arrays | precise checks, such as gradient checks |
torch.int64 (long) |
Python ints | class labels for CrossEntropyLoss, indices |
torch.bool |
comparisons | masks: t[t > 0] |
float32 stores about 7 significant digits in 4 bytes. That is enough for weights that are adjusted thousands of times anyway, and it halves the memory and time of float64. Convert with t.float() (to float32), t.long() (to int64) or t.to(torch.float64).
Shapes, operations and broadcasting
Section titled “Shapes, operations and broadcasting”By convention, the first dimension of a data tensor is the batch dimension: one row per sample. A batch of 64 customers with 22 features has shape (64, 22). Most errors in PyTorch code are shape errors, so print .shape often.
batch = torch.arange(6.0).reshape(2, 3) # 2 samples, 3 featuresprint(batch)print(batch.shape, batch.ndim, batch.numel())print(batch.sum(dim=0), batch.mean(dim=1))print(batch @ torch.ones(3)) # matrix-vector productprint(batch.unsqueeze(0).shape, batch[:, 0].shape, batch[:, :1].shape)tensor([[0., 1., 2.], [3., 4., 5.]])torch.Size([2, 3]) 2 6tensor([3., 5., 7.]) tensor([1., 4.])tensor([ 3., 12.])torch.Size([1, 2, 3]) torch.Size([2]) torch.Size([2, 1])- Operations such as
+,*andtorch.expwork element-wise, as in NumPy.@is the matrix product. - Reductions take
dim=(NumPy calls itaxis=; PyTorch accepts both).dim=0reduces over the rows and gives one value per column. reshapechanges the shape and keeps the values.unsqueeze(d)adds a dimension of size 1 at positiond;squeeze(d)removes one.t[:, 0]drops the column dimension, andt[:, :1]keeps it.
Broadcasting follows NumPy’s rules exactly: shapes are compared from the right, and a dimension of size 1 (or a missing dimension) is stretched to match. So a (3,) vector of column means is subtracted from every row of a (2, 3) batch:
col_mean = batch.mean(dim=0)print(col_mean.shape)print(batch - col_mean)torch.Size([3])tensor([[-1.5000, -1.5000, -1.5000], [ 1.5000, 1.5000, 1.5000]])Moving between NumPy and PyTorch
Section titled “Moving between NumPy and PyTorch”Data usually starts in pandas or NumPy. Four tools move it across:
| Call | Copies? | Result |
|---|---|---|
torch.from_numpy(arr) |
no: shares memory with arr |
same dtype as arr (float64 stays float64) |
torch.as_tensor(arr, dtype=torch.float32) |
only when the dtype changes | the dtype you ask for |
torch.tensor(arr, dtype=torch.float32) |
always | the dtype you ask for |
t.numpy() |
no: shares memory | a NumPy array; fails if t requires a gradient |
arr = np.array([29.95, 54.50, 89.00])shared = torch.from_numpy(arr)arr[0] = 0.0 # change the NumPy arrayprint(shared, shared.dtype)print(torch.tensor(arr, dtype=torch.float32))total = shared.sum()print(total, type(total.item()), total.item())tensor([ 0.0000, 54.5000, 89.0000], dtype=torch.float64) torch.float64tensor([ 0.0000, 54.5000, 89.0000])tensor(143.5000, dtype=torch.float64) <class 'float'> 143.5The tensor shared changed with the array, because both use the same memory. .item() turns a tensor with one element into a plain Python number. Use it to print a loss, to store a metric in a list or to compare with round(). .tolist() does the same for a whole tensor.
Autograd: gradients for free
Section titled “Autograd: gradients for free”To train a model, you need the gradient of the loss with respect to every weight (module 32). For a network with thousands of weights, deriving the formulas by hand is slow and error-prone. Autograd is PyTorch’s automatic differentiation engine. It computes every gradient for you.
It works in two passes:
- Forward pass: you compute the loss from the inputs as usual. For every tensor with
requires_grad=True, PyTorch records each operation in a computational graph: a graph whose nodes are the operations and whose edges are the tensors that flow between them. - Backward pass:
loss.backward()walks the graph from the loss back to the inputs and applies the chain rule at each node. This is backpropagation. Each tensor that you created withrequires_grad=True(a leaf tensor) receives its gradient in.grad.
flowchart LR
W["w (leaf)<br/>requires_grad"] --> M["w * x"]
X["x (data)"] --> M
M --> S["− 5.0"]
S --> P["** 2"]
P --> L["loss"]
L -. "backward()" .-> W
A tiny example, with and . By the chain rule, .
w = torch.tensor(2.0, requires_grad=True)x = torch.tensor(3.0)loss = (w * x - 5.0) ** 2print(loss, loss.grad_fn.name())loss.backward()print(w.grad, x.grad)tensor(1., grad_fn=<PowBackward0>) PowBackward0tensor(6.) Nonegrad_fn is the last recorded operation; it proves that loss is part of a graph. w.grad holds 6, as the formula says. x.grad is None because x does not require a gradient.
Three rules complete the picture:
| Rule | Why | Code |
|---|---|---|
backward() adds to .grad |
so gradients from several losses can be summed; this is gradient accumulation | reset with optimizer.zero_grad() or w.grad.zero_() |
updates and evaluation go in torch.no_grad() |
the weight update must not become part of the graph, and evaluation needs no graph (faster, less memory) | with torch.no_grad(): w -= lr * w.grad |
t.detach() gives the same values without the graph |
to plot, store or convert to NumPy | t.detach().numpy() |
nn.Module: a model is a class
Section titled “nn.Module: a model is a class”In PyTorch, every model is a subclass of nn.Module. You already know this design. Here is the same idea in the three libraries of the course:
| Idea | minilearn (Part 3) |
scikit-learn (module 34) | PyTorch |
|---|---|---|---|
| base class | BaseEstimator |
sklearn.base.BaseEstimator |
torch.nn.Module |
| constructor holds | hyperparameters (n_neighbors=5) |
hyperparameters | hyperparameters and the layers, whose weights are the learned parameters |
| learned values | attributes ending in _, created by fit() (coef_) |
same (coef_, intercept_) |
nn.Parameter tensors inside the layers, created at once with random values |
| learn | fit(X, y) |
fit(X, y) |
a training loop that you write (or a wrapper; see the mini-project) |
| predict | predict(X) |
predict(X), predict_proba(X) |
forward(x), run with model(x) |
| list the learned values | the _ attributes |
the _ attributes |
model.parameters(), model.named_parameters() |
| save | pickle (module 07) | joblib | model.state_dict() with torch.save |
| chain steps | Pipeline |
Pipeline |
nn.Sequential |
A module follows four rules:
- Call
super().__init__()first in__init__. It sets up the bookkeeping that finds your layers. - Assign each layer to an attribute (
self.linear = nn.Linear(3, 1)).nn.Modulethen registers it, and its weights appear inparameters()andstate_dict(). - Write the computation in
forward(self, x). - Call the model as
model(x), notmodel.forward(x).nn.Moduledefines__call__(module 20), which runs some bookkeeping (hooks) and thenforward.
The workhorse layer is nn.Linear(in_features, out_features). For a batch of shape (n, in), it computes
with a weight matrix of shape (out, in) and a bias of shape (out,). The ReLU (rectified linear unit) activation is : it keeps positive numbers and sets negative numbers to 0. It is cheap and works well in hidden layers.
from torch import nn
torch.manual_seed(42)layer = nn.Linear(3, 2)print(layer)for name, param in layer.named_parameters(): print(name, tuple(param.shape), param.requires_grad)x = torch.tensor([[1.0, -2.0, 0.5]])print(torch.relu(torch.tensor([-1.5, 0.0, 2.0])))print(torch.allclose(layer(x), x @ layer.weight.T + layer.bias))Linear(in_features=3, out_features=2, bias=True)weight (2, 3) Truebias (2,) Truetensor([0., 0., 2.])TrueAn nn.Parameter is a tensor that a module registers as learnable. It always has requires_grad=True. nn.Sequential(layer1, layer2, ...) is a ready-made module that runs its layers in order, like a Pipeline of transformers.
The state_dict of a module is an ordered dictionary from parameter names (such as "net.0.weight") to tensors. It holds the learned values only, not the code and not the hyperparameters. It plays the role that the _ attributes played in minilearn: it is what you save after training.
Logits and loss functions
Section titled “Logits and loss functions”The last layer of a classifier returns logits: raw scores on the whole real line. A logit is the log-odds of module 32: the sigmoid turns it into a probability, . For classes, the network returns logits, and the softmax (module 36) turns them into probabilities that sum to 1.
The two classification losses in the table below take logits, not probabilities. They apply the sigmoid or the softmax inside, with a formula that avoids overflow and log(0). So a PyTorch classifier has no sigmoid at the end during training.
| Task | Last layer | Loss | Target |
|---|---|---|---|
| regression (price) | nn.Linear(h, 1) |
nn.MSELoss() |
float, same shape as the output |
| binary (churn) | nn.Linear(h, 1): 1 logit |
nn.BCEWithLogitsLoss() |
float 0.0/1.0, same shape as the output |
| multiclass (digit 0–9) | nn.Linear(h, 10): 10 logits |
nn.CrossEntropyLoss() |
int64 class index, shape (n,) |
BCEWithLogitsLoss is binary cross-entropy (log loss) computed from logits. Its pos_weight argument multiplies the loss of every positive sample. For one sample with logit and label :
With about 4 stayers per churner, pos_weight = n_negative / n_positive ≈ 4.2 makes the churners count as much as the stayers in total. This is the PyTorch version of class_weight="balanced" in scikit-learn. It pushes the predicted probabilities up, so it changes the useful threshold, but it keeps most of the ranking (ROC-AUC).
Cross-entropy loss (nn.CrossEntropyLoss) is the multiclass version: the negative log of the softmax probability of the true class.
Optimizers
Section titled “Optimizers”An optimizer updates the parameters from their gradients. You give it the parameters once: torch.optim.SGD(model.parameters(), lr=0.1). Then each training step is three calls:
optimizer.zero_grad() # 1. clear the old gradients (backward() adds to them)loss.backward() # 2. compute new gradients for every parameteroptimizer.step() # 3. update every parameter| Optimizer | Update | Typical lr |
|---|---|---|
torch.optim.SGD |
: plain gradient descent on each batch | 0.01–0.1 |
torch.optim.Adam |
gradient descent with momentum (an average of recent gradients) and a separate step size for every parameter | 0.001 |
torch.optim.AdamW |
Adam with decoupled weight decay (see below) | 0.001 |
Adam adapts the step size of each parameter to the size of its recent gradients. It works well with little tuning, so AdamW(lr=1e-3) is a good default for the networks of this module. is the learning rate from module 32.
The training loop: Dataset, DataLoader, epochs
Section titled “The training loop: Dataset, DataLoader, epochs”scikit-learn hides training inside fit(). In PyTorch, you write the loop. That costs ten lines and gives you full control.
- A
Datasetis any object with__len__and__getitem__that returns one sample, such as(features, target). It is the protocol of module 20’sDatasetclass.TensorDataset(X, y)is a ready-made one for tensors that are already in memory. - A
DataLoaderdraws samples from a dataset and stacks them into batches (module 32). Withshuffle=True, it uses a new random order in every epoch. Passgenerator=torch.Generator().manual_seed(42)to make that order reproducible. - An epoch is one pass over the whole training set. With 3,000 rows and
batch_size=64, one epoch is 47 steps.
flowchart TD
A["Start epoch<br/>model.train()"] --> B["Next batch<br/>from DataLoader"]
B --> C["Forward: logits = model(xb)"]
C --> D["loss = loss_fn(logits, yb)"]
D --> E["zero_grad → backward → step"]
E --> F{"More batches?"}
F -- yes --> B
F -- no --> G["Validate<br/>model.eval(), no_grad"]
G --> H{"Stop early?"}
H -- no --> A
H -- yes --> I["Restore the best weights"]
Train mode and eval mode
Section titled “Train mode and eval mode”Some layers behave differently while you train and while you predict. Dropout (next section) is the main one in this module; batch normalization is another. Every module has a training flag:
| Call | Sets training to |
Dropout | Gradients |
|---|---|---|---|
model.train() |
True (the default after construction) |
active: zeroes random values | recorded |
model.eval() |
False |
off: passes values through | still recorded unless you use no_grad |
with torch.no_grad(): |
unchanged | unchanged | not recorded |
model.eval() and torch.no_grad() do different jobs. Use both when you evaluate or predict. Then call model.train() again before the next training epoch. Both methods set the flag on every submodule and return the model, so model.eval()(x) also works.
Overfitting: dropout, weight decay and early stopping
Section titled “Overfitting: dropout, weight decay and early stopping”A network with thousands of weights can memorize the training rows: its training loss keeps falling while the validation loss rises. This is overfitting (module 37). Three standard tools fight it:
- Dropout (
nn.Dropout(p)) sets a random sharepof the values that pass through it to 0 during training, and multiplies the rest by so that the average stays the same. No neuron can rely on one particular input, so the network learns more robust features. In eval mode, dropout does nothing. - Weight decay shrinks every weight a little at each step, which keeps the weights small. With plain SGD, this is the same as adding an L2 penalty to the loss (module 35). With Adam, an L2 penalty in the loss would pass through the adaptive step sizes and be rescaled differently for each parameter. AdamW therefore applies the shrink directly to the weights, outside the Adam update; this is what decoupled means. In
AdamW(lr=η, weight_decay=λ), each step multiplies each weight by and then applies the Adam update. The default isweight_decay=0.01. - Early stopping watches the validation loss after every epoch and stops when it has not improved for
patienceepochs. Patience is the number of epochs without improvement that you accept before you stop. The model then returns to the weights of its best epoch.
The validation set comes out of the training data. The test set stays untouched until the very end, so it gives an honest final score.
Convolutional networks for images
Section titled “Convolutional networks for images”An 8×8 grayscale image is 64 numbers. An MLP could treat them as 64 unrelated features, but it would ignore that neighboring pixels belong together. A convolutional neural network (CNN) uses that structure.
- A convolution slides a small grid of weights, the convolution kernel (or filter), over the image. At each position, it multiplies the kernel with the pixels under it, sums the products and adds a bias. The grid of results is a feature map. A 3×3 kernel that has learned “vertical edge” lights up wherever the digit has a vertical stroke.
- The same kernel is used at every position. This weight sharing means that a 3×3 kernel has only 9 weights per input channel and 1 bias, whatever the size of the image.
- A layer learns many kernels at once. Each one produces its own feature map, called a channel. A grayscale image has 1 input channel;
nn.Conv2d(1, 16, kernel_size=3)produces 16 channels. - Pooling shrinks the feature maps. Max pooling (
nn.MaxPool2d(2)) keeps the largest value of each 2×2 window, which halves the height and the width and keeps the strongest signals. - Image tensors use the NCHW layout:
(batch, channels, height, width). A batch of 32 digits has shape(32, 1, 8, 8).
Padding adds a border of zeros around the image, and stride is the step between two kernel positions. For an input of height , kernel size , padding and stride , the output height is
With , , and , the output stays 8 tall. A 2×2 max pooling then gives 4. The width works the same way. After the convolutions, flatten turns each sample’s feature maps into one vector for a final nn.Linear layer that returns 10 logits.
Saving and loading models
Section titled “Saving and loading models”The recommended way to save a PyTorch model is to save its state_dict, not the whole object:
torch.save(model.state_dict(), "output/model.pt") # save the learned tensorsmodel = MyModel(...) # rebuild the same architecture from your codemodel.load_state_dict(torch.load("output/model.pt", weights_only=True))model.eval() # loaded for predictiontorch.savewrites the dictionary with pickle inside a zip file. Loading a pickle can run any code that the file contains.weights_only=Truerestricts loading to tensors and plain containers (dicts, lists, numbers, strings), which blocks the arbitrary code that a malicious pickle could run. It greatly reduces the risk but is not an absolute guarantee: still prefer files from trusted sources and keep PyTorch up to date. It is the default in recent PyTorch versions; write it anyway, so the intent is clear and older versions behave the same.- The
state_dictdoes not contain the class or the hyperparameters. Keep the model class in an importable module and save the hyperparameters next to the weights. A dictionary with the weights, the hyperparameters, the optimizer state and the epoch is a model checkpoint. It lets you resume training. torch.save(model)pickles the whole object. Loading it needsweights_only=Falseand the exact same class at the same import path, and it breaks when you rename or move the class. Avoid it.
Worked examples
Section titled “Worked examples”Example 1 — Turn customer records into tensors
Section titled “Example 1 — Turn customer records into tensors”Goal: Load four numeric columns of data/customers.csv, convert them to a float32 tensor, standardize them with broadcasting and check the result against scikit-learn.
Step 1 — Load the columns with pandas
Section titled “Step 1 — Load the columns with pandas”import pandas as pd
customers = pd.read_csv("data/customers.csv")cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]values = customers[cols].to_numpy()print(values.dtype, values.shape)print(values[:3])float64 (5000, 4)[[ 72. 84.69 0. 17. ] [ 72. 55.33 0. 15. ] [ 72. 108.02 1. 12. ]]to_numpy() gives one array for the four columns. The integer and float columns share one dtype, so NumPy promotes everything to float64.
Step 2 — Convert to a float32 tensor
Section titled “Step 2 — Convert to a float32 tensor”features = torch.from_numpy(values)print(features.dtype)features = features.float() # float32, the dtype of PyTorch weightstarget = torch.tensor(customers["churned"].to_numpy(), dtype=torch.float32)print(features.dtype, features.shape, target.shape)print(features[:3])torch.float64torch.float32 torch.Size([5000, 4]) torch.Size([5000])tensor([[ 72.0000, 84.6900, 0.0000, 17.0000], [ 72.0000, 55.3300, 0.0000, 15.0000], [ 72.0000, 108.0200, 1.0000, 12.0000]])from_numpy keeps float64. .float() makes a float32 copy, which matches the weights of nn.Linear. The target is float too, because BCEWithLogitsLoss compares it with float logits. PyTorch prints float32 values with 4 decimals.
Step 3 — Standardize with broadcasting
Section titled “Step 3 — Standardize with broadcasting”mean = features.mean(dim=0)std = features.std(dim=0, correction=0)print(mean.shape, mean.round(decimals=2))scaled = (features - mean) / stdprint(scaled.shape)print(torch.allclose(scaled.mean(dim=0), torch.zeros(4), atol=1e-5))print(torch.allclose(scaled.std(dim=0, correction=0), torch.ones(4), atol=1e-5))torch.Size([4]) tensor([23.0800, 60.8400, 1.2400, 11.7400])torch.Size([5000, 4])TrueTruemean(dim=0) reduces over the 5,000 rows and gives one mean per column, shape (4,). Broadcasting subtracts that vector from every row. After scaling, each column has mean 0 and standard deviation 1, up to float32 rounding. torch.allclose compares with a tolerance, like math.isclose for whole tensors.
Step 4 — Compare with StandardScaler
Section titled “Step 4 — Compare with StandardScaler”from sklearn.preprocessing import StandardScaler
sk_scaled = StandardScaler().fit_transform(values)gap = (scaled - torch.from_numpy(sk_scaled).float()).abs().max()print(f"largest difference: {gap.item():.1e}")print(gap.item() < 1e-5)largest difference: 7.2e-07TrueTwo lines of tensor code did what StandardScaler does, because both divide by . With the default features.std(dim=0), the values would differ by a factor of about : small, but a silent mismatch with every scaler of module 33.
Step 5 — Read single numbers with .item()
Section titled “Step 5 — Read single numbers with .item()”churn_rate = target.mean()print(churn_rate)print(f"churn rate: {churn_rate.item():.2%}")churned = target == 1tenure = features[:, 0]print(round(tenure[churned].mean().item(), 1), round(tenure[~churned].mean().item(), 1))tensor(0.1926)churn rate: 19.26%11.7 25.8The mean of a tensor is still a tensor with zero dimensions. .item() turns it into a Python float that f-strings and round() handle. A boolean tensor works as a mask, as in NumPy: churners have a much shorter mean tenure than the customers who stay.
Common mistakes:
- Feeding a float64 tensor to a float32 model.
nn.LinearraisesRuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float. Convert with.float()once, when you build the tensors. - Using
t.std()to standardize. It divides by . Writecorrection=0when you want to match scikit-learn. - Forgetting that
from_numpyshares memory. Changing the array later changes the tensor too. Usetorch.tensor(arr)when you need an independent copy.
Example 2 — Check autograd against the analytic derivative
Section titled “Example 2 — Check autograd against the analytic derivative”Goal: For a one-feature price model on five houses of data/houses.csv, let autograd compute the gradient of the mean squared error, check it against the formula, and then use it for gradient descent.
Step 1 — Prepare the data and the parameters
Section titled “Step 1 — Prepare the data and the parameters”houses = pd.read_csv("data/houses.csv")sample = houses.head(5)x = torch.tensor(sample["sqft"].to_numpy() / 1000, dtype=torch.float32)y = torch.tensor(sample["price"].to_numpy() / 1000, dtype=torch.float32)w = torch.tensor(200.0, requires_grad=True) # thousand USD per 1,000 sqftb = torch.tensor(0.0, requires_grad=True) # thousand USDprint(x)print(y)tensor([2.4200, 1.6100, 1.2600, 1.7900, 3.1700])tensor([1097.5000, 486.5000, 223.0000, 431.0000, 626.5000])The size is in thousands of square feet and the price in thousands of dollars, so the numbers stay small. w and b are leaf tensors with requires_grad=True: autograd will compute their gradients.
Step 2 — Run the forward and the backward pass
Section titled “Step 2 — Run the forward and the backward pass”pred = w * x + bloss = ((pred - y) ** 2).mean()print(round(loss.item(), 2), loss.grad_fn.name())loss.backward()print(round(w.grad.item(), 2), round(b.grad.item(), 2))81933.75 MeanBackward0-727.95 -325.8The forward pass is ordinary tensor code. backward() filled w.grad and b.grad. Both gradients are negative: increasing w or b lowers the loss, because the model predicts too little for these houses.
Step 3 — Compute the derivative by hand
Section titled “Step 3 — Compute the derivative by hand”The loss is . By the chain rule:
with torch.no_grad(): residual = w * x + b - y dw = 2 * (residual * x).mean() db = 2 * residual.mean()print(round(dw.item(), 2), round(db.item(), 2))print(torch.allclose(w.grad, dw), torch.allclose(b.grad, db))-727.95 -325.8True TrueThe hand formula and autograd agree. torch.no_grad() keeps this check out of the graph. From now on, you can trust autograd for networks where the formula would fill a page.
Step 4 — See the gradients accumulate
Section titled “Step 4 — See the gradients accumulate”loss = ((w * x + b - y) ** 2).mean()loss.backward()print(round(w.grad.item(), 2))w.grad.zero_()b.grad.zero_()print(w.grad.item(), b.grad.item())-1455.90.0 0.0The second backward() added the same gradient again, so w.grad doubled. A training loop that forgets to reset the gradients takes steps that grow with every batch. zero_() (with the trailing underscore, which marks an in-place method) resets them.
Step 5 — Update a leaf tensor the wrong way
Section titled “Step 5 — Update a leaf tensor the wrong way”w -= 0.1 * w.gradRuntimeError: a leaf Variable that requires grad is being used in an in-place operation.PyTorch refuses to change a leaf tensor that requires a gradient while it records the graph, because the change would break the recorded history. The update must happen inside torch.no_grad().
Step 6 — Run gradient descent
Section titled “Step 6 — Run gradient descent”lr = 0.1for step in range(301): loss = ((w * x + b - y) ** 2).mean() loss.backward() with torch.no_grad(): w -= lr * w.grad b -= lr * b.grad w.grad.zero_() b.grad.zero_() if step % 100 == 0: print(step, round(loss.item(), 1))slope, intercept = np.polyfit(x.numpy(), y.numpy(), deg=1)print(f"autograd: {w.item():.2f} {b.item():.2f} polyfit: {slope:.2f} {intercept:.2f}")0 81933.8100 53416.9200 53416.9300 53416.9autograd: 265.95 27.71 polyfit: 265.95 27.70This is the gradient-descent loop of module 32, with autograd in place of the hand-written gradient. It reaches the least-squares line that np.polyfit computes in closed form. x.numpy() works because x does not require a gradient.
Common mistakes:
- Forgetting to zero the gradients. The loss jumps around or explodes. Reset after each step.
- Updating weights outside
torch.no_grad(). You get theRuntimeErrorof Step 5, or, withw = w - lr * w.grad, a new non-leaf tensor whose.gradstaysNone. - Calling
.numpy()on a tensor that requires a gradient. Uset.detach().numpy().
Example 3 — Rebuild minilearn’s LinearRegression as an nn.Module
Section titled “Example 3 — Rebuild minilearn’s LinearRegression as an nn.Module”Goal: Fit price against size for all 3,000 houses with a PyTorch module, and compare it line by line with the LinearRegression class of minilearn (modules 18–22).
Step 1 — Write the module
Section titled “Step 1 — Write the module”class TorchLinearRegression(nn.Module): """Fit y = coef * x + intercept, like minilearn's LinearRegression."""
def __init__(self, n_features: int = 1) -> None: super().__init__() self.n_features = n_features # a hyperparameter, stored unchanged self.linear = nn.Linear(n_features, 1) # learned: weight and bias
def forward(self, X: torch.Tensor) -> torch.Tensor: return self.linear(X) # plays the role of predict()
torch.manual_seed(42)model = TorchLinearRegression()print(model)for name, param in model.named_parameters(): print(name, tuple(param.shape))TorchLinearRegression( (linear): Linear(in_features=1, out_features=1, bias=True))linear.weight (1, 1)linear.bias (1,)The constructor stores the hyperparameter, as in minilearn. It also creates the layer, so the learned parameters exist at once, with random values. In minilearn, coef_ and intercept_ appeared only in fit(). named_parameters() finds the weight and the bias because the layer is an attribute.
Step 2 — Call the model like a function
Section titled “Step 2 — Call the model like a function”X_all = torch.tensor(houses[["sqft"]].to_numpy() / 1000, dtype=torch.float32)y_all = torch.tensor(houses[["price"]].to_numpy() / 1000, dtype=torch.float32)print(X_all.shape, y_all.shape)with torch.no_grad(): print(model(X_all[:3]))torch.Size([3000, 1]) torch.Size([3000, 1])tensor([[2.6802], [2.0609], [1.7933]])houses[["sqft"]] (double brackets) keeps a 2-D shape (3000, 1): 3,000 samples with 1 feature. nn.Linear always expects a feature dimension. model(...) runs __call__, which calls forward. The random starting weights predict nonsense, which is expected before training.
Step 3 — Train with full-batch gradient descent
Section titled “Step 3 — Train with full-batch gradient descent”loss_fn = nn.MSELoss()optimizer = torch.optim.SGD(model.parameters(), lr=0.1)for epoch in range(501): optimizer.zero_grad() loss = loss_fn(model(X_all), y_all) loss.backward() optimizer.step() if epoch % 100 == 0: print(epoch, round(loss.item()))0 326196100 47545200 47444300 47442400 47442500 47442The loss is in squared thousands of dollars. The optimizer replaced the two hand-written update lines of Example 2: step() updates every parameter that you passed to it. Each epoch uses all 3,000 rows at once, so there is no DataLoader yet.
Step 4 — Compare with the closed-form solution
Section titled “Step 4 — Compare with the closed-form solution”xs = X_all.squeeze(1).double()ys = y_all.squeeze(1).double()coef = ((xs - xs.mean()) * (ys - ys.mean())).sum() / ((xs - xs.mean()) ** 2).sum()intercept = ys.mean() - coef * xs.mean()print("minilearn formula:", round(coef.item(), 1), round(intercept.item(), 1))print("nn.Module + SGD: ", round(model.linear.weight.item(), 1), round(model.linear.bias.item(), 1))minilearn formula: 326.8 -130.3nn.Module + SGD: 326.8 -130.3The first line is the least-squares formula from minilearn’s LinearRegression.fit, written with tensors in float64. Gradient descent found the same line: about 327 thousand dollars per extra 1,000 square feet. For a linear model, the formula is faster. Gradient descent wins when no formula exists, which is the case for every network with a hidden layer.
Step 5 — Read the state_dict
Section titled “Step 5 — Read the state_dict”state = model.state_dict()print(list(state.keys()))print({name: tuple(t.shape) for name, t in state.items()})print(model.n_features, "n_features" in state)['linear.weight', 'linear.bias']{'linear.weight': (1, 1), 'linear.bias': (1,)}1 FalseThe state_dict holds the two learned tensors under the names linear.weight and linear.bias. The hyperparameter n_features is a plain attribute, so it is not in the state_dict. This is the same split as in scikit-learn: get_params() for the settings, the _ attributes for the learned values.
Common mistakes:
- Forgetting
super().__init__(). Assigningself.linear = ...then raisesAttributeError: cannot assign module before Module.__init__() call. - Passing a 1-D tensor of shape
(3000,)tonn.Linear(1, 1). It raises a shape error. Keep a feature dimension:(3000, 1). - Comparing an output of shape
(n, 1)with a target of shape(n,).MSELossbroadcasts them to(n, n)and warns. Make both shapes equal.
Example 4 — Train an MLP on the churn data, step by step
Section titled “Example 4 — Train an MLP on the churn data, step by step”Goal: Turn the 12 features of data/customers.csv into scaled tensors, then write and run the full training loop for a small MLP with a validation set and a loss curve.
Step 1 — Split and scale the features
Section titled “Step 1 — Split and scale the features”from sklearn.compose import ColumnTransformer, make_column_selectorfrom sklearn.impute import SimpleImputerfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder
X = customers.drop(columns=["customer_id", "signup_date", "churned"])y = customers["churned"]X_rest, X_test, y_rest, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42)X_train, X_val, y_train, y_val = train_test_split( X_rest, y_rest, test_size=0.2, stratify=y_rest, random_state=42)prep = ColumnTransformer([ ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), make_column_selector(dtype_include="number")), ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), make_column_selector(dtype_include="str")),])A_train = prep.fit_transform(X_train)A_val, A_test = prep.transform(X_val), prep.transform(X_test)print(A_train.shape, A_val.shape, A_test.shape)print(f"{y_train.mean():.3f} {y_val.mean():.3f} {y_test.mean():.3f}")(3000, 22) (750, 22) (1250, 22)0.193 0.192 0.193This is the preprocessing of module 34: median imputation and scaling for the 8 numeric columns, one-hot encoding for the 4 text columns, 22 features in total. The test set is the same 1,250 customers as in module 34. The second split takes 20% of the remaining rows as a validation set. stratify keeps the churn rate equal in all three parts. The scaler learns from the training rows only.
Step 2 — Wrap the tensors in a DataLoader
Section titled “Step 2 — Wrap the tensors in a DataLoader”from torch.utils.data import DataLoader, TensorDataset
def to_tensor(a) -> torch.Tensor: return torch.tensor(np.asarray(a), dtype=torch.float32)
X_tr, X_va, X_te = to_tensor(A_train), to_tensor(A_val), to_tensor(A_test)y_tr, y_va, y_te = to_tensor(y_train), to_tensor(y_val), to_tensor(y_test)train_ds = TensorDataset(X_tr, y_tr)loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42))xb, yb = next(iter(loader))print(len(train_ds), len(loader))print(xb.shape, yb.shape, yb[:8])3000 47torch.Size([64, 22]) torch.Size([64]) tensor([0., 0., 0., 0., 0., 0., 0., 0.])TensorDataset pairs row i of the features with element i of the target. The DataLoader cuts the 3,000 shuffled rows into 47 batches: 46 batches of 64 and a last one of 56. next(iter(loader)) takes the first batch, the way a for loop would (module 10).
Step 3 — Define the model as a class
Section titled “Step 3 — Define the model as a class”class ChurnMLP(nn.Module): """A multilayer perceptron that returns one churn logit per customer."""
def __init__( self, n_features: int, hidden: tuple[int, ...] = (32, 16), dropout: float = 0.0 ) -> None: super().__init__() self.n_features = n_features self.hidden = hidden self.dropout = dropout layers: list[nn.Module] = [] size_in = n_features for size_out in hidden: layers += [nn.Linear(size_in, size_out), nn.ReLU(), nn.Dropout(dropout)] size_in = size_out layers.append(nn.Linear(size_in, 1)) self.net = nn.Sequential(*layers)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.net(x).squeeze(1) # shape (batch,): one logit per row
torch.manual_seed(42)mlp = ChurnMLP(n_features=22)print(mlp)print(sum(p.numel() for p in mlp.parameters()))ChurnMLP( (net): Sequential( (0): Linear(in_features=22, out_features=32, bias=True) (1): ReLU() (2): Dropout(p=0.0, inplace=False) (3): Linear(in_features=32, out_features=16, bias=True) (4): ReLU() (5): Dropout(p=0.0, inplace=False) (6): Linear(in_features=16, out_features=1, bias=True) ))1281The constructor arguments are the hyperparameters: the input size, the hidden sizes and the dropout rate. The loop builds the layers from them, so ChurnMLP(22, hidden=(64, 32)) is a bigger network with no new code. With dropout=0.0, the dropout layers pass values through unchanged; Example 6 turns them on. The network has 22·32 + 32 + 32·16 + 16 + 16·1 + 1 = 1,281 parameters. squeeze(1) turns the output shape (batch, 1) into (batch,), the shape of the target.
Step 4 — Choose the loss and the optimizer, then take one step
Section titled “Step 4 — Choose the loss and the optimizer, then take one step”pos_weight = (y_tr == 0).sum() / (y_tr == 1).sum()loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)optimizer = torch.optim.AdamW(mlp.parameters(), lr=1e-3)print(round(pos_weight.item(), 3))before = loss_fn(mlp(xb), yb)optimizer.zero_grad()before.backward()optimizer.step()with torch.no_grad(): after = loss_fn(mlp(xb), yb)print(round(before.item(), 4), round(after.item(), 4))4.191.1081 1.105pos_weight is the number of stayers per churner in the training rows. One optimizer step on the first batch lowered the loss on that batch a little. Training repeats this step thousands of times on different batches.
Step 5 — Write one epoch as two functions
Section titled “Step 5 — Write one epoch as two functions”def train_one_epoch(model, loader, loss_fn, optimizer) -> float: """Run one pass over the loader and return the mean training loss.""" model.train() total = 0.0 for xb, yb in loader: optimizer.zero_grad() loss = loss_fn(model(xb), yb) loss.backward() optimizer.step() total += loss.item() * len(xb) # undo the mean of the batch return total / len(loader.dataset)
def evaluate_loss(model, X, y, loss_fn) -> float: """Return the loss on (X, y) in eval mode, without a graph.""" model.eval() with torch.no_grad(): return loss_fn(model(X), y).item()The five lines inside the for loop are the heart of every PyTorch training script. train_one_epoch switches to train mode first; evaluate_loss switches to eval mode and turns off the graph. The training loss is weighted by the batch size, so the smaller last batch counts correctly.
Step 6 — Train for 20 epochs and record the history
Section titled “Step 6 — Train for 20 epochs and record the history”torch.manual_seed(42)mlp = ChurnMLP(n_features=22)optimizer = torch.optim.AdamW(mlp.parameters(), lr=1e-3)history = {"train": [], "val": []}for epoch in range(1, 21): history["train"].append(train_one_epoch(mlp, loader, loss_fn, optimizer)) history["val"].append(evaluate_loss(mlp, X_va, y_va, loss_fn)) if epoch % 5 == 0: print(f"epoch {epoch:2d} train {history['train'][-1]:.4f}" f" val {history['val'][-1]:.4f}")epoch 5 train 0.8450 val 0.8237epoch 10 train 0.8015 val 0.8114epoch 15 train 0.7724 val 0.8020epoch 20 train 0.7527 val 0.7993A fresh model starts the real run, so the single step of Step 4 does not count. Both losses fall quickly at first and then flatten. The training loss is the mean over an epoch while the weights were still changing, and the validation loss is measured at the end of the epoch, so the two are not exactly comparable. A validation loss that stops falling is the signal that more epochs will not help.
Step 7 — Plot the loss curves
Section titled “Step 7 — Plot the loss curves”import matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocator
epochs = range(1, len(history["train"]) + 1)fig, ax = plt.subplots(figsize=(7, 4))ax.xaxis.set_major_locator(MaxNLocator(integer=True)) # whole epochs onlyax.plot(epochs, history["train"], marker="o", label="training loss")ax.plot(epochs, history["val"], marker="s", label="validation loss")ax.set_xlabel("epoch")ax.set_ylabel("weighted BCE loss")ax.set_title("ChurnMLP: loss per epoch")ax.legend()plt.show()
A loss curve (module 32) is the first thing to look at after training. Here the training loss crosses below the validation loss around epoch 9 and keeps falling, while the validation loss stays near 0.80. The model has started to learn details of the training rows that do not carry over to new customers.
Common mistakes:
- Fitting the scaler on all rows before the split. The validation and test rows then leak into training (module 33). Fit
prepon the training rows only. - Building the optimizer before you rebuild the model. The optimizer then updates the parameters of the old model, and the new one never learns. Create the optimizer right after the model.
- Accumulating
total += lossinstead ofloss.item(). Each loss keeps its whole graph alive, so memory grows with every batch.
Example 5 — Compare the MLP with a logistic-regression baseline
Section titled “Example 5 — Compare the MLP with a logistic-regression baseline”Goal: Predict churn probabilities for the 1,250 test customers, score them with ROC-AUC and compare the network with a logistic regression that is trained on the same rows.
Step 1 — Predict probabilities in eval mode
Section titled “Step 1 — Predict probabilities in eval mode”mlp.eval()with torch.no_grad(): mlp_proba = torch.sigmoid(mlp(X_te)).numpy()print(mlp_proba.shape, mlp_proba.dtype)print(mlp_proba[:5].round(3))(1250,) float32[0.279 0.688 0.234 0.558 0.131]The model returns logits, so the sigmoid turns them into probabilities. eval() and no_grad() together make the prediction deterministic and cheap. The result is a NumPy array, ready for scikit-learn’s metrics.
Step 2 — Score both models with ROC-AUC
Section titled “Step 2 — Score both models with ROC-AUC”from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import recall_score, roc_auc_score
logreg = LogisticRegression(max_iter=1000).fit(A_train, y_train)logreg_proba = logreg.predict_proba(A_test)[:, 1]print(f"logistic regression ROC-AUC: {roc_auc_score(y_test, logreg_proba):.3f}")print(f"ChurnMLP ROC-AUC: {roc_auc_score(y_test, mlp_proba):.3f}")logistic regression ROC-AUC: 0.813ChurnMLP ROC-AUC: 0.831Both models saw the same 3,000 training rows and the same 22 features. The MLP ranks churners better than the logistic regression. One possible reason: hidden layers can model non-linear effects and interactions between features, which a linear model on these 22 features cannot express. These are test scores, so they only report the comparison; a real choice between the two models must come from cross-validation or the validation split. This page does not test that explanation; the partial-dependence plots of module 43 show how to check it. The data dictionary page reports a hold-out ROC-AUC of 0.825 for a default HistGradientBoostingClassifier on the same 1,250 test customers, so gradient boosting reaches a similar score with less code (module 38).
Step 3 — Read the effect of pos_weight on the probabilities
Section titled “Step 3 — Read the effect of pos_weight on the probabilities”for name, proba in [("logistic", logreg_proba), ("ChurnMLP", mlp_proba)]: recall = recall_score(y_test, proba >= 0.5) print(f"{name:9s} mean probability {proba.mean():.3f}" f" recall at 0.5 {recall:.3f}")print(f"actual churn rate {y_test.mean():.3f}")logistic mean probability 0.197 recall at 0.5 0.303ChurnMLP mean probability 0.399 recall at 0.5 0.763actual churn rate 0.193The logistic regression is close to calibrated: its mean probability is near the real churn rate. The MLP’s pos_weight pushed its probabilities up, so at the 0.5 threshold it flags many more customers and catches most churners. Neither number is “right”: ROC-AUC measures the ranking, and the threshold is a business choice (module 36). If you need calibrated probabilities, train without pos_weight or calibrate afterwards.
Common mistakes:
- Predicting in train mode. With dropout, two calls give different answers. Call
model.eval()first. - Passing logits to
roc_auc_scoreand probabilities elsewhere, and then mixing them up. ROC-AUC gives the same result for both, because the sigmoid keeps the order, but a threshold of 0.5 means something only for probabilities. - Comparing a network with a baseline that saw different rows or features. Train both on the same split.
Example 6 — Regularize with dropout, weight decay and early stopping
Section titled “Example 6 — Regularize with dropout, weight decay and early stopping”Goal: Watch a large network overfit the churn data, add dropout, weight decay and an early-stopping class that keeps the best weights, and then measure what each tool contributes by changing one setting at a time.
Step 1 — Watch a large network overfit
Section titled “Step 1 — Watch a large network overfit”def fresh_loader() -> DataLoader: """A loader with a newly seeded generator: the same batches in every run.""" return DataLoader(train_ds, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42))
def fit_history(model, optimizer, epochs: int) -> list[float]: """Train for a fixed number of epochs and return the validation losses.""" losses, run_loader = [], fresh_loader() for _ in range(epochs): train_one_epoch(model, run_loader, loss_fn, optimizer) losses.append(evaluate_loss(model, X_va, y_va, loss_fn)) return losses
torch.manual_seed(42)big = ChurnMLP(22, hidden=(128, 64))big_val = fit_history(big, torch.optim.AdamW(big.parameters(), lr=1e-3, weight_decay=0.0), epochs=40)best_epoch = int(np.argmin(big_val)) + 1print(sum(p.numel() for p in big.parameters()))print(f"best epoch {best_epoch}: val {min(big_val):.4f}")print(f"epoch 40: val {big_val[-1]:.4f}")11265best epoch 6: val 0.8004epoch 40: val 1.1022The bigger network has almost nine times more parameters than ChurnMLP(22) (11,265 against 1,281), no dropout and no weight decay. The learning rate is the same as before. Its validation loss is lowest after a few epochs and then climbs far above its minimum by epoch 40: the network memorizes the training rows. Training longer makes this model worse.
Step 2 — See dropout in train and eval mode
Section titled “Step 2 — See dropout in train and eval mode”torch.manual_seed(42)drop = nn.Dropout(p=0.5)ones = torch.ones(8)print(drop.training, drop(ones))drop.eval()print(drop.training, drop(ones))True tensor([2., 2., 2., 2., 0., 2., 0., 0.])False tensor([1., 1., 1., 1., 1., 1., 1., 1.])In train mode, dropout zeroed 3 of the 8 values and doubled the others, which is the scaling with . Each value is dropped with probability 0.5, so the count varies from call to call, but the expected mean stays 1. In eval mode, dropout is the identity. A model that you evaluate in train mode adds this noise to every prediction.
Step 3 — Write an early-stopping class
Section titled “Step 3 — Write an early-stopping class”import copy
class EarlyStopping: """Stop when the validation loss has not improved for `patience` epochs."""
def __init__(self, patience: int = 5, min_delta: float = 0.0) -> None: self.patience = patience self.min_delta = min_delta self.best_loss = float("inf") self.best_epoch = 0 self.best_state: dict[str, torch.Tensor] = {} self.bad_epochs = 0
def step(self, val_loss: float, model: nn.Module, epoch: int) -> bool: """Record one epoch. Return True when training should stop.""" if val_loss < self.best_loss - self.min_delta: self.best_loss, self.best_epoch = val_loss, epoch self.best_state = copy.deepcopy(model.state_dict()) self.bad_epochs = 0 else: self.bad_epochs += 1 return self.bad_epochs >= self.patienceThe class keeps state across epochs: the best loss, its epoch, a copy of the best weights and a counter. It is a training callback in the sense of module 22: the loop calls it once per epoch. copy.deepcopy matters: state_dict() returns references to the live tensors, which the next optimizer step would change.
Step 4 — Train the same network with regularization and early stopping
Section titled “Step 4 — Train the same network with regularization and early stopping”torch.manual_seed(42)reg = ChurnMLP(22, hidden=(128, 64), dropout=0.3)optimizer = torch.optim.AdamW(reg.parameters(), lr=1e-3, weight_decay=0.05)stopper = EarlyStopping(patience=5)reg_history, reg_loader = {"train": [], "val": []}, fresh_loader()for epoch in range(1, 101): reg_history["train"].append(train_one_epoch(reg, reg_loader, loss_fn, optimizer)) reg_history["val"].append(evaluate_loss(reg, X_va, y_va, loss_fn)) if stopper.step(reg_history["val"][-1], reg, epoch): breakprint(f"stopped after epoch {epoch}; best epoch {stopper.best_epoch}" f" with val loss {stopper.best_loss:.4f}")stopped after epoch 17; best epoch 12 with val loss 0.7951Only two settings differ from Step 1: dropout=0.3 and weight_decay=0.05. The architecture, the learning rate, the seed and the data order are the same. The loop allows up to 100 epochs, but early stopping ends it once 5 epochs in a row bring no improvement. You no longer guess the number of epochs: the validation set decides.
Step 5 — Restore the best weights and score the test set
Section titled “Step 5 — Restore the best weights and score the test set”def test_auc(model: nn.Module) -> float: """ROC-AUC on the test customers; logits rank like probabilities.""" model.eval() with torch.no_grad(): return roc_auc_score(y_test, model(X_te).numpy())
reg.load_state_dict(stopper.best_state)print(f"big, epoch 40: {test_auc(big):.3f}")print(f"regularized, best epoch restored: {test_auc(reg):.3f}")print(f"logistic regression: {roc_auc_score(y_test, logreg_proba):.3f}")big, epoch 40: 0.805regularized, best epoch restored: 0.830logistic regression: 0.813load_state_dict puts the saved copy back, so reg now holds the weights of its best epoch, not of its last one. The network that trained for 40 epochs without any protection ranks the test customers worse than the logistic regression. The regularized, early-stopped network beats it. The test scores only illustrate the effect; the validation loss made every choice here. This comparison still mixes three tools, so the next step separates them.
Step 6 — Isolate each tool with an ablation
Section titled “Step 6 — Isolate each tool with an ablation”An ablation changes one setting at a time and keeps everything else fixed, so that each difference in the result has one cause. Each run below trains the big network for 40 epochs. An early-stopping object watches every run; when it fires, it freezes its copy of the best weights, and the run continues only so that you can see what would have happened without stopping.
def ablation_run(dropout: float, weight_decay: float) -> tuple[list[float], dict]: torch.manual_seed(42) model = ChurnMLP(22, hidden=(128, 64), dropout=dropout) opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=weight_decay) watcher, stop_epoch, losses = EarlyStopping(patience=5), None, [] run_loader = fresh_loader() for epoch in range(1, 41): train_one_epoch(model, run_loader, loss_fn, opt) losses.append(evaluate_loss(model, X_va, y_va, loss_fn)) if stop_epoch is None and watcher.step(losses[-1], model, epoch): stop_epoch = epoch # a real run would stop here auc_40 = test_auc(model) model.load_state_dict(watcher.best_state) # what early stopping returns return losses, {"best": watcher.best_epoch, "stop": stop_epoch, "val_40": losses[-1], "auc_40": auc_40, "auc_es": test_auc(model)}
configs = {"none": (0.0, 0.0), "dropout 0.3": (0.3, 0.0), "weight decay 0.05": (0.0, 0.05), "both": (0.3, 0.05)}curves = {}print("setting best stop val@40 AUC@40 AUC early-stopped")for name, (p, wd) in configs.items(): curves[name], r = ablation_run(p, wd) print(f"{name:18s} {r['best']:5d} {r['stop']:4d} {r['val_40']:6.3f}" f" {r['auc_40']:6.3f} {r['auc_es']:6.3f}")setting best stop val@40 AUC@40 AUC early-stoppednone 6 11 1.102 0.805 0.828dropout 0.3 12 17 0.885 0.823 0.830weight decay 0.05 6 11 1.074 0.806 0.829both 12 17 0.888 0.822 0.830Read the table one column at a time:
- best and stop: without dropout, the validation loss is lowest at epoch 6 and early stopping fires at epoch 11. With dropout, both come 6 epochs later.
- val@40 and AUC@40 (what you get without early stopping): the unprotected network ends with a validation loss of 1.102 and a test AUC of 0.805. Dropout alone cuts most of that damage (0.885 and 0.823). Weight decay of 0.05 alone barely changes it (1.074 and 0.806); for this network and 40 epochs, that strength is too weak. Both together behave like dropout alone.
- AUC early-stopped: once early stopping restores the best epoch, all four settings land between 0.828 and 0.830. On one split of 1,250 customers, differences of 0.002 are noise.
So on this data, early stopping does most of the work. Dropout makes training robust: the climb after the minimum is much slower, so a stop that comes late, or a fixed number of epochs that is too large, costs far less. It does not find a clearly better minimum. Exercise M42-X05 on the exercises page shows that stronger weight decay does matter.
Step 7 — Plot the validation curves
Section titled “Step 7 — Plot the validation curves”fig, ax = plt.subplots(figsize=(7, 4))for name, losses in curves.items(): ax.plot(range(1, len(losses) + 1), losses, label=name)ax.xaxis.set_major_locator(MaxNLocator(integer=True))ax.set_xlabel("epoch")ax.set_ylabel("validation loss")ax.set_title("Big network: validation loss with and without regularization")ax.legend(title="regularization")plt.show()
The curves pair up by one setting only: with or without dropout. Weight decay at this strength moves each curve very little. All four reach about 0.80; after that, the networks without dropout climb fast and the ones with dropout stay much lower.
Common mistakes:
- Storing
model.state_dict()without a copy. The “best” weights then change with every step, and you restore the last weights instead of the best. - Changing several settings at once and crediting one of them. Compare runs that differ in one setting, with the same seed and data order.
- Choosing the patience or the number of epochs on the test set. Then the test score is no longer an honest estimate. Use the validation set for every decision; the test AUC columns here only illustrate the effect.
- Forgetting to call
load_state_dict(stopper.best_state)after the loop. The model keeps the weights of the last epoch, which arepatienceepochs past the best.
Example 7 — A CNN for handwritten digits
Section titled “Example 7 — A CNN for handwritten digits”Goal: Train a small convolutional network on scikit-learn’s 8×8 digit images and compare its accuracy with a logistic regression on the raw pixels.
Step 1 — Load the images as an NCHW tensor
Section titled “Step 1 — Load the images as an NCHW tensor”from sklearn.datasets import load_digits
digits = load_digits()print(digits.images.shape, digits.images.min(), digits.images.max())images = torch.tensor(digits.images / 16.0, dtype=torch.float32).unsqueeze(1)labels = torch.tensor(digits.target)print(images.shape, labels.dtype, labels[:10])idx_train, idx_test = train_test_split( np.arange(len(labels)), test_size=0.25, stratify=digits.target, random_state=42)print(len(idx_train), len(idx_test))(1797, 8, 8) 0.0 16.0torch.Size([1797, 1, 8, 8]) torch.int64 tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])1347 450load_digits has 1,797 grayscale images of 8×8 pixels with values from 0 to 16. Dividing by 16 scales them to [0, 1]. unsqueeze(1) adds the channel dimension, so the shape becomes NCHW: (1797, 1, 8, 8). The labels are int64, as CrossEntropyLoss needs. Splitting an index array lets you split the tensors and the scikit-learn arrays the same way.
Step 2 — Trace the shapes through the layers
Section titled “Step 2 — Trace the shapes through the layers”torch.manual_seed(42)conv = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, padding=1)pool = nn.MaxPool2d(kernel_size=2)batch = images[:4]h1 = torch.relu(conv(batch))h2 = pool(h1)flat = h2.flatten(start_dim=1)print([tuple(t.shape) for t in (batch, h1, h2, flat)])print(conv.weight.shape, conv.bias.shape)[(4, 1, 8, 8), (4, 16, 8, 8), (4, 16, 4, 4), (4, 256)]torch.Size([16, 1, 3, 3]) torch.Size([16])The convolution keeps 8×8 (the formula gives ) and makes 16 channels. Max pooling halves each side to 4×4. flatten(start_dim=1) keeps the batch dimension and joins the rest: 16·4·4 = 256 numbers per image. The convolution has only 16 kernels of 3×3 weights plus 16 biases: 160 parameters.
Step 3 — Define the CNN as a module
Section titled “Step 3 — Define the CNN as a module”class DigitCNN(nn.Module): """conv -> ReLU -> max pool -> linear: 10 logits per 8x8 image."""
def __init__(self, n_filters: int = 16, n_classes: int = 10) -> None: super().__init__() self.n_filters = n_filters self.n_classes = n_classes self.conv = nn.Conv2d(1, n_filters, kernel_size=3, padding=1) self.pool = nn.MaxPool2d(kernel_size=2) self.fc = nn.Linear(n_filters * 4 * 4, n_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.pool(torch.relu(self.conv(x))) # (n, 16, 4, 4) return self.fc(x.flatten(start_dim=1)) # (n, 10) logits
torch.manual_seed(42)cnn = DigitCNN()print(sum(p.numel() for p in cnn.parameters()))print(cnn(images[:2]).shape)2730torch.Size([2, 10])The same pattern as ChurnMLP: hyperparameters and layers in __init__, the computation in forward. torch.relu is a function with no weights, so it needs no attribute. The final layer has 256·10 + 10 = 2,570 parameters, so the whole network has 2,730.
Step 4 — Train for 8 epochs
Section titled “Step 4 — Train for 8 epochs”X_img_tr, y_img_tr = images[idx_train], labels[idx_train]X_img_te, y_img_te = images[idx_test], labels[idx_test]digit_loader = DataLoader(TensorDataset(X_img_tr, y_img_tr), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42))ce_loss = nn.CrossEntropyLoss()cnn_opt = torch.optim.AdamW(cnn.parameters(), lr=0.01)
def accuracy(model: nn.Module, X: torch.Tensor, y: torch.Tensor) -> float: model.eval() with torch.no_grad(): return (model(X).argmax(dim=1) == y).float().mean().item()
for epoch in range(1, 9): train_loss = train_one_epoch(cnn, digit_loader, ce_loss, cnn_opt) if epoch % 2 == 0: print(f"epoch {epoch} training loss {train_loss:.4f}")epoch 2 training loss 0.2587epoch 4 training loss 0.1027epoch 6 training loss 0.0575epoch 8 training loss 0.0419train_one_epoch from Example 4 works unchanged: it only needs a model, a loader, a loss and an optimizer. That is the payoff of writing the loop as a function. argmax(dim=1) picks the class with the largest logit; the softmax is not needed for that, because it keeps the order. The loop prints only the training loss. The test set is scored once, in the next step; to choose the number of epochs, you would watch a validation set as in Example 6.
Step 5 — Compare with a logistic regression on the pixels
Section titled “Step 5 — Compare with a logistic regression on the pixels”pixels = digits.data / 16.0 # (1797, 64): each image as one rowpixel_model = LogisticRegression(max_iter=2000).fit(pixels[idx_train], digits.target[idx_train])pixel_acc = pixel_model.score(pixels[idx_test], digits.target[idx_test])print(f"logistic regression: {pixel_acc:.3f}")print(f"DigitCNN: {accuracy(cnn, X_img_te, y_img_te):.3f}")logistic regression: 0.962DigitCNN: 0.973On these tiny, centered images, a linear model on 64 pixels is already strong. The CNN makes fewer mistakes with fewer than 3,000 weights, because its kernels detect strokes wherever they appear. This page does not test larger images; on photos, convolutional networks are the standard tool for exactly this reason.
Step 6 — Plot sample predictions
Section titled “Step 6 — Plot sample predictions”with torch.no_grad(): pred = cnn(X_img_te).argmax(dim=1)wrong = torch.nonzero(pred != y_img_te).flatten()[:6]right = torch.nonzero(pred == y_img_te).flatten()[:6]print(len(torch.nonzero(pred != y_img_te)), "mistakes out of", len(y_img_te))fig, axes = plt.subplots(2, 6, figsize=(9, 3.6))for ax, i in zip(axes.flat, torch.cat([right, wrong]).tolist(), strict=True): ax.imshow(X_img_te[i, 0], cmap="gray_r") ok = pred[i] == y_img_te[i] ax.set_title(f"pred {pred[i].item()} / true {y_img_te[i].item()}", fontsize=9, color="black" if ok else "firebrick") ax.axis("off")fig.suptitle("DigitCNN on test images: top row correct, bottom row mistakes")plt.show()12 mistakes out of 450
Looking at the mistakes is an essential check. Most of them are digits with unusual shapes or very few strokes. If the mistakes were clear digits, the model or the data pipeline would have a bug, such as images that were flipped or not scaled.
Common mistakes:
- Passing images of shape
(n, 8, 8)tonn.Conv2d. It reads a 3-D input as one unbatched image(C, H, W), so the batch sizenbecomes the number of channels. It fails withexpected input[1, n, 8, 8] to have 1 channels, but got n channels instead. Add the channel dimension withunsqueeze(1). - Using float labels of shape
(n,)withCrossEntropyLoss. It raisesexpected target dtype to be Long or Byte. It accepts int64 class indices of shape(n,), or float class probabilities (for example one-hot rows) of shape(n, 10). - Computing the flattened size by hand and getting it wrong after you change the kernel or the padding. Trace the shapes with one batch, as in Step 2.
Example 8 — Save the model and load it back
Section titled “Example 8 — Save the model and load it back”Goal: Save the early-stopped churn network to output/, load it into a fresh model for prediction, and save a full checkpoint that also holds the hyperparameters and the optimizer state.
Step 1 — Save the state_dict
Section titled “Step 1 — Save the state_dict”from pathlib import Path
out_dir = Path("output")out_dir.mkdir(exist_ok=True)weights_path = out_dir / "churn_mlp.pt"torch.save(reg.state_dict(), weights_path)print(weights_path.exists())print(list(reg.state_dict().keys()))True['net.0.weight', 'net.0.bias', 'net.3.weight', 'net.3.bias', 'net.6.weight', 'net.6.bias']reg holds the best weights since Step 5 of Example 6. The keys follow the attribute names: net is the nn.Sequential, and 0, 3 and 6 are the positions of the three nn.Linear layers inside it. The ReLU and dropout layers at the other positions have no parameters, so they have no keys.
Step 2 — Load the weights into a fresh model
Section titled “Step 2 — Load the weights into a fresh model”torch.manual_seed(0) # a different random start, to prove the load worksloaded = ChurnMLP(22, hidden=(128, 64), dropout=0.3)result = loaded.load_state_dict(torch.load(weights_path, weights_only=True))print(result)loaded.eval()with torch.no_grad(): same = torch.equal(loaded(X_te), reg(X_te))print(same)<All keys matched successfully>TrueYou rebuild the architecture with the same hyperparameters, then copy the saved tensors into it. load_state_dict reports keys that were missing or unexpected; here there are none. torch.equal checks that the two models give exactly the same logits for every test customer. Without eval(), dropout would make them differ.
Step 3 — Load into the wrong architecture
Section titled “Step 3 — Load into the wrong architecture”wrong = ChurnMLP(22, hidden=(32, 16))try: wrong.load_state_dict(torch.load(weights_path, weights_only=True))except RuntimeError as err: lines = str(err).splitlines() print(lines[0]) for line in lines[1:]: print(line.strip().split(":")[0])Error(s) in loading state_dict for ChurnMLP:size mismatch for net.0.weightsize mismatch for net.0.biassize mismatch for net.3.weightsize mismatch for net.3.biassize mismatch for net.6.weightThe file stores tensors, not the architecture. A model with other hidden sizes has parameters of other shapes, so the load fails with a clear message. This is why you must save the hyperparameters next to the weights.
Step 4 — Save and reload a full checkpoint
Section titled “Step 4 — Save and reload a full checkpoint”checkpoint = { "config": {"n_features": reg.n_features, "hidden": list(reg.hidden), "dropout": reg.dropout}, "model_state": reg.state_dict(), "optimizer_state": optimizer.state_dict(), "epoch": stopper.best_epoch, "val_loss": stopper.best_loss,}torch.save(checkpoint, out_dir / "churn_checkpoint.pt")
ckpt = torch.load(out_dir / "churn_checkpoint.pt", weights_only=True)config = ckpt["config"]restored = ChurnMLP(config["n_features"], tuple(config["hidden"]), config["dropout"])restored.load_state_dict(ckpt["model_state"])restored.eval()print(config, ckpt["epoch"], round(ckpt["val_loss"], 4))with torch.no_grad(): print(torch.equal(restored(X_te), reg(X_te))){'n_features': 22, 'hidden': [128, 64], 'dropout': 0.3} 12 0.7951TrueThe checkpoint is a plain dictionary of tensors, numbers, strings and lists, so weights_only=True can load it safely. The config entry rebuilds the model without guessing. The optimizer state holds Adam’s running averages; you need it to continue training with optimizer.load_state_dict(...). Here, the stored epoch is the best epoch, and the optimizer state is from the last one; in a resumable job, you save both from the same epoch.
Common mistakes:
- Loading without
weights_only=Trueon an old PyTorch version. A malicious file could run code. Always pass it. - Forgetting
model.eval()after loading. The loaded model is in train mode, and dropout changes every prediction. - Saving into
data/or the current folder without a plan. Keep models inoutput/(or amodels/folder) and add the hyperparameters to the file name or the checkpoint.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| float64 features into a float32 model | RuntimeError: mat1 and mat2 must have the same dtype |
convert once with .float() or dtype=torch.float32 |
no optimizer.zero_grad() |
the loss jumps around or explodes | call zero_grad() before backward() in every step |
a sigmoid at the end of the model with BCEWithLogitsLoss |
training stalls; probabilities squeezed toward 0.5–0.73 | return logits; apply torch.sigmoid only to predict |
output (n, 1) and target (n,) |
ValueError: Target size ... must be the same as input size for BCE; an (n, n) broadcast and a UserWarning for MSE |
squeeze(1) the output or unsqueeze(1) the target |
float labels with CrossEntropyLoss |
RuntimeError: expected target dtype to be Long or Byte |
use int64 class indices: labels.long() |
| evaluating in train mode | predictions change between calls; scores look noisy | model.eval() and torch.no_grad() for every evaluation |
forgetting model.train() after evaluation |
dropout stays off; regularization silently disappears | call model.train() at the start of each epoch |
early-stopping state without deepcopy |
the “best” model equals the last model | copy.deepcopy(model.state_dict()) |
torch.load without weights_only=True |
a pickle file can run arbitrary code | torch.load(path, weights_only=True) |
t.std() to standardize |
values differ slightly from StandardScaler |
t.std(dim=0, correction=0) |
| several threads per process in parallel jobs | slow training; last digits that differ between machines with other thread counts | torch.set_num_threads(1) early in each script |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web and mobile apps: photo apps, document scanners and content moderation run CNNs like
DigitCNN, trained in PyTorch and exported to a server or a phone. - Optimization and engineering tools: autograd differentiates any Python computation made of tensor operations. Engineers use it to fit physical models, tune simulation parameters or calibrate a camera, with no neural network at all.
- Automation and long jobs: the checkpoint pattern of Example 8 (save the state every epoch, resume after a crash) is the same pattern that backup tools, web crawlers and ETL jobs use to restart where they stopped.
- Tooling:
nn.Moduleis a clean example of the composite pattern: modules contain modules, and one call (parameters(),train(),state_dict()) walks the whole tree. GUI toolkits and HTML document trees use the same design.
Summary
Section titled “Summary”- A tensor is a NumPy-like array with a dtype and a shape. Use float32 for features and weights, int64 for class labels. Broadcasting follows NumPy’s rules.
torch.set_num_threads(1)andtorch.manual_seed(42)make runs reproducible; round printed losses and metrics.- Autograd records the operations on tensors with
requires_grad=True.backward()fills.gradand adds to it. Updates and evaluation go insidetorch.no_grad(). - A model is an
nn.Modulesubclass: hyperparameters and layers in__init__, the computation inforward, called asmodel(x).parameters()lists the learned tensors;state_dict()maps their names to values. - Classifiers return logits.
BCEWithLogitsLoss(withpos_weightfor imbalance) andCrossEntropyLossapply the sigmoid or softmax inside. - Each training step is
zero_grad(),backward(),step()on a batch from aDataLoader. Write the epoch as a function and reuse it. - Switch with
model.train()andmodel.eval(). Use dropout, AdamW’s weight decay and early stopping with patience on a validation split to fight overfitting. - A CNN uses shared 3×3 kernels, channels and pooling on NCHW tensors, and beats a pixel-wise linear model on images.
- Save
state_dict()(plus the hyperparameters) withtorch.save, and load it withtorch.load(..., weights_only=True)into a rebuilt model.
Self-check questions
Section titled “Self-check questions”Q1. What do torch.tensor([1, 2, 3]).dtype and torch.tensor([1.0, 2.0]).dtype return, and what dtype does torch.from_numpy(np.array([1.0, 2.0])) have?
Answer
torch.int64, torch.float32 and torch.float64. Python floats become float32, but NumPy’s default float64 is kept. Convert it with .float() before you feed it to a model.
Q2. Why does this page call torch.set_num_threads(1) at the start?
Answer
With several threads, PyTorch splits sums into parts, and float addition is not exactly associative, so results can depend on the number of threads. The default number differs between machines. One fixed thread gives the same additions in the same order everywhere, so the results are reproducible across machines with the same library versions. It also avoids oversubscription when several processes run at once. For small networks, it costs no speed.
Q3. You call loss.backward() twice without zeroing. What is in w.grad?
Answer
The sum of the two gradients: twice the gradient if the two losses are the same. backward() adds to .grad. Reset it with optimizer.zero_grad() (or w.grad.zero_()) before each backward pass.
Q4. Name three things that nn.Module.__init__ and a minilearn estimator’s __init__ have in common, and one difference.
Answer
Both receive the hyperparameters as arguments, store them as attributes, and belong to a base class that adds shared behavior (get_params() in minilearn, parameters() and state_dict() in PyTorch). The difference: a PyTorch module also creates its layers in __init__, so its learned parameters exist at once with random values. In minilearn, the learned _ attributes appear only in fit().
Q5. Why does a binary PyTorch classifier usually have no sigmoid in its forward method?
Answer
BCEWithLogitsLoss applies the sigmoid inside the loss with a numerically stable formula. The model returns logits. To get probabilities for prediction, apply torch.sigmoid(model(x)) outside the model.
Q6. What is the difference between model.eval() and torch.no_grad()?
Answer
model.eval() changes how layers behave: dropout stops dropping values and batch normalization uses its stored statistics. torch.no_grad() stops autograd from recording a graph, which saves memory and time. Neither one does the other’s job, so use both for evaluation.
Q7. The training data has 1,000 positive and 4,000 negative samples. What pos_weight balances them, and what does it do to the predicted probabilities?
Answer
pos_weight = 4000 / 1000 = 4.0. Each positive sample counts four times in the loss, so the model pays more attention to positives. Its probabilities move up, above the real positive rate. The ranking (ROC-AUC) changes little, but the right threshold changes.
Q8. A convolution has kernel_size=3, padding=0 and stride=1. What output size does it give for a 28×28 input? And after a MaxPool2d(2)?
Answer
, so 26×26. Max pooling with a 2×2 window halves it to 13×13.
Q9. Early stopping with patience=5 sees the best validation loss at epoch 12 and no improvement after it. When does training stop, and which weights should the model keep?
Answer
It stops after epoch 17, the fifth epoch in a row without improvement. The model should keep the weights of epoch 12. That is why the early-stopping object stores a deep copy of the best state_dict and the loop restores it.
Q10. Why save model.state_dict() instead of torch.save(model), and why pass weights_only=True when you load?
Answer
The state_dict holds only tensors with stable names. It does not depend on where the class lives, so you can refactor the code and still load the weights into a rebuilt model. torch.save(model) pickles the whole object and breaks when the class moves. weights_only=True stops torch.load from running arbitrary pickled code. That makes loading a shared file much safer, though not risk-free: prefer trusted sources and an up-to-date PyTorch.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 29 exercises on tensors, autograd, modules, training loops, CNNs and checkpoints, with hints and full solutions.
- Mini-project: wrap a PyTorch MLP in a scikit-learn-compatible classifier and run it in a real
Pipelineon the churn data. - Cheat sheet: tensors, autograd, layers, losses, optimizers, the training loop and saving on one page.
- Next module: 43. Interpretability explains what your models learned with coefficients, permutation importance, partial dependence and SHAP.