42. Deep learning with PyTorch — Exercises
These exercises practice every idea of the PyTorch lesson. They use the churn data (data/customers.csv), the house sales (data/houses.csv) and scikit-learn’s 8×8 digits. Every training run is small, so each one finishes in about a second on a laptop CPU.
How to work:
- Read the task and the expected output.
- Copy the setup block below and the starter code into one script, for example
exercise.py. Replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Add the same checks to your own code.
Every exercise starts with this block. It fixes the seeds and the thread count, and defines three helpers from the lesson:
churn_tensors()returns the scaled churn features and targets as float32 tensors, split as in the lesson: 3,000 training rows, 750 validation rows and 1,250 test rows with 22 features.digit_tensors()returns the digit images in NCHW layout, scaled to [0, 1], with 1,347 training and 450 test images.train_one_epoch(model, loader, loss_fn, optimizer)runs one epoch in train mode and returns the mean training loss.
import copy
import numpy as npimport pandas as pdimport torchfrom torch import nnfrom torch.utils.data import DataLoader, Dataset, TensorDataset
torch.set_num_threads(1) # results depend on the thread count: fix ittorch.manual_seed(42)
def churn_tensors() -> tuple[torch.Tensor, ...]: """Scaled churn data as float32 tensors: X_tr, X_va, X_te, y_tr, y_va, y_te.""" from sklearn.compose import ColumnTransformer, make_column_selector from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv") X = customers.drop(columns=["customer_id", "signup_date", "churned"]) y = customers["churned"] X_rest, X_te, y_rest, y_te = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42 ) X_tr, X_va, y_tr, y_va = 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")), ]) arrays = [prep.fit_transform(X_tr), prep.transform(X_va), prep.transform(X_te)] arrays += [y_tr.to_numpy(), y_va.to_numpy(), y_te.to_numpy()] return tuple(torch.tensor(a, dtype=torch.float32) for a in arrays)
def digit_tensors() -> tuple[torch.Tensor, ...]: """8x8 digits as NCHW float32 images in [0, 1]: X_tr, X_te, y_tr, y_te.""" from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split
digits = load_digits() images = torch.tensor(digits.images / 16.0, dtype=torch.float32).unsqueeze(1) labels = torch.tensor(digits.target) idx_tr, idx_te = train_test_split( np.arange(len(labels)), test_size=0.25, stratify=digits.target, random_state=42 ) return images[idx_tr], images[idx_te], labels[idx_tr], labels[idx_te]
def train_one_epoch(model, loader, loss_fn, optimizer) -> float: """One pass over the loader in train mode; 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) return total / len(loader.dataset)Warm-up
Section titled “Warm-up”M42-W01 · Build tensors from customer values
Section titled “M42-W01 · Build tensors from customer values”Four customers have the monthly charges 29.95, 54.50, 89.00 and 112.40 and the support-ticket counts 0, 3, 1 and 4. Create one tensor for each list and print the dtype and shape of both. Then compute the charges per ticket, counting one extra ticket so that a customer with 0 tickets does not cause a division by zero: charges / (tickets + 1). Print the result rounded to 2 decimals.
torch.float32 (4,)torch.int64 (4,)tensor([29.9500, 13.6200, 44.5000, 22.4800])# TODO: create charges and tickets as tensors# TODO: print the dtype and shape of each# TODO: compute charges / (tickets + 1) and print it rounded to 2 decimalsHint 1
torch.tensor([29.95, 54.50, 89.00, 112.40]) builds a float32 tensor. A list of Python ints gives int64.
Hint 2
Dividing a float32 tensor by an int64 tensor gives float32. t.round(decimals=2) rounds every element.
Solution
charges = torch.tensor([29.95, 54.50, 89.00, 112.40])tickets = torch.tensor([0, 3, 1, 4])print(charges.dtype, tuple(charges.shape))print(tickets.dtype, tuple(tickets.shape))per_ticket = charges / (tickets + 1)print(per_ticket.round(decimals=2))assert charges.dtype == torch.float32 and tickets.dtype == torch.int64assert per_ticket.dtype == torch.float32assert torch.isclose(per_ticket[1], torch.tensor(13.625))torch.float32 (4,)torch.int64 (4,)tensor([29.9500, 13.6200, 44.5000, 22.4800])How it works:
- Python floats become
float32, the default dtype for deep learning. Python ints becomeint64. tickets + 1adds 1 to every element (broadcasting a scalar).- Mixing float32 and int64 promotes the result to float32, as in NumPy.
Alternative: convert the counts first with tickets.float(). The result is the same, and the dtype of every intermediate tensor is explicit.
M42-W02 · Predict the shapes
Section titled “M42-W02 · Predict the shapes”Predict the output: a batch of 64 customers with 22 features has shape (64, 22). Write down the shape that each line prints, then run the code.
batch = torch.zeros(64, 22)print(tuple(batch[:, 0].shape))print(tuple(batch[:, :1].shape))print(tuple(batch.unsqueeze(0).shape))print(tuple(batch.sum(dim=0).shape))print(tuple(batch.mean(dim=1, keepdim=True).shape))print(tuple(batch.reshape(-1).shape))print(tuple(batch.T.shape))print(tuple(batch[:, :1].squeeze(1).shape))Acceptance criteria:
- Write your 8 predictions line by line, then run the code.
- Your predictions match the Output in the solution.
Hint 1
An integer index removes a dimension; a slice keeps it. A reduction with dim=d removes dimension d, unless keepdim=True.
Hint 2
reshape(-1) flattens everything into one dimension: 64 · 22 elements. .T swaps the two dimensions.
Solution
batch = torch.zeros(64, 22)print(tuple(batch[:, 0].shape))print(tuple(batch[:, :1].shape))print(tuple(batch.unsqueeze(0).shape))print(tuple(batch.sum(dim=0).shape))print(tuple(batch.mean(dim=1, keepdim=True).shape))print(tuple(batch.reshape(-1).shape))print(tuple(batch.T.shape))print(tuple(batch[:, :1].squeeze(1).shape))assert batch.reshape(-1).numel() == 64 * 22(64,)(64, 1)(1, 64, 22)(22,)(64, 1)(1408,)(22, 64)(64,)How it works:
batch[:, 0]picks one column with an integer, so the column dimension disappears:(64,).batch[:, :1]slices one column and keeps it:(64, 1).unsqueeze(0)adds a new dimension of size 1 in front.sum(dim=0)reduces over the rows: one value per feature.mean(dim=1, keepdim=True)reduces over the features but keeps a dimension of size 1, which is handy for broadcasting back against the batch.reshape(-1)computes the missing size itself: 1,408..Ttransposes.squeeze(1)removes the size-1 dimension that the slice kept.
M42-W03 · Standardize a batch with broadcasting
Section titled “M42-W03 · Standardize a batch with broadcasting”The batch below holds tenure_months, monthly_charges and logins_last_30d for 4 customers. Standardize each column with its mean and its population standard deviation, using broadcasting. Print the result with 3 decimals and check it against scikit-learn’s StandardScaler.
tensor([[-1.0900, 0.5490, -1.0570], [ 0.3260, -0.5150, 0.4700], [-0.7170, 1.2930, -0.8220], [ 1.4810, -1.3280, 1.4090]])batch = torch.tensor([ [2.0, 89.0, 1.0], [40.0, 55.5, 14.0], [12.0, 112.4, 3.0], [71.0, 29.9, 22.0],])# TODO: compute the column means and population standard deviations# TODO: standardize with broadcasting and print the result rounded to 3 decimals# TODO: compare with sklearn.preprocessing.StandardScalerHint 1
batch.mean(dim=0) gives one mean per column, shape (3,). Broadcasting subtracts it from every row.
Hint 2
batch.std(dim=0) divides by . StandardScaler divides by : pass correction=0.
Solution
from sklearn.preprocessing import StandardScaler
batch = torch.tensor([ [2.0, 89.0, 1.0], [40.0, 55.5, 14.0], [12.0, 112.4, 3.0], [71.0, 29.9, 22.0],])mean = batch.mean(dim=0)std = batch.std(dim=0, correction=0)scaled = (batch - mean) / stdprint(scaled.round(decimals=3))expected = torch.tensor(StandardScaler().fit_transform(batch.numpy()))assert torch.allclose(scaled, expected, atol=1e-5)assert torch.allclose(scaled.mean(dim=0), torch.zeros(3), atol=1e-6)tensor([[-1.0900, 0.5490, -1.0570], [ 0.3260, -0.5150, 0.4700], [-0.7170, 1.2930, -0.8220], [ 1.4810, -1.3280, 1.4090]])How it works:
meanandstdhave shape(3,). Against the(4, 3)batch, they broadcast to every row.correction=0divides by , the population standard deviation thatStandardScaleruses.batch.numpy()shares memory with the tensor, which is fine for reading.torch.allclosecompares with a tolerance, because float32 and float64 round differently.
Alternative: torch.nn.functional.normalize does something else (it scales each row to length 1), so it is not a replacement. For a reusable step, fit a StandardScaler once on the training rows and convert its output to a tensor, as the setup helper does.
M42-W04 · Fix the bug: the dtype mismatch
Section titled “M42-W04 · Fix the bug: the dtype mismatch”Fix the bug: this code feeds three customers to a linear layer and fails with RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float. Make it run without changing the layer, and print the dtype and the shape of the output.
torch.float32 torch.float32torch.float32 (3, 1)features = np.array([[0.5, -1.2], [1.0, 0.3], [-0.7, 2.1]])layer = nn.Linear(2, 1)logits = layer(torch.from_numpy(features)) # RuntimeErrorprint(logits.dtype, tuple(logits.shape))Hint 1
What dtype does np.array give for floats? What dtype does nn.Linear use for its weights?
Hint 2
Convert the tensor with .float(), or build it with torch.tensor(features, dtype=torch.float32).
Solution
features = np.array([[0.5, -1.2], [1.0, 0.3], [-0.7, 2.1]])layer = nn.Linear(2, 1)x = torch.from_numpy(features).float() # float64 -> float32logits = layer(x)print(x.dtype, layer.weight.dtype)print(logits.dtype, tuple(logits.shape))assert logits.shape == (3, 1)assert logits.dtype == torch.float32torch.float32 torch.float32torch.float32 (3, 1)How it works:
- NumPy creates float64 arrays, and
torch.from_numpykeeps that dtype. nn.Linearcreates float32 weights. A matrix product needs both sides in the same dtype, so PyTorch refuses..float()makes a float32 copy. Convert once, where you build the tensors, not inside the model.
Alternative: torch.as_tensor(features, dtype=torch.float32) converts in one call. Converting the model with layer.double() also works, but it doubles memory and time for no benefit.
M42-W05 · Predict the output: shared memory and .item()
Section titled “M42-W05 · Predict the output: shared memory and .item()”Predict the output: what does each print show? Pay attention to which tensors share memory with the NumPy array.
arr = np.array([10.0, 20.0, 30.0])shared = torch.from_numpy(arr)copied = torch.tensor(arr)arr[1] = 99.0print(shared[1].item(), copied[1].item())total = copied.sum()print(total.ndim, type(total.item()).__name__, total.item())print(shared.tolist())Acceptance criteria:
- Write your 3 predicted lines, then run the code.
- Your predictions match the Output in the solution.
Hint 1
torch.from_numpy shares memory. torch.tensor always copies.
Hint 2
A sum of all elements is a tensor with zero dimensions. .item() returns a Python number.
Solution
arr = np.array([10.0, 20.0, 30.0])shared = torch.from_numpy(arr)copied = torch.tensor(arr)arr[1] = 99.0print(shared[1].item(), copied[1].item())total = copied.sum()print(total.ndim, type(total.item()).__name__, total.item())print(shared.tolist())assert shared[1].item() == 99.0 and copied[1].item() == 20.099.0 20.00 float 60.0[10.0, 99.0, 30.0]How it works:
shareduses the same memory asarr, so the change toarr[1]shows up in it.copiedhas its own memory and keeps 20.0.copied.sum()is a 0-dimensional tensor..item()gives the Pythonfloat60.0..tolist()converts a whole tensor to a Python list of floats.
M42-W06 · Check two gradients by hand
Section titled “M42-W06 · Check two gradients by hand”Use autograd to compute two derivatives and compare each one with its formula:
- at . The formula is .
- The sigmoid at . The formula is .
Print each autograd value and each formula value rounded to 4 decimals.
-18.0 -18.00.235 0.235w = torch.tensor(1.0, requires_grad=True)# TODO: compute f, call backward(), compare w.grad with the formulaz = torch.tensor(0.5, requires_grad=True)# TODO: compute torch.sigmoid(z), call backward(), compare z.grad with the formulaHint 1
After f.backward(), the derivative is in w.grad.
Hint 2
Compute the formula values without a graph: inside with torch.no_grad(): or with plain Python floats.
Solution
w = torch.tensor(1.0, requires_grad=True)f = (3 * w - 6) ** 2f.backward()formula_w = 2 * (3 * 1.0 - 6) * 3print(round(w.grad.item(), 4), round(formula_w, 4))
z = torch.tensor(0.5, requires_grad=True)s = torch.sigmoid(z)s.backward()with torch.no_grad(): formula_z = (s * (1 - s)).item()print(round(z.grad.item(), 4), round(formula_z, 4))assert w.grad.item() == formula_wassert abs(z.grad.item() - formula_z) < 1e-6-18.0 -18.00.235 0.235How it works:
- The forward pass builds a small graph from
wtof.backward()applies the chain rule: the outer square gives , the inner linear part gives 3. torch.sigmoidknows its own derivative, so autograd returns without a formula from you.- The first check is exact, because every number involved is a whole number. The second uses a tolerance.
Alternative: torch.autograd.grad(f, w) returns the gradient as a tuple instead of storing it in w.grad. It is handy when you do not want to touch .grad.
M42-W07 · Fix the bug: gradients that grow
Section titled “M42-W07 · Fix the bug: gradients that grow”Fix the bug: this loop computes the gradient of the same loss three times, but the printed gradient grows. Make every iteration print the true gradient, 6.0.
0 6.01 6.02 6.0w = torch.tensor(2.0, requires_grad=True)for step in range(3): loss = (w * 3.0 - 5.0) ** 2 loss.backward() print(step, w.grad.item()) # 6.0, 12.0, 18.0Hint 1
What does backward() do with the value that is already in w.grad?
Hint 2
Reset with w.grad.zero_() after you use the gradient, or set w.grad = None before each backward pass.
Solution
w = torch.tensor(2.0, requires_grad=True)grads = []for step in range(3): loss = (w * 3.0 - 5.0) ** 2 loss.backward() print(step, w.grad.item()) grads.append(w.grad.item()) w.grad.zero_()assert grads == [6.0, 6.0, 6.0]0 6.01 6.02 6.0How it works:
backward()adds the new gradient tow.grad. Without a reset, the second pass gives 6 + 6 = 12, the third 18.w.grad.zero_()sets the stored gradient to 0 in place. The nextbackward()then starts from zero.- In a training loop,
optimizer.zero_grad()does this for every parameter at once.
Alternative: w.grad = None before backward() also works. optimizer.zero_grad() does exactly that by default (set_to_none=True), which saves a little memory.
M42-W08 · Recompute nn.Linear by hand
Section titled “M42-W08 · Recompute nn.Linear by hand”Create nn.Linear(3, 2) after torch.manual_seed(42). Pass a batch of two customers through it, then compute the same output by hand with x @ W.T + b. Print the shapes of the weight and the bias, the output rounded to 4 decimals and whether both results are close.
(2, 3) (2,)tensor([[-0.8101, 0.9638], [ 0.4487, 1.0764]])Truetorch.manual_seed(42)layer = nn.Linear(3, 2)x = torch.tensor([[0.5, -1.0, 2.0], [1.5, 0.0, -0.5]])# TODO: print the weight and bias shapes# TODO: compute layer(x) and the manual version; compare themHint 1
The weight has shape (out_features, in_features), so you need its transpose.
Hint 2
Use torch.no_grad() so that the outputs carry no graph, and torch.allclose to compare.
Solution
torch.manual_seed(42)layer = nn.Linear(3, 2)x = torch.tensor([[0.5, -1.0, 2.0], [1.5, 0.0, -0.5]])print(tuple(layer.weight.shape), tuple(layer.bias.shape))with torch.no_grad(): out = layer(x) manual = x @ layer.weight.T + layer.biasprint(out.round(decimals=4))print(torch.allclose(out, manual))assert out.shape == (2, 2)assert torch.allclose(out, manual)(2, 3) (2,)tensor([[-0.8101, 0.9638], [ 0.4487, 1.0764]])TrueHow it works:
xis(2, 3)andW.Tis(3, 2), sox @ W.Tis(2, 2): one row per customer, one column per output.- The bias of shape
(2,)broadcasts to both rows. nn.Lineardoes exactly this, with a fused, faster implementation. The result is the same up to float rounding.
Alternative: torch.nn.functional.linear(x, layer.weight, layer.bias) is the functional form of the layer and gives the same result.
M42-W09 · Count the parameters
Section titled “M42-W09 · Count the parameters”Write a function count_parameters(model, trainable_only=False) that returns the number of parameter values in a model. Test it on the network 22 → 32 → 16 → 1 (with ReLUs) from the lesson. Then freeze the first layer (requires_grad_(False) on its parameters) and count only the trainable values.
1281 1281545model = nn.Sequential( nn.Linear(22, 32), nn.ReLU(), nn.Linear(32, 16), nn.ReLU(), nn.Linear(16, 1))
def count_parameters(model: nn.Module, trainable_only: bool = False) -> int: # TODO: sum p.numel() over model.parameters(), filtering on p.requires_grad ...
# TODO: print the total, freeze model[0] and print the trainable countHint 1
p.numel() is the number of elements of one tensor.
Hint 2
model[0].requires_grad_(False) sets requires_grad=False on every parameter of the first layer.
Solution
model = nn.Sequential( nn.Linear(22, 32), nn.ReLU(), nn.Linear(32, 16), nn.ReLU(), nn.Linear(16, 1))
def count_parameters(model: nn.Module, trainable_only: bool = False) -> int: return sum( p.numel() for p in model.parameters() if p.requires_grad or not trainable_only )
total = count_parameters(model)by_formula = (22 * 32 + 32) + (32 * 16 + 16) + (16 * 1 + 1)print(total, by_formula)model[0].requires_grad_(False)print(count_parameters(model, trainable_only=True))assert total == by_formula == 1281assert count_parameters(model, trainable_only=True) == 1281 - (22 * 32 + 32)1281 1281545How it works:
- Each
nn.Linear(i, o)hasi · oweights andobiases. ReLU has no parameters. - Freezing the first layer leaves its parameters in the model but excludes them from training: the optimizer skips tensors without a gradient.
- Freezing is how fine-tuning works: you reuse a pre-trained network, freeze most of it and train only the last layers.
M42-C01 · Write a Dataset class for customer records
Section titled “M42-C01 · Write a Dataset class for customer records”Write a class CustomerDataset(Dataset) that takes a DataFrame, a list of feature columns and a target column. Its __len__ returns the number of rows; its __getitem__(i) returns (features, target) as float32 tensors with shapes (n_features,) and (). Load the first 10 rows of data/customers.csv with the features tenure_months, monthly_charges and support_tickets, wrap the dataset in a DataLoader with batch_size=4 and no shuffling, and print the number of samples, the number of batches and the shapes of every batch.
10 3(3,) () [72.0, 84.69000244140625, 0.0](4, 3) (4,)(4, 3) (4,)(2, 3) (2,)class CustomerDataset(Dataset): def __init__(self, frame: pd.DataFrame, features: list[str], target: str) -> None: # TODO: store the features and the target as float32 tensors ...
def __len__(self) -> int: ...
def __getitem__(self, i: int) -> tuple[torch.Tensor, torch.Tensor]: ...
# TODO: build the dataset from the first 10 customers, wrap it in a DataLoader# TODO: print len(dataset), len(loader) and the shapes of each batchHint 1
Convert the columns once in __init__: torch.tensor(frame[features].to_numpy(), dtype=torch.float32). Then __getitem__ only indexes.
Hint 2
The DataLoader calls __getitem__ once per sample and stacks the results, so 4 samples of shape (3,) become a batch of shape (4, 3).
Solution
class CustomerDataset(Dataset): """Customer rows as (features, target) pairs of float32 tensors."""
def __init__(self, frame: pd.DataFrame, features: list[str], target: str) -> None: self.X = torch.tensor(frame[features].to_numpy(), dtype=torch.float32) self.y = torch.tensor(frame[target].to_numpy(), dtype=torch.float32)
def __len__(self) -> int: return len(self.y)
def __getitem__(self, i: int) -> tuple[torch.Tensor, torch.Tensor]: return self.X[i], self.y[i]
customers = pd.read_csv("data/customers.csv").head(10)dataset = CustomerDataset( customers, ["tenure_months", "monthly_charges", "support_tickets"], "churned")loader = DataLoader(dataset, batch_size=4)print(len(dataset), len(loader))x0, y0 = dataset[0]print(tuple(x0.shape), tuple(y0.shape), x0.tolist())for xb, yb in loader: print(tuple(xb.shape), tuple(yb.shape))assert len(dataset) == 10 and len(loader) == 3assert dataset[9][0].dtype == torch.float3210 3(3,) () [72.0, 84.69000244140625, 0.0](4, 3) (4,)(4, 3) (4,)(2, 3) (2,)How it works:
Datasetis the protocol of module 20:__len__and__getitem__. The base class adds nothing else you must implement.x0.tolist()shows84.69000244140625for the monthly charge 84.69: float32 cannot store 84.69 exactly, and.tolist()converts to a Python float with all its digits. Printing the tensor itself shows 4 decimals.- Converting in
__init__keeps__getitem__cheap, which matters because the loader calls it once per sample in every epoch. - Ten samples in batches of 4 give 3 batches: 4, 4 and 2.
Alternative: for tensors that are already in memory, TensorDataset(X, y) does the same with no class. Write your own Dataset when each sample needs work, such as reading an image file from disk or tokenizing a text.
M42-C02 · Count the batches of an epoch
Section titled “M42-C02 · Count the batches of an epoch”Write a function n_batches(n_samples, batch_size, drop_last=False) that returns the number of batches in one epoch, without building a DataLoader. Check it against len(DataLoader(...)) for these cases and print one line per case with the number of batches and the size of the last batch: 3,000 rows in batches of 64, the same with drop_last=True, 1,347 rows in batches of 32, and 750 rows in one batch of 750.
n=3000 batch= 64 drop_last=False batches=47 last=56n=3000 batch= 64 drop_last=True batches=46 last=64n=1347 batch= 32 drop_last=False batches=43 last=3n= 750 batch=750 drop_last=False batches=1 last=750def n_batches(n_samples: int, batch_size: int, drop_last: bool = False) -> int: # TODO: floor division with drop_last, ceiling division without ...
cases = [(3000, 64, False), (3000, 64, True), (1347, 32, False), (750, 750, False)]# TODO: for each case, compare with len(DataLoader(TensorDataset(...), ...))Hint 1
Without drop_last, the last smaller batch counts: that is a ceiling division. -(-a // b) computes it with integers.
Hint 2
TensorDataset(torch.zeros(n, 1)) is enough to test the loader: only the length matters.
Solution
def n_batches(n_samples: int, batch_size: int, drop_last: bool = False) -> int: if drop_last: return n_samples // batch_size return -(-n_samples // batch_size) # ceiling division
cases = [(3000, 64, False), (3000, 64, True), (1347, 32, False), (750, 750, False)]for n, size, drop in cases: loader = DataLoader(TensorDataset(torch.zeros(n, 1)), batch_size=size, drop_last=drop) last = n - (n_batches(n, size, drop) - 1) * size if not drop else size print(f"n={n:4d} batch={size:3d} drop_last={drop!s:5} " f"batches={n_batches(n, size, drop)} last={last}") assert n_batches(n, size, drop) == len(loader)n=3000 batch= 64 drop_last=False batches=47 last=56n=3000 batch= 64 drop_last=True batches=46 last=64n=1347 batch= 32 drop_last=False batches=43 last=3n= 750 batch=750 drop_last=False batches=1 last=750How it works:
- Without
drop_last, the loader keeps a last, smaller batch: 3,000 = 46 · 64 + 56, so 47 batches. - With
drop_last=True, it skips those 56 rows in this epoch. Shuffling picks other rows to drop in the next epoch, so no row is lost for good. - One batch of the whole set (750 of 750) is full-batch gradient descent.
Alternative: math.ceil(n_samples / batch_size) gives the same count. The integer version avoids float rounding for very large numbers.
M42-C03 · Refactor a row loop into one matrix product
Section titled “M42-C03 · Refactor a row loop into one matrix product”Refactor (loop → vectorized): the code below scores 5 customers with a linear model, one row at a time. Rewrite the scoring as one tensor expression, check that it gives the same scores and print them rounded to 3 decimals.
tensor([-0.8250, -1.3960, 0.5340, -0.5030, 0.0420])Truetorch.manual_seed(42)X = torch.randn(5, 4) # 5 customers, 4 scaled featuresw = torch.tensor([0.8, -1.2, 0.5, 0.3])b = -0.4
scores = []for row in X: total = b for x_j, w_j in zip(row, w): total = total + x_j * w_j scores.append(total)loop_scores = torch.stack(scores)# TODO: compute vec_scores with one expression and compareHint 1
The inner loop is a dot product. Across all rows, it is a matrix-vector product.
Hint 2
X @ w has shape (5,). Add b with broadcasting.
Solution
torch.manual_seed(42)X = torch.randn(5, 4) # 5 customers, 4 scaled featuresw = torch.tensor([0.8, -1.2, 0.5, 0.3])b = -0.4
scores = []for row in X: total = b for x_j, w_j in zip(row, w, strict=True): total = total + x_j * w_j scores.append(total)loop_scores = torch.stack(scores)
vec_scores = X @ w + bprint(vec_scores.round(decimals=3))print(torch.allclose(loop_scores, vec_scores, atol=1e-6))assert vec_scores.shape == (5,)assert torch.allclose(loop_scores, vec_scores, atol=1e-6)tensor([-0.8250, -1.3960, 0.5340, -0.5030, 0.0420])TrueHow it works:
- For each row, the inner loop computes : a dot product plus the bias.
X @ wcomputes all 5 dot products at once. The scalarbbroadcasts.- The loop makes 20 tiny tensor operations in Python; the vectorized version makes 2 calls into optimized code. The loop’s cost grows with every row and feature, so on 3,000 customers it is much slower; measure it with
timeit(module 15) to see the gap on your machine.
Alternative: torch.addmv(torch.full((5,), b), X, w) fuses the product and the addition. nn.Linear(4, 1) with these weights does the same and adds a feature dimension.
M42-C04 · Refactor procedural code into an nn.Module
Section titled “M42-C04 · Refactor procedural code into an nn.Module”Refactor (procedural → OOP): the code below keeps four loose tensors and a forward function. Rewrite it as a class TwoLayerNet(nn.Module) with two nn.Linear layers, then copy the four tensors into the layers and check that the class gives exactly the same output. Print the parameter names with their shapes and the comparison.
hidden.weight (8, 22)hidden.bias (8,)out.weight (1, 8)out.bias (1,)Truetorch.manual_seed(42)W1, b1 = torch.randn(8, 22), torch.randn(8)W2, b2 = torch.randn(1, 8), torch.randn(1)
def forward(x: torch.Tensor) -> torch.Tensor: hidden = torch.relu(x @ W1.T + b1) return hidden @ W2.T + b2
class TwoLayerNet(nn.Module): # TODO: __init__ with self.hidden = nn.Linear(...) and self.out = nn.Linear(...) # TODO: forward ...
# TODO: build the net, copy W1, b1, W2, b2 into it, compare outputs on a batchHint 1
W1 has shape (8, 22), which is the weight shape of nn.Linear(22, 8).
Hint 2
Copy inside torch.no_grad(): net.hidden.weight.copy_(W1).
Solution
torch.manual_seed(42)W1, b1 = torch.randn(8, 22), torch.randn(8)W2, b2 = torch.randn(1, 8), torch.randn(1)
def forward(x: torch.Tensor) -> torch.Tensor: hidden = torch.relu(x @ W1.T + b1) return hidden @ W2.T + b2
class TwoLayerNet(nn.Module): """22 features -> 8 hidden units (ReLU) -> 1 logit."""
def __init__(self, n_features: int = 22, n_hidden: int = 8) -> None: super().__init__() self.hidden = nn.Linear(n_features, n_hidden) self.out = nn.Linear(n_hidden, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.out(torch.relu(self.hidden(x)))
net = TwoLayerNet()with torch.no_grad(): net.hidden.weight.copy_(W1) net.hidden.bias.copy_(b1) net.out.weight.copy_(W2) net.out.bias.copy_(b2)for name, param in net.named_parameters(): print(name, tuple(param.shape))x = torch.randn(5, 22)with torch.no_grad(): same = torch.allclose(net(x), forward(x), atol=1e-5)print(same)assert sameassert sum(p.numel() for p in net.parameters()) == W1.numel() + 8 + 8 + 1hidden.weight (8, 22)hidden.bias (8,)out.weight (1, 8)out.bias (1,)TrueHow it works:
- The constructor creates the layers and registers them as attributes. The hyperparameters
n_featuresandn_hiddenreplace the hard-coded sizes. forwardis the old function, written with the layers instead of the loose tensors.copy_overwrites the random starting weights in place. Insideno_grad, the copy is not recorded in a graph.- The class gains everything that
nn.Moduleoffers:parameters()for an optimizer,state_dict()for saving,train()/eval()and a readableprint(net).
Alternative: nn.Sequential(nn.Linear(22, 8), nn.ReLU(), nn.Linear(8, 1)) builds the same network without a class. Use a class as soon as forward needs more than a straight chain, or when you want named attributes.
M42-C05 · Fix the bug: shapes and dtypes for BCE
Section titled “M42-C05 · Fix the bug: shapes and dtypes for BCE”Fix the bug: the code below computes the loss of a churn model on a batch of 8 customers. It fails first with a ValueError about sizes and, after a naive fix, with a RuntimeError about types. Fix both problems in the loss line, without changing the model or the label tensor, and print the loss rounded to 4 decimals.
(8, 1) (8,) torch.int640.7885torch.manual_seed(42)model = nn.Sequential(nn.Linear(22, 8), nn.ReLU(), nn.Linear(8, 1))xb = torch.randn(8, 22)yb = torch.tensor([0, 1, 0, 0, 1, 0, 0, 0]) # int64 labelsloss_fn = nn.BCEWithLogitsLoss()loss = loss_fn(model(xb), yb) # ValueError: Target size ... input sizeprint(round(loss.item(), 4))Hint 1
Print model(xb).shape and yb.shape. They must be equal.
Hint 2
BCEWithLogitsLoss needs float targets. yb.float() converts them.
Solution
torch.manual_seed(42)model = nn.Sequential(nn.Linear(22, 8), nn.ReLU(), nn.Linear(8, 1))xb = torch.randn(8, 22)yb = torch.tensor([0, 1, 0, 0, 1, 0, 0, 0]) # int64 labelsloss_fn = nn.BCEWithLogitsLoss()logits = model(xb)print(tuple(logits.shape), tuple(yb.shape), yb.dtype)loss = loss_fn(logits.squeeze(1), yb.float())print(round(loss.item(), 4))assert logits.squeeze(1).shape == yb.shapeassert loss.ndim == 0(8, 1) (8,) torch.int640.7885How it works:
- The last layer returns shape
(8, 1); the labels have shape(8,).squeeze(1)removes the size-1 dimension. - The loss mixes the labels into float arithmetic, so PyTorch refuses int64 targets.
.float()gives 0.0 and 1.0. - Fix the dtype where you build the data, if you can: then every batch is right.
Alternative: keep the output shape and add the dimension to the target instead: loss_fn(logits, yb.float().unsqueeze(1)). The lesson’s ChurnMLP squeezes inside forward, so the shapes always match.
M42-C06 · Fix the bug: a sigmoid too many
Section titled “M42-C06 · Fix the bug: a sigmoid too many”Fix the bug, then interpret the result: a model ends with nn.Sigmoid() and is trained with BCEWithLogitsLoss. To see why that is wrong, compute the loss for two very confident, correct predictions (logits 10.0 for a churner and -10.0 for a stayer) in both ways: with the extra sigmoid and with the raw logits. Print both losses rounded to 4 decimals, and the smallest loss that the buggy version can ever reach.
buggy 0.5032 correct 0.0000 floor 0.5032logits = torch.tensor([10.0, -10.0])targets = torch.tensor([1.0, 0.0])loss_fn = nn.BCEWithLogitsLoss()# TODO: the buggy loss passes torch.sigmoid(logits) to loss_fn# TODO: the correct loss passes the logits# TODO: the floor of the buggy loss: the loss for "probabilities" 1.0 and 0.0Hint 1
The buggy version applies the sigmoid twice: once in the model, once inside the loss. What range does have?
Hint 2
for lies between 0.5 and . The loss for a churner is then at least , and for a stayer at least .
Solution
logits = torch.tensor([10.0, -10.0])targets = torch.tensor([1.0, 0.0])loss_fn = nn.BCEWithLogitsLoss()buggy = loss_fn(torch.sigmoid(logits), targets)correct = loss_fn(logits, targets)floor = loss_fn(torch.tensor([1.0, 0.0]), targets)print(f"buggy {buggy.item():.4f} correct {correct.item():.4f}" f" floor {floor.item():.4f}")assert correct.item() < 1e-3assert buggy.item() >= floor.item() - 1e-6buggy 0.5032 correct 0.0000 floor 0.5032How it works:
- With the extra sigmoid, the “logits” are probabilities between 0 and 1. The loss applies its own sigmoid again, so the final probabilities are squeezed into about [0.5, 0.73].
- Even these perfect predictions cost 0.5032 instead of almost 0, and no model can do better than this floor. The gradients near the floor are tiny, so training crawls and the model never becomes confident.
- The fix: remove
nn.Sigmoid()from the model. Applytorch.sigmoidonly when you want probabilities for prediction.
Alternative: if you really want the model to return probabilities, keep the sigmoid and use nn.BCELoss(). It is less stable for extreme logits (it clamps the log to avoid infinity), so BCEWithLogitsLoss is the recommended pair.
M42-C07 · Interpret the effect of pos_weight
Section titled “M42-C07 · Interpret the effect of pos_weight”Interpret a result: train the same small network twice on the churn data for 10 epochs, once with a plain BCEWithLogitsLoss and once with pos_weight = n_stayers / n_churners. For each run, print the test ROC-AUC, the mean predicted probability and the recall at a threshold of 0.5. Then explain in two sentences what pos_weight changed and what it did not change.
plain ROC-AUC 0.816 mean p 0.204 recall@0.5 0.340pos_weight ROC-AUC 0.823 mean p 0.422 recall@0.5 0.784from sklearn.metrics import recall_score, roc_auc_score
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()
def make_model() -> nn.Module: return nn.Sequential(nn.Linear(22, 32), nn.ReLU(), nn.Linear(32, 1), nn.Flatten(0))
# TODO: for pos_weight in [None, n_stayers / n_churners]:# seed, build the model, the loss, AdamW(lr=1e-3) and a seeded DataLoader# train 10 epochs with train_one_epoch, then predict test probabilities# print ROC-AUC, mean probability and recall at 0.5Hint 1
nn.Flatten(0) turns the (n, 1) output into (n,), so it matches the target shape. pos_weight=None is the default: no weighting.
Hint 2
Call torch.manual_seed(42) before each model and build the loader with generator=torch.Generator().manual_seed(42), so the only difference between the runs is the loss.
Solution
from sklearn.metrics import recall_score, roc_auc_score
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()
def make_model() -> nn.Module: return nn.Sequential(nn.Linear(22, 32), nn.ReLU(), nn.Linear(32, 1), nn.Flatten(0))
results = {}balanced = (y_tr == 0).sum() / (y_tr == 1).sum()for name, pos_weight in [("plain", None), ("pos_weight", balanced)]: torch.manual_seed(42) model = make_model() loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42)) for _ in range(10): train_one_epoch(model, loader, loss_fn, optimizer) model.eval() with torch.no_grad(): proba = torch.sigmoid(model(X_te)).numpy() results[name] = (roc_auc_score(y_te, proba), proba.mean(), recall_score(y_te, proba >= 0.5)) auc, mean_p, recall = results[name] print(f"{name:10s} ROC-AUC {auc:.3f} mean p {mean_p:.3f} recall@0.5 {recall:.3f}")assert abs(results["plain"][0] - results["pos_weight"][0]) < 0.02assert results["pos_weight"][2] > 2 * results["plain"][2]plain ROC-AUC 0.816 mean p 0.204 recall@0.5 0.340pos_weight ROC-AUC 0.823 mean p 0.422 recall@0.5 0.784How it works:
- Both runs use the same seed, data order and architecture. Only the loss differs.
pos_weight ≈ 4.19makes each churner count about four times. The model shifts its probabilities up: the mean probability doubles, far above the real churn rate of 0.19.- Interpretation:
pos_weightmoved the probabilities, so the 0.5 threshold catches more than twice as many churners. It barely changed the ranking (ROC-AUC), so you could get a similar recall from the plain model with a lower threshold.
Alternative: keep the plain loss, which gives better-calibrated probabilities, and choose the threshold on the validation set for the recall you need (module 36).
M42-C08 · Write predict_proba for a PyTorch model
Section titled “M42-C08 · Write predict_proba for a PyTorch model”Write a function predict_proba(model, X) that returns churn probabilities as a NumPy array. It must use eval mode and torch.no_grad(), and it must put the model back into the mode it was in before the call. Test it on a model with dropout: two calls must give the same result, the model must be in train mode again afterwards, and every probability must lie in [0, 1].
[0.511 0.478 0.493 0.489 0.402 0.502]True Truetorch.manual_seed(42)model = nn.Sequential(nn.Linear(22, 16), nn.ReLU(), nn.Dropout(0.5), nn.Linear(16, 1))X = torch.randn(6, 22)
def predict_proba(model: nn.Module, X: torch.Tensor) -> np.ndarray: # TODO: remember model.training, switch to eval, predict without a graph, # restore the mode, return a 1-D NumPy array of probabilities ...Hint 1
model.training is True or False. model.train(mode) sets it back.
Hint 2
Use try/finally so that the mode is restored even if the forward pass raises an error.
Solution
torch.manual_seed(42)model = nn.Sequential(nn.Linear(22, 16), nn.ReLU(), nn.Dropout(0.5), nn.Linear(16, 1))X = torch.randn(6, 22)
def predict_proba(model: nn.Module, X: torch.Tensor) -> np.ndarray: """Probabilities of the positive class, computed in eval mode.""" was_training = model.training model.eval() try: with torch.no_grad(): return torch.sigmoid(model(X)).squeeze(1).numpy() finally: model.train(was_training)
first = predict_proba(model, X)second = predict_proba(model, X)print(first.round(3))print(np.array_equal(first, second), model.training)assert np.array_equal(first, second)assert model.trainingassert ((first >= 0) & (first <= 1)).all()[0.511 0.478 0.493 0.489 0.402 0.502]True TrueHow it works:
model.eval()turns dropout off, so two calls give identical results.torch.no_grad()skips the graph, so.numpy()works withoutdetach().- The
finallyblock runs after thereturnvalue is computed and restores the mode. A training loop that calls this function for validation keeps its dropout.
Alternative: torch.inference_mode() is a stricter, slightly faster version of no_grad() for pure prediction. Tensors created inside it can never join a graph later.
M42-C09 · Fix the bug: evaluation in train mode
Section titled “M42-C09 · Fix the bug: evaluation in train mode”Fix the bug: the code below trains a digit classifier with dropout for 3 epochs and then measures the test accuracy twice. The two numbers differ. Fix the evaluation so that it is deterministic, and print the accuracy of both calls with 3 decimals.
0.933 0.933X_tr, X_te, y_tr, y_te = digit_tensors()torch.manual_seed(42)model = nn.Sequential(nn.Flatten(), nn.Linear(64, 64), nn.ReLU(), nn.Dropout(0.5), nn.Linear(64, 10))optimizer = torch.optim.AdamW(model.parameters(), lr=0.01)loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42))for _ in range(3): train_one_epoch(model, loader, nn.CrossEntropyLoss(), optimizer)
def accuracy(model, X, y) -> float: return (model(X).argmax(dim=1) == y).float().mean().item()
print(f"{accuracy(model, X_te, y_te):.3f} {accuracy(model, X_te, y_te):.3f}")Hint 1
train_one_epoch leaves the model in train mode. What does dropout do in train mode?
Hint 2
Add model.eval() and torch.no_grad() inside accuracy.
Solution
X_tr, X_te, y_tr, y_te = digit_tensors()torch.manual_seed(42)model = nn.Sequential(nn.Flatten(), nn.Linear(64, 64), nn.ReLU(), nn.Dropout(0.5), nn.Linear(64, 10))optimizer = torch.optim.AdamW(model.parameters(), lr=0.01)loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42))for _ in range(3): train_one_epoch(model, loader, nn.CrossEntropyLoss(), optimizer)
def accuracy(model, X, y) -> float: model.eval() with torch.no_grad(): return (model(X).argmax(dim=1) == y).float().mean().item()
first, second = accuracy(model, X_te, y_te), accuracy(model, X_te, y_te)print(f"{first:.3f} {second:.3f}")assert first == secondassert first > 0.90.933 0.933How it works:
- After training, the model is still in train mode, so dropout zeroed a random half of the hidden values in every call. Each call saw a different network.
model.eval()makes dropout the identity, so both calls give the same predictions.torch.no_grad()is not needed for determinism, but it saves memory and time.
Alternative: use the predict_proba pattern of M42-C08, which also restores the previous mode for the next training epoch.
M42-C10 · Train a regression MLP on house prices
Section titled “M42-C10 · Train a regression MLP on house prices”Predict the log price of a house from sqft, bedrooms, bathrooms, condition and distance_to_center_km in data/houses.csv. Hold out 25% as a test set, then 20% of the rest as a validation set (both with random_state=42). Scale the features with a StandardScaler fitted on the training rows, and center the target by subtracting the training mean of the log price. Train a network 5 → 32 → 1 (ReLU) with MSELoss, AdamW(lr=3e-3) and batches of 64 for 30 epochs. Print the validation RMSE on the log scale every 10 epochs. After training, print the test RMSE once and compare it with a LinearRegression fitted on the same training rows.
epoch 10 validation RMSE (log price) 0.2234epoch 20 validation RMSE (log price) 0.2141epoch 30 validation RMSE (log price) 0.2106test RMSE MLP 0.2178 LinearRegression 0.2909from sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]X = houses[cols].to_numpy()y = np.log(houses["price"].to_numpy())# TODO: test split, then validation split; scale X, center y, build tensors# TODO: model, loss, optimizer, seeded DataLoader; train 30 epochs# TODO: print the validation RMSE every 10 epochs# TODO: print the test RMSE once; compare with LinearRegressionHint 1
A log price is about 12.9. Starting from random weights, the output is near 0, so the network wastes many epochs just learning the mean. Centering the target removes that problem.
Hint 2
The RMSE is the square root of the MSE: loss_fn(model(X_te), y_te).sqrt(). Centering does not change it, because it shifts predictions and targets by the same amount.
Solution
from sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]X = houses[cols].to_numpy()y = np.log(houses["price"].to_numpy())X_rest, X_b, y_rest, y_b = train_test_split(X, y, test_size=0.25, random_state=42)X_a, X_v, y_a, y_v = train_test_split(X_rest, y_rest, test_size=0.2, random_state=42)scaler = StandardScaler().fit(X_a)y_mean = y_a.mean()
def as_tensors(X_part, y_part) -> tuple[torch.Tensor, torch.Tensor]: X_t = torch.tensor(scaler.transform(X_part), dtype=torch.float32) return X_t, torch.tensor(y_part - y_mean, dtype=torch.float32)
X_tr, y_tr = as_tensors(X_a, y_a)X_va, y_va = as_tensors(X_v, y_v)X_te, y_te = as_tensors(X_b, y_b)
torch.manual_seed(42)model = nn.Sequential(nn.Linear(5, 32), nn.ReLU(), nn.Linear(32, 1), nn.Flatten(0))loss_fn = nn.MSELoss()optimizer = torch.optim.AdamW(model.parameters(), lr=3e-3)loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42))for epoch in range(1, 31): train_one_epoch(model, loader, loss_fn, optimizer) if epoch % 10 == 0: model.eval() with torch.no_grad(): val_rmse = loss_fn(model(X_va), y_va).sqrt().item() print(f"epoch {epoch} validation RMSE (log price) {val_rmse:.4f}")
model.eval()with torch.no_grad(): rmse = loss_fn(model(X_te), y_te).sqrt().item()linear = LinearRegression().fit(scaler.transform(X_a), y_a)lin_rmse = np.sqrt(np.mean((linear.predict(scaler.transform(X_b)) - y_b) ** 2))print(f"test RMSE MLP {rmse:.4f} LinearRegression {lin_rmse:.4f}")assert rmse < lin_rmseepoch 10 validation RMSE (log price) 0.2234epoch 20 validation RMSE (log price) 0.2141epoch 30 validation RMSE (log price) 0.2106test RMSE MLP 0.2178 LinearRegression 0.2909How it works:
- The scaler and the target mean come from the training rows only, so no validation or test information leaks into training. The validation set is the one you watch during training; the test set is scored once, at the end.
nn.Flatten(0)turns the output into shape(n,), the shape of the target.MSELosswould otherwise broadcast(n, 1)against(n,)and warn.- A test RMSE of about 0.22 on the log scale means typical errors of about ±25% of the price (). The linear model, at about 0.29, misses non-linear effects that the network can fit. This exercise does not show which effects those are; adding
np.log(sqft)as a feature to the linear model is one way to test a guess. - The neighborhood is not among these features. Try adding it (one-hot encoded) to both models and measure the change on the validation set; module 35 works with it for linear models.
Alternative: standardize the target fully ((y - mean) / std) and multiply the RMSE back by std. For targets with a large spread, this also keeps the gradients in a good range.
M42-C11 · Write the early-stopping logic
Section titled “M42-C11 · Write the early-stopping logic”Write a class EarlyStopping(patience, min_delta=0.0) with a method step(val_loss) -> bool that returns True when training should stop. It counts the epochs since the last improvement; an improvement means a loss lower than the best loss minus min_delta. Feed it the validation losses below, one per epoch, and print the epoch where it stops and the best epoch, for patience=3 and for patience=3, min_delta=0.01.
min_delta=0.0: stop after epoch 10, best epoch 7 (0.799)min_delta=0.01: stop after epoch 6, best epoch 3 (0.81)val_losses = [0.95, 0.84, 0.81, 0.805, 0.80, 0.802, 0.799, 0.81, 0.83, 0.86]
class EarlyStopping: def __init__(self, patience: int, min_delta: float = 0.0) -> None: # TODO: store the settings; best_loss, best_epoch, bad_epochs, epoch ...
def step(self, val_loss: float) -> bool: # TODO: update the counters and return True when bad_epochs >= patience ...
# TODO: run both settings over val_losses and print the stop and best epochsHint 1
Count epochs from 1. Start with best_loss = float("inf"), so the first loss is always an improvement.
Hint 2
With min_delta=0.01, going from 0.81 to 0.805 is not an improvement: 0.805 is not below 0.81 − 0.01.
Solution
val_losses = [0.95, 0.84, 0.81, 0.805, 0.80, 0.802, 0.799, 0.81, 0.83, 0.86]
class EarlyStopping: """Stop when the loss has not improved by min_delta for `patience` epochs."""
def __init__(self, patience: int, min_delta: float = 0.0) -> None: self.patience = patience self.min_delta = min_delta self.best_loss = float("inf") self.best_epoch = 0 self.bad_epochs = 0 self.epoch = 0
def step(self, val_loss: float) -> bool: self.epoch += 1 if val_loss < self.best_loss - self.min_delta: self.best_loss, self.best_epoch = val_loss, self.epoch self.bad_epochs = 0 else: self.bad_epochs += 1 return self.bad_epochs >= self.patience
for min_delta in [0.0, 0.01]: stopper = EarlyStopping(patience=3, min_delta=min_delta) for loss in val_losses: if stopper.step(loss): break print(f"min_delta={min_delta}: stop after epoch {stopper.epoch}," f" best epoch {stopper.best_epoch} ({stopper.best_loss})")assert (stopper.epoch, stopper.best_epoch) == (6, 3)min_delta=0.0: stop after epoch 10, best epoch 7 (0.799)min_delta=0.01: stop after epoch 6, best epoch 3 (0.81)How it works:
- With
min_delta=0, every new low counts: epoch 5 (0.80) and epoch 7 (0.799) reset the counter. Epochs 8, 9 and 10 bring no improvement, so the stopper fires after epoch 10. - With
min_delta=0.01, the small gains after epoch 3 do not count. Three epochs in a row without a real improvement end training after epoch 6. min_deltaignores noise-level gains, so training stops sooner. The lesson’s version also stores a copy of the best weights, which this logic-only version leaves out.
M42-C12 · Compute convolution output shapes
Section titled “M42-C12 · Compute convolution output shapes”Write a function conv_out(size, kernel, padding=0, stride=1) that applies the output-size formula of the lesson. Check it against real layers for the configurations below, using a random batch of shape (1, 1, size, size), and print one line per configuration.
in 8 k=3 p=1 s=1 -> 8 (real 8)in 8 k=3 p=0 s=1 -> 6 (real 6)in 28 k=5 p=0 s=1 -> 24 (real 24)in 28 k=3 p=1 s=2 -> 14 (real 14)in 32 k=7 p=3 s=2 -> 16 (real 16)max pool on 8x8 -> 4 (real 4)max pool on 7x7 -> 3 (real 3)def conv_out(size: int, kernel: int, padding: int = 0, stride: int = 1) -> int: # TODO: floor((size + 2 * padding - kernel) / stride) + 1 ...
configs = [(8, 3, 1, 1), (8, 3, 0, 1), (28, 5, 0, 1), (28, 3, 1, 2), (32, 7, 3, 2)]# TODO: for each (size, kernel, padding, stride), compare with nn.Conv2d(1, 4, ...)# TODO: also check nn.MaxPool2d(2) on an 8x8 and a 7x7 inputHint 1
Integer floor division // computes the floor for positive numbers.
Hint 2
nn.MaxPool2d(2) is a window of 2 with stride 2 and no padding, so the same formula applies with kernel=2, stride=2.
Solution
def conv_out(size: int, kernel: int, padding: int = 0, stride: int = 1) -> int: return (size + 2 * padding - kernel) // stride + 1
configs = [(8, 3, 1, 1), (8, 3, 0, 1), (28, 5, 0, 1), (28, 3, 1, 2), (32, 7, 3, 2)]for size, k, p, s in configs: layer = nn.Conv2d(1, 4, kernel_size=k, padding=p, stride=s) real = layer(torch.randn(1, 1, size, size)).shape[-1] out = conv_out(size, k, p, s) print(f"in {size:2d} k={k} p={p} s={s} -> {out:2d} (real {real})") assert conv_out(size, k, p, s) == realfor size in [8, 7]: real = nn.MaxPool2d(2)(torch.randn(1, 1, size, size)).shape[-1] print(f"max pool on {size}x{size} -> {conv_out(size, 2, 0, 2)} (real {real})") assert conv_out(size, 2, 0, 2) == realin 8 k=3 p=1 s=1 -> 8 (real 8)in 8 k=3 p=0 s=1 -> 6 (real 6)in 28 k=5 p=0 s=1 -> 24 (real 24)in 28 k=3 p=1 s=2 -> 14 (real 14)in 32 k=7 p=3 s=2 -> 16 (real 16)max pool on 8x8 -> 4 (real 4)max pool on 7x7 -> 3 (real 3)How it works:
padding=1with a 3×3 kernel keeps the size (“same” padding). Without padding, a 3×3 kernel loses one pixel on each side.- A stride of 2 roughly halves the size, like pooling, but with learned weights.
- Pooling a 7×7 map gives 3×3: the floor drops the last row and column. Odd sizes lose information silently, so plan the sizes of a CNN on paper first.
Alternative: nn.Conv2d(..., padding="same") computes the padding for you when the stride is 1.
M42-C13 · Compute one convolution output by hand
Section titled “M42-C13 · Compute one convolution output by hand”Take the first training digit from digit_tensors() and a convolution with one 3×3 kernel and no padding, created after torch.manual_seed(42). Compute the output value at row 2, column 3 of the feature map by hand: multiply the kernel with the 3×3 patch of the image under it, sum and add the bias. Print both values rounded to 4 decimals and the shape of the feature map.
(1, 1, 6, 6)0.235 0.235X_tr, X_te, y_tr, y_te = digit_tensors()image = X_tr[:1] # shape (1, 1, 8, 8)torch.manual_seed(42)conv = nn.Conv2d(1, 1, kernel_size=3)# TODO: feature_map = conv(image); read the value at row 2, column 3# TODO: the patch under the kernel starts at the same row and column# TODO: manual = (patch * kernel).sum() + biasHint 1
Without padding and with stride 1, output position (r, c) covers input rows r to r + 2 and columns c to c + 2.
Hint 2
conv.weight[0, 0] is the 3×3 kernel, conv.bias[0] its bias. image[0, 0, 2:5, 3:6] is the patch.
Solution
X_tr, X_te, y_tr, y_te = digit_tensors()image = X_tr[:1] # shape (1, 1, 8, 8)torch.manual_seed(42)conv = nn.Conv2d(1, 1, kernel_size=3)with torch.no_grad(): feature_map = conv(image) r, c = 2, 3 patch = image[0, 0, r : r + 3, c : c + 3] manual = (patch * conv.weight[0, 0]).sum() + conv.bias[0]print(tuple(feature_map.shape))print(round(feature_map[0, 0, r, c].item(), 4), round(manual.item(), 4))assert torch.isclose(feature_map[0, 0, r, c], manual, atol=1e-6)(1, 1, 6, 6)0.235 0.235How it works:
- Without padding, the 8×8 image gives a 6×6 feature map: .
- Each output value is the sum of a 3×3 patch times the 3×3 kernel, plus one bias. The same 10 numbers are used at all 36 positions: weight sharing.
- Deep-learning “convolution” does not flip the kernel; mathematically, it is a cross-correlation. For learned kernels, the difference does not matter.
Alternative: torch.nn.functional.unfold(image, kernel_size=3) extracts all 36 patches as columns. One matrix product with the flattened kernel then computes the whole feature map, which is how many libraries implement convolutions.
M42-C14 · Choose the output layer and the loss
Section titled “M42-C14 · Choose the output layer and the loss”Choose a method and justify it: for each task below, choose the number of outputs of the last layer, the loss class and the dtype and shape of the target. Store your choices in a dictionary, then prove them by computing each loss on a dummy batch of 4 samples with the right shapes. Print one line per task.
- Predict the sale price of a house.
- Predict whether a customer churns.
- Read a handwritten digit from 0 to 9.
house price output (4, 1) target (4, 1) torch.float32 MSELosschurn output (4, 1) target (4, 1) torch.float32 BCEWithLogitsLossdigit output (4, 10) target (4,) torch.int64 CrossEntropyLosschoices = { "house price": {"outputs": ..., "loss": ..., "target_dtype": ...}, "churn": {"outputs": ..., "loss": ..., "target_dtype": ...}, "digit": {"outputs": ..., "loss": ..., "target_dtype": ...},}# TODO: for each task, build dummy outputs of shape (4, outputs) and matching targets# TODO: compute the loss and print the task, the shapes and the loss nameHint 1
Regression and binary classification need one output each. Multiclass needs one logit per class.
Hint 2
CrossEntropyLoss wants int64 targets of shape (4,). MSELoss and BCEWithLogitsLoss want float targets with the same shape as the output.
Solution
choices = { "house price": {"outputs": 1, "loss": nn.MSELoss, "target_dtype": torch.float32}, "churn": {"outputs": 1, "loss": nn.BCEWithLogitsLoss, "target_dtype": torch.float32}, "digit": {"outputs": 10, "loss": nn.CrossEntropyLoss, "target_dtype": torch.int64},}torch.manual_seed(42)for task, choice in choices.items(): outputs = torch.randn(4, choice["outputs"]) if task == "digit": target = torch.randint(0, 10, (4,)) # class indices elif task == "churn": target = torch.randint(0, 2, (4, 1)).float() # 0.0 or 1.0 else: target = torch.randn(4, 1) # a centered log price assert target.dtype == choice["target_dtype"] loss = choice["loss"]()(outputs, target) print(f"{task:11s} output {tuple(outputs.shape)} target {tuple(target.shape)} " f"{str(target.dtype):13s} {choice['loss'].__name__}") assert loss.ndim == 0 and torch.isfinite(loss)house price output (4, 1) target (4, 1) torch.float32 MSELosschurn output (4, 1) target (4, 1) torch.float32 BCEWithLogitsLossdigit output (4, 10) target (4,) torch.int64 CrossEntropyLossHow it works:
- House price: one unbounded number, so one output and
MSELoss(orL1Lossfor a robust MAE). Train on the log price, as in M42-C10, because prices are right-skewed. - Churn: one logit, and
BCEWithLogitsLoss, which applies the sigmoid inside. Float targets 0.0 and 1.0 with the same shape as the output. - Digit: 10 logits, one per class, and
CrossEntropyLoss, which applies the softmax inside. The targets are int64 class indices of shape(4,). Float class probabilities of shape(4, 10), such as one-hot rows, also work; float labels of shape(4,)do not. - The dummy batch proves that the shapes and dtypes work together: a wrong choice raises an error or a warning here, before any real training.
Alternative: a binary task can also use 2 logits with CrossEntropyLoss. It gives the same model quality; one logit with BCEWithLogitsLoss is simpler and works directly with pos_weight.
Challenge
Section titled “Challenge”M42-X01 · CNN against MLP on the same budget
Section titled “M42-X01 · CNN against MLP on the same budget”Compare a CNN and an MLP with a similar number of parameters on the digits. The CNN is the lesson’s DigitCNN (one 3×3 convolution with 16 filters and padding 1, ReLU, 2×2 max pooling, a linear layer to 10 logits). The MLP flattens the 64 pixels into a hidden layer of 40 units with ReLU and then 10 logits. Train each one for 8 epochs with AdamW(lr=0.01), batches of 32 and the same seeds. Print the parameter count and the test accuracy of both, then explain the result.
CNN: 2730 parameters, test accuracy 0.973MLP: 3010 parameters, test accuracy 0.960X_tr, X_te, y_tr, y_te = digit_tensors()
class DigitCNN(nn.Module): # TODO: conv, pool, fc as in the lesson ...
def make_mlp() -> nn.Module: # TODO: Flatten -> Linear(64, 40) -> ReLU -> Linear(40, 10) ...
def fit_and_score(model: nn.Module) -> float: # TODO: train 8 epochs with a seeded loader; return the test accuracy ...Hint 1
The MLP has 64·40 + 40 + 40·10 + 10 = 3,010 parameters, the CNN 2,730. The budgets are close.
Hint 2
Seed with torch.manual_seed(42) right before you build each model, and give each loader its own torch.Generator().manual_seed(42).
Solution
X_tr, X_te, y_tr, y_te = digit_tensors()
class DigitCNN(nn.Module): def __init__(self, n_filters: int = 16) -> None: super().__init__() self.conv = nn.Conv2d(1, n_filters, kernel_size=3, padding=1) self.pool = nn.MaxPool2d(2) self.fc = nn.Linear(n_filters * 4 * 4, 10)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.fc(self.pool(torch.relu(self.conv(x))).flatten(start_dim=1))
def make_mlp() -> nn.Module: return nn.Sequential(nn.Flatten(), nn.Linear(64, 40), nn.ReLU(), nn.Linear(40, 10))
def fit_and_score(model: nn.Module) -> float: optimizer = torch.optim.AdamW(model.parameters(), lr=0.01) loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42)) for _ in range(8): train_one_epoch(model, loader, nn.CrossEntropyLoss(), optimizer) model.eval() with torch.no_grad(): return (model(X_te).argmax(dim=1) == y_te).float().mean().item()
scores = {}for name, build in [("CNN", DigitCNN), ("MLP", make_mlp)]: torch.manual_seed(42) model = build() n_params = sum(p.numel() for p in model.parameters()) scores[name] = fit_and_score(model) print(f"{name}: {n_params} parameters, test accuracy {scores[name]:.3f}")assert scores["CNN"] > scores["MLP"]CNN: 2730 parameters, test accuracy 0.973MLP: 3010 parameters, test accuracy 0.960How it works:
- Both models see the same images, in the same order, for the same number of steps.
- The MLP gives every pixel its own weight in every hidden unit. It must learn a stroke separately at each position where it can appear.
- The CNN’s 16 kernels of 9 weights detect a stroke anywhere (weight sharing), and pooling tolerates small shifts. With fewer parameters, it makes fewer mistakes.
- On 8×8 images, the gap is about one point of accuracy, on one split and one seed. This exercise does not test larger images; convolutional layers are the standard choice for photos because of the weight sharing shown here.
Alternative: add a second convolution block (16 → 32 channels, then pooling to 2×2) to see whether depth helps here. Measure on a validation split, not on the test set, before you decide.
M42-X02 · Resume training from a checkpoint
Section titled “M42-X02 · Resume training from a checkpoint”A long training job must survive a restart. Prove that a checkpoint is complete: train a small churn network (22 → 16 → 1 with ReLU and dropout 0.2) for 4 epochs in one run and keep its final weights. Then train the same setup for 2 epochs, save a checkpoint to output/, build everything again from scratch with a different seed, load the checkpoint and train 2 more epochs. The resumed weights must equal the uninterrupted weights exactly. Print which parts the checkpoint holds and the result of the comparison.
['epoch', 'global_rng', 'loader_rng', 'model', 'optimizer']resumed == uninterrupted: Truefrom pathlib import Path
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()loss_fn = nn.BCEWithLogitsLoss()
def build(seed: int): """Return a fresh model, optimizer, loader generator and loader.""" # TODO ...
# TODO: run A: 4 epochs, keep a deep copy of the state_dict# TODO: run B: 2 epochs, save model, optimizer, loader generator, global RNG, epoch# TODO: run C: build(seed=0), load everything, train 2 epochs, compare with run AHint 1
The model and optimizer states are not enough. The shuffle order comes from the loader’s generator (g.get_state()), and dropout uses the global generator (torch.get_rng_state()).
Hint 2
Restore with model.load_state_dict, optimizer.load_state_dict, g.set_state and torch.set_rng_state. Seed the global generator the same way before runs A and B, after the model is built.
Hint 3
All the states are tensors or dictionaries of tensors and numbers, so torch.load(path, weights_only=True) can read the checkpoint.
Solution
from pathlib import Path
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()loss_fn = nn.BCEWithLogitsLoss()
def build(seed: int): torch.manual_seed(seed) model = nn.Sequential(nn.Linear(22, 16), nn.ReLU(), nn.Dropout(0.2), nn.Linear(16, 1), nn.Flatten(0)) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) gen = torch.Generator().manual_seed(42) loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=gen) return model, optimizer, gen, loader
model, optimizer, gen, loader = build(seed=42) # run A: 4 epochs in one gotorch.manual_seed(7)for _ in range(4): train_one_epoch(model, loader, loss_fn, optimizer)uninterrupted = copy.deepcopy(model.state_dict())
model, optimizer, gen, loader = build(seed=42) # run B: 2 epochs, then savetorch.manual_seed(7)for _ in range(2): train_one_epoch(model, loader, loss_fn, optimizer)Path("output").mkdir(exist_ok=True)torch.save({ "model": model.state_dict(), "optimizer": optimizer.state_dict(), "loader_rng": gen.get_state(), "global_rng": torch.get_rng_state(), "epoch": 2,}, "output/resume.pt")
model, optimizer, gen, loader = build(seed=0) # run C: a fresh processckpt = torch.load("output/resume.pt", weights_only=True)model.load_state_dict(ckpt["model"])optimizer.load_state_dict(ckpt["optimizer"])gen.set_state(ckpt["loader_rng"])torch.set_rng_state(ckpt["global_rng"])for _ in range(ckpt["epoch"], 4): train_one_epoch(model, loader, loss_fn, optimizer)
print(sorted(ckpt))same = all(torch.equal(uninterrupted[k], v) for k, v in model.state_dict().items())print("resumed == uninterrupted:", same)assert same['epoch', 'global_rng', 'loader_rng', 'model', 'optimizer']resumed == uninterrupted: TrueHow it works:
- Run A is the reference. Run B stops after epoch 2 and saves five things: the weights, the optimizer state (Adam’s running averages and step counts), the loader’s generator, the global generator and the epoch.
- Run C starts from different random weights (seed 0) to prove that everything comes from the checkpoint.
- Without the loader generator, epochs 3 and 4 would shuffle differently. Without the global generator, dropout would drop different values. Either way, the weights would differ slightly.
torch.equaldemands bit-for-bit equality. It holds because both runs use the same thread count on the same machine, and every random state is restored.
Alternative: if exact equality does not matter, saving only the model, the optimizer and the epoch is common practice. Training then continues from a slightly different but equally valid path.
M42-X03 · Compare learning rates
Section titled “M42-X03 · Compare learning rates”Train the network 22 → 32 → 1 (ReLU) on the churn data with torch.optim.Adam and the learning rates 0.0001, 0.001, 0.01 and 0.1, for 10 epochs each, with a plain BCEWithLogitsLoss. Record the validation loss after every epoch. Print the validation loss after epochs 1, 4, 7 and 10 for each rate, name the best rate by the final validation loss, and describe the failure of the smallest and the largest rate.
lr=0.0001 0.6318 0.5844 0.5440 0.5096lr=0.001 0.5107 0.3910 0.3734 0.3678lr=0.01 0.3749 0.3647 0.3656 0.3616lr=0.1 0.3871 0.3942 0.3956 0.4105best learning rate: 0.01X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()loss_fn = nn.BCEWithLogitsLoss()rates = [1e-4, 1e-3, 1e-2, 1e-1]# TODO: for each rate: seed, build the model, Adam, seeded loader# 10 epochs; after each one, compute the validation loss in eval mode# TODO: print the losses after epochs 1, 4, 7 and 10; print the best rateHint 1
Keep everything else identical: the same seed before each model and a new seeded generator for each loader.
Hint 2
losses[::3] picks epochs 1, 4, 7 and 10 from a list of 10 values.
Solution
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()loss_fn = nn.BCEWithLogitsLoss()rates = [1e-4, 1e-3, 1e-2, 1e-1]final = {}for lr in rates: torch.manual_seed(42) model = nn.Sequential(nn.Linear(22, 32), nn.ReLU(), nn.Linear(32, 1), nn.Flatten(0)) optimizer = torch.optim.Adam(model.parameters(), lr=lr) loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42)) losses = [] for _ in range(10): train_one_epoch(model, loader, loss_fn, optimizer) model.eval() with torch.no_grad(): losses.append(loss_fn(model(X_va), y_va).item()) final[lr] = losses[-1] print(f"lr={lr:<6}", " ".join(f"{v:.4f}" for v in losses[::3]))best = min(final, key=final.get)print("best learning rate:", best)assert best == 1e-2assert final[1e-4] > final[1e-3] > final[1e-2]lr=0.0001 0.6318 0.5844 0.5440 0.5096lr=0.001 0.5107 0.3910 0.3734 0.3678lr=0.01 0.3749 0.3647 0.3656 0.3616lr=0.1 0.3871 0.3942 0.3956 0.4105best learning rate: 0.01How it works:
- lr = 0.0001 is too small. The loss falls at every epoch but is still far from the others after 10 epochs: the steps are tiny.
- lr = 0.001 and 0.01 both work. 0.01 gets low fastest and ends lowest within this budget.
- lr = 0.1 is too large. The loss is low after one epoch, then rises: the steps jump over the minimum and the weights become too extreme for new data.
- Learning rates are compared on a log scale (factors of 10), because their effect is multiplicative.
Alternative: a learning-rate schedule (module 32) changes the rate during training. ReduceLROnPlateau lowers the rate when the validation loss stalls. OneCycleLR warms up from a low rate to a peak and then anneals it far below the starting rate. Both aim to combine the speed of a large rate with the precision of a small one.
M42-X04 · Gradient-check a whole network
Section titled “M42-X04 · Gradient-check a whole network”Autograd is reliable, but a custom layer or loss can still have a bug. Write a gradient check (module 32) for a whole network: for a tiny MLP 4 → 3 → 1 (tanh activation) in float64 and a batch of 5 samples with MSE loss, compare every element of every parameter’s autograd gradient with the central difference , with . Print the number of checked values and the largest relative error.
19 values checkedlargest relative error: 4.5e-09torch.manual_seed(42)model = nn.Sequential(nn.Linear(4, 3), nn.Tanh(), nn.Linear(3, 1)).double()X = torch.randn(5, 4, dtype=torch.float64)y = torch.randn(5, 1, dtype=torch.float64)loss_fn = nn.MSELoss()# TODO: autograd gradients: one backward pass# TODO: for every parameter p and every index i: nudge p[i] by +h and -h# inside torch.no_grad(), recompute the loss, restore p[i]# TODO: relative error = |auto - numeric| / max(|auto| + |numeric|, 1e-12)Hint 1
p.view(-1) gives a flat view of the parameter that shares its memory, so flat[i] += h changes the parameter itself.
Hint 2
Use float64. Near 1, float32 numbers are about apart, so is only a few float32 rounding steps; rounding error then swamps the difference of the two losses.
Solution
torch.manual_seed(42)model = nn.Sequential(nn.Linear(4, 3), nn.Tanh(), nn.Linear(3, 1)).double()X = torch.randn(5, 4, dtype=torch.float64)y = torch.randn(5, 1, dtype=torch.float64)loss_fn = nn.MSELoss()
model.zero_grad()loss_fn(model(X), y).backward()h = 1e-6worst = 0.0checked = 0with torch.no_grad(): for param in model.parameters(): flat = param.view(-1) grad = param.grad.view(-1) for i in range(flat.numel()): original = flat[i].item() flat[i] = original + h loss_plus = loss_fn(model(X), y).item() flat[i] = original - h loss_minus = loss_fn(model(X), y).item() flat[i] = original numeric = (loss_plus - loss_minus) / (2 * h) auto = grad[i].item() rel = abs(auto - numeric) / max(abs(auto) + abs(numeric), 1e-12) worst = max(worst, rel) checked += 1print(checked, "values checked")print(f"largest relative error: {worst:.1e}")assert checked == sum(p.numel() for p in model.parameters()) == 19assert worst < 1e-619 values checkedlargest relative error: 4.5e-09How it works:
- One
backward()gives all 19 autograd gradients at once. - The central difference needs two extra forward passes per value: 38 passes here. That is why nobody trains with numerical gradients, but they are perfect for a test.
flat[i] = originalrestores each value before the next one is nudged, so every check starts from the same model.- A relative error around or smaller means the gradients agree; an error near 1 would point to a bug.
Alternative: torch.autograd.gradcheck(fn, inputs) runs the same check for a function of float64 tensors and raises an error when a gradient is wrong.
M42-X05 · Measure the effect of weight decay
Section titled “M42-X05 · Measure the effect of weight decay”Train the network 22 → 64 → 1 (ReLU) on the churn data for 20 epochs with AdamW(lr=1e-2) and a plain BCEWithLogitsLoss, once for each weight decay 0.0, 0.1 and 1.0. For each run, print the Euclidean norm of all weight matrices (biases excluded), the validation loss and the validation ROC-AUC. Explain the trend.
weight_decay=0.0 weight norm 15.17 val loss 0.4156 val ROC-AUC 0.813weight_decay=0.1 weight norm 10.48 val loss 0.3795 val ROC-AUC 0.829weight_decay=1.0 weight norm 3.73 val loss 0.3631 val ROC-AUC 0.839from sklearn.metrics import roc_auc_score
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()loss_fn = nn.BCEWithLogitsLoss()# TODO: for weight_decay in [0.0, 0.1, 1.0]: seed, model, AdamW, seeded loader# train 20 epochs; compute the weight norm, the validation loss and ROC-AUCHint 1
named_parameters() gives names such as 0.weight and 0.bias. Keep the ones that end with weight.
Hint 2
The norm of several tensors is the square root of the sum of all their squared elements.
Solution
from sklearn.metrics import roc_auc_score
X_tr, X_va, X_te, y_tr, y_va, y_te = churn_tensors()loss_fn = nn.BCEWithLogitsLoss()norms = []for weight_decay in [0.0, 0.1, 1.0]: torch.manual_seed(42) model = nn.Sequential(nn.Linear(22, 64), nn.ReLU(), nn.Linear(64, 1), nn.Flatten(0)) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2, weight_decay=weight_decay) loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42)) for _ in range(20): train_one_epoch(model, loader, loss_fn, optimizer) model.eval() with torch.no_grad(): logits = model(X_va) val_loss = loss_fn(logits, y_va).item() auc = roc_auc_score(y_va.numpy(), logits.numpy()) norm = torch.sqrt(sum((p**2).sum() for name, p in model.named_parameters() if name.endswith("weight"))).item() norms.append(norm) print(f"weight_decay={weight_decay:<4} weight norm {norm:6.2f} " f"val loss {val_loss:.4f} val ROC-AUC {auc:.3f}")assert norms[0] > norms[1] > norms[2]weight_decay=0.0 weight norm 15.17 val loss 0.4156 val ROC-AUC 0.813weight_decay=0.1 weight norm 10.48 val loss 0.3795 val ROC-AUC 0.829weight_decay=1.0 weight norm 3.73 val loss 0.3631 val ROC-AUC 0.839How it works:
- With
lr=1e-2and no decay, 20 epochs let the weights grow large. The network fits the training rows closely and generalizes worse. - Weight decay multiplies every weight by at each step, so the weights stay small. The norm falls as grows.
- Smaller weights give a smoother function of the inputs. Here, that lowers the validation loss and raises the ROC-AUC. Far larger values would shrink the weights so much that the model underfits.
- ROC-AUC is computed from the logits: the sigmoid keeps the order, so probabilities are not needed.
Alternative: torch.optim.Adam(..., weight_decay=λ) adds an L2 penalty to the gradient instead. With Adam’s adaptive steps, that penalty acts unevenly on the parameters, which is why AdamW’s decoupled decay is the standard choice.
M42-X06 · Find the digits the CNN confuses
Section titled “M42-X06 · Find the digits the CNN confuses”Train the lesson’s DigitCNN for 8 epochs (AdamW(lr=0.01), batches of 32, seed 42), then build a 10×10 confusion matrix of the test predictions with tensor operations only (no scikit-learn). Print the test accuracy, the number of mistakes and the three most frequent (true, predicted) confusions with their counts. Break ties by the smaller true digit, then the smaller predicted digit.
accuracy 0.973, 12 mistakestrue 8 predicted as 1: 3true 5 predicted as 9: 2true 0 predicted as 4: 1X_tr, X_te, y_tr, y_te = digit_tensors()
class DigitCNN(nn.Module): # TODO: as in the lesson ...
# TODO: train 8 epochs; predict the test labels in eval mode# TODO: confusion = torch.bincount(y_te * 10 + pred, minlength=100).reshape(10, 10)# TODO: zero the diagonal, sort the off-diagonal counts, print the top 3Hint 1
y_te * 10 + pred turns each (true, predicted) pair into one number from 0 to 99. bincount counts each number.
Hint 2
A stable sort keeps the original order of equal counts. The flat index true * 10 + pred already orders the pairs by true digit, then by predicted digit.
Solution
X_tr, X_te, y_tr, y_te = digit_tensors()
class DigitCNN(nn.Module): def __init__(self, n_filters: int = 16) -> None: super().__init__() self.conv = nn.Conv2d(1, n_filters, kernel_size=3, padding=1) self.pool = nn.MaxPool2d(2) self.fc = nn.Linear(n_filters * 4 * 4, 10)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.fc(self.pool(torch.relu(self.conv(x))).flatten(start_dim=1))
torch.manual_seed(42)cnn = DigitCNN()optimizer = torch.optim.AdamW(cnn.parameters(), lr=0.01)loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42))for _ in range(8): train_one_epoch(cnn, loader, nn.CrossEntropyLoss(), optimizer)cnn.eval()with torch.no_grad(): pred = cnn(X_te).argmax(dim=1)
confusion = torch.bincount(y_te * 10 + pred, minlength=100).reshape(10, 10)mistakes = confusion.clone()mistakes.fill_diagonal_(0)counts, flat_idx = mistakes.flatten().sort(descending=True, stable=True)print(f"accuracy {confusion.diag().sum().item() / len(y_te):.3f}," f" {mistakes.sum().item()} mistakes")for count, idx in zip(counts[:3].tolist(), flat_idx[:3].tolist(), strict=True): print(f"true {idx // 10} predicted as {idx % 10}: {count}")assert confusion.sum().item() == len(y_te)assert mistakes.sum().item() == (pred != y_te).sum().item()accuracy 0.973, 12 mistakestrue 8 predicted as 1: 3true 5 predicted as 9: 2true 0 predicted as 4: 1How it works:
- Row
t, columnpof the confusion matrix counts the test digits of classtthat the model predicted asp. The diagonal holds the correct predictions. bincounton the combined index builds the whole matrix in one call, with no loop.- With
descending=True, stable=True, equal counts keep their flat-index order, which is the tie-break the task asks for. - 8s read as 1s is the top confusion: both are tall, thin strokes on an 8×8 grid. The other mistakes happen only once or twice; on 450 test images, single counts are noise, not patterns.
Alternative: sklearn.metrics.confusion_matrix(y_te, pred) builds the same matrix from NumPy arrays and ConfusionMatrixDisplay plots it.