A linear regression is a single, fully connected neuron.

Figure: one neuron. Each input is multiplied by its weight, the products are added with the bias to give the score , and the activation turns the score into the prediction (figure from lecture 21, book/slides/2026/figscripts/lec21_one_neuron.py).
A single artificial neuron computes a weighted sum of its inputs plus one bias term, then applies an activation function:
,
where is the prediction, are the weights, is the bias of the neuron (one per neuron, not one per input), and is an activation function (e.g., sigmoid, ReLU, etc).
The choice of names the unit. With a step activation that fires when the weighted sum exceeds a threshold, the neuron is a Threshold Logic Unit (TLU): it outputs a hard yes or no. The step has no slope, so a TLU cannot be trained by gradient descent (4.0, section 4.2). With the sigmoid activation, the same neuron computes a logistic regression and outputs a probability instead. A perceptron is a single layer of TLUs, with each TLU connected to all the inputs.
In 4.0 you trained a neuron and a small network with gradient descent written out in NumPy. Here we build our first neural network in PyTorch and train it on a 4-class classification problem; PyTorch computes the gradients (backpropagation) for us. The workflow has five steps that repeat in every deep-learning project:
Prepare the dataset.
Design the model.
Choose the loss function.
Choose the optimizer.
Write the training loop.
Sections 7 to 9 then control overfitting with dropout and batch normalization, keep the best model with a checkpoint, and fit the same network with scikit-learn.
🖥️ Lecture slides, Session 21 (Wed Nov 18): fully connected networks
Your turn. Two cells ask for one line of code each. The hidden cell below each one holds the solution and checks your answer; if your answer is missing, it uses the solution so that the rest of the notebook still runs.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
# Device-agnostic setup: use a GPU if one is available.
device = torch.device("cuda" if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available()
else "cpu")
print("Using device:", device)
torch.manual_seed(42)
np.random.seed(42)Using device: cpu
1. Dataset in PyTorch¶
We reuse the seismic-source dataset from Chapter 3: 62 physical features (waveform, envelope, and spectral statistics) extracted from seismograms of four source types recorded in the Pacific Northwest: earthquake, explosion, noise, and surface event. In Chapter 3 you classified these events with classical machine learning (random forests reached roughly 80-90% accuracy). Here we train a neural network on the same problem, so you can compare the two approaches directly.
The data lives on Zenodo as four CSV files, one per class, with 1,000 events each. We download them with pooch, which caches the files locally.
1.1 Load and label the data¶
import pooch
base = "https://zenodo.org/api/records/14025693/files"
classes = ["earthquakes", "explosion", "noise", "surface"]
frames = []
for c in classes:
fname = f"1000_{c}_physical_features.csv"
path = pooch.retrieve(f"{base}/{fname}/content", known_hash=None, fname=fname)
frames.append(pd.read_csv(path))
df = pd.concat(frames, ignore_index=True)
print(df.shape)
print(df["source"].value_counts())Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_earthquakes_physical_features.csv/content' to file '/home/runner/.cache/pooch/1000_earthquakes_physical_features.csv'.
SHA256 hash of downloaded file: ec7fad7540ea2d869a48960b16e136462e222337650988d6ab8010c6fe4f29e3
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_explosion_physical_features.csv/content' to file '/home/runner/.cache/pooch/1000_explosion_physical_features.csv'.
SHA256 hash of downloaded file: 3582c2719d8255505af69083094cfa87fdfa7166d75bb876f07ec19ca4a3e198
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_noise_physical_features.csv/content' to file '/home/runner/.cache/pooch/1000_noise_physical_features.csv'.
SHA256 hash of downloaded file: 59c12eeec54dff29638d484ca64a31bddc991bb15a4f315b413466f7a620c891
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_surface_physical_features.csv/content' to file '/home/runner/.cache/pooch/1000_surface_physical_features.csv'.
SHA256 hash of downloaded file: a793dcd52d3d9e4dcd6ffe51311ad14311452b35246c6655f2670fdcdf516abe
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
(4000, 65)
source
earthquake 1000
explosion 1000
noise 1000
surface event 1000
Name: count, dtype: int64
1.2 Clean the feature table¶
The table has 65 columns. Three are not features: Unnamed: 0 (a leftover row index), serial_no (an event identifier), and source (the class name, which becomes our label). We map the four class names to integers 0-3, which is the label format that PyTorch’s classification loss expects.
We also check for missing and infinite values. One feature column, Gamma, is empty (all NaN) in this dataset, so we drop the column rather than drop every row or invent values by imputation. After cleaning, no NaN or inf remain and we keep 61 numeric features.
class_names = ["earthquake", "explosion", "noise", "surface event"]
labels = df["source"].map({name: i for i, name in enumerate(class_names)}).to_numpy()
features = df.drop(columns=["Unnamed: 0", "serial_no", "source"])
# Columns that are entirely NaN carry no information: drop them.
all_nan = features.columns[features.isna().all()]
print("Dropping all-NaN columns:", list(all_nan))
features = features.drop(columns=all_nan)
print("Remaining NaN:", int(features.isna().sum().sum()),
"- inf:", int(np.isinf(features.to_numpy()).sum()))
X = features.to_numpy(dtype=np.float32)
n_features = X.shape[1]
print("Feature matrix:", X.shape, "- labels:", labels.shape)Dropping all-NaN columns: ['Gamma']
Remaining NaN: 0 - inf: 0
Feature matrix: (4000, 61) - labels: (4000,)
1.3 Split, then scale¶
We split the data three ways: train (60%) to fit the weights, validation (20%) to monitor generalization during training, and test (20%) held out for the final evaluation. The split is stratified so each subset keeps the same class balance.
Neural networks train poorly when input features span very different ranges, so we standardize each feature to zero mean and unit variance. The scaler is fit on the training set only and then applied to the validation and test sets. Fitting it on all the data would leak information from the held-out sets into training.

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 60% train, 20% validation, 20% test, stratified by class.
X_train, X_tmp, y_train, y_tmp = train_test_split(
X, labels, test_size=0.4, random_state=42, stratify=labels)
X_val, X_test, y_val, y_test = train_test_split(
X_tmp, y_tmp, test_size=0.5, random_state=42, stratify=y_tmp)
scaler = StandardScaler().fit(X_train) # fit on train only
X_train = scaler.transform(X_train).astype(np.float32)
X_val = scaler.transform(X_val).astype(np.float32)
X_test = scaler.transform(X_test).astype(np.float32)
print("train:", X_train.shape, " val:", X_val.shape, " test:", X_test.shape)train: (2400, 61) val: (800, 61) test: (800, 61)
1.4 Create a custom Dataset class¶
PyTorch provides the Dataset class that you can use to wrap your arrays. You need to implement the __len__ and __getitem__ methods. The class also converts the NumPy arrays into tensors: float32 for the features, int64 (long) for the class labels.
from torch.utils.data import Dataset
class SeismicFeatures(Dataset):
def __init__(self, data, labels):
self.data = torch.tensor(data, dtype=torch.float32)
self.labels = torch.tensor(labels, dtype=torch.long)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index], self.labels[index]
train_dataset = SeismicFeatures(X_train, y_train)
val_dataset = SeismicFeatures(X_val, y_val)
test_dataset = SeismicFeatures(X_test, y_test)
sample_x, sample_y = train_dataset[0]
print("one sample:", sample_x.shape, sample_x.dtype, "- label:", sample_y.item())one sample: torch.Size([61]) torch.float32 - label: 1
1.5 Create a DataLoader¶
Once you have a dataset, a DataLoader handles batching and shuffling. We shuffle the training set at every epoch so batches are different each time; validation and test sets do not need shuffling.
from torch.utils.data import DataLoader
batch_size = 128
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
for batch_data, batch_labels in train_loader:
print("batch data:", batch_data.shape)
print("batch labels:", batch_labels.shape)
breakbatch data: torch.Size([128, 61])
batch labels: torch.Size([128])
2. Design the Model¶
Our first neural network has a single hidden layer: a linear map from the 61 input features to 32 hidden units, a ReLU activation, and a linear map from the hidden units to 4 output scores, one per class.
The raw outputs are called logits. We do not apply softmax inside the model: PyTorch’s cross-entropy loss (Section 3) applies it internally, which is both numerically safer and the standard practice.
A model is a subclass of nn.Module. The __init__ method declares the layers; the forward method defines how data flows through them.



class NN1(nn.Module):
def __init__(self, n_features, n_hidden, n_classes):
# super() makes NN1 inherit the machinery of nn.Module
super().__init__()
self.hidden = nn.Linear(n_features, n_hidden) # z1 = W1 x + b1
self.activation = nn.ReLU() # a1 = max(0, z1)
self.output = nn.Linear(n_hidden, n_classes) # logits = W2 a1 + b2
def forward(self, x):
x = self.activation(self.hidden(x))
return self.output(x) # raw logits; softmax lives in the lossWe create a model of the class NN1 and move it to the compute device with .to(device). All tensors we feed it must live on the same device.
model = NN1(n_features=n_features, n_hidden=32, n_classes=4).to(device)
print(model)
n_params = sum(p.numel() for p in model.parameters())
print(f"trainable parameters: {n_params}")NN1(
(hidden): Linear(in_features=61, out_features=32, bias=True)
(activation): ReLU()
(output): Linear(in_features=32, out_features=4, bias=True)
)
trainable parameters: 2116
2.1 Random starting weights¶
nn.Linear does not start from zeros. It draws each weight at random from a uniform distribution between and , where is the number of inputs of the layer, and the biases the same way. Random starting weights make the 32 hidden neurons differ from the first update; with equal weights they would receive equal gradients and stay copies of each other (4.0, section 2.1). The call torch.manual_seed(42) at the top of the notebook fixes these random numbers, so every run starts from the same weights.
W1 = model.hidden.weight.detach().cpu().numpy() # 32 x 61 weights of the hidden layer
print(f"hidden-layer weights: {W1.size}, between {W1.min():.3f} and {W1.max():.3f}, "
f"bound 1/sqrt({n_features}) = {1 / np.sqrt(n_features):.3f}")
print("first five weights of hidden neuron 1:", W1[0, :5].round(3))
print("weights equal to zero:", int((W1 == 0).sum()))hidden-layer weights: 1952, between -0.127 and 0.128, bound 1/sqrt(61) = 0.128
first five weights of hidden neuron 1: [-0.028 0.026 -0.062 0.075 0.113]
weights equal to zero: 0
3. Loss Function¶
The loss measures, for each sample, how far the prediction is from the observation; training lowers its mean over a batch (4.0, sections 2.3 and 4.1).
Two classes. The neuron’s score goes through the sigmoid, , the predicted probability that the sample belongs to class 1. The loss of one sample is the log-loss (or binary cross-entropy):
,
where the observation is 1 or 0. It is near 0 when the predicted probability agrees with the observation, and grows without bound when the network is confident and wrong. Lowering its mean is the same as choosing the weights that make the observed labels most probable.

classes. The network now has outputs, one score per class (here ). The softmax turns the scores into probabilities that add up to 1:
.
The predicted class is the one with the largest probability. The loss of one sample is the cross-entropy:
,
where for the observed class of sample and 0 otherwise: only the probability given to the observed class counts. With two classes it is the log-loss above.
In PyTorch, nn.CrossEntropyLoss applies the softmax and the cross-entropy in one function, which is why the model outputs raw scores (logits). By default it returns the mean of the losses over the samples of the batch.
criterion = nn.CrossEntropyLoss()
criterionCrossEntropyLoss()3.1 The loss of each sample, and its mean over a batch¶
As in 4.0, each sample has its own loss, and the loss used for training is the mean over the samples of a batch. nn.CrossEntropyLoss() returns that mean directly. With reduction="none" it returns the loss of each sample instead. We look at the first 128 training events, before any training.
Your turn (1): the mean loss of a batch¶
lossPerSample holds the loss of each of the 128 events. Compute batchLoss, their mean, and compare it with what criterion returns.
Hint: lossPerSample.mean().item().
xBatch = torch.tensor(X_train[:128]).to(device)
yBatch = torch.tensor(y_train[:128], dtype=torch.long).to(device)
with torch.no_grad():
logitsBatch = model(xBatch)
lossPerSample = nn.CrossEntropyLoss(reduction="none")(logitsBatch, yBatch) # one loss per event
batchLoss = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
batchLoss = lossPerSample.mean().item()with torch.no_grad():
print(f"criterion on the same batch: {criterion(logitsBatch, yBatch).item():.4f} mean of the 128 losses: {batchLoss:.4f}")
print(f"loss of one event: from {lossPerSample.min().item():.3f} to {lossPerSample.max().item():.3f}")
print(f"a model that gives 1/4 to every class has a loss of ln 4 = {np.log(4):.3f} for every event")
fig, ax = plt.subplots(figsize=(6, 3.5))
ax.hist(lossPerSample.cpu().numpy(), bins=25, color="tab:red")
ax.axvline(batchLoss, color="k", ls="--", label=f"mean: the loss of the batch, {batchLoss:.3f}")
ax.set_xlabel("Cross-entropy loss of one event")
ax.set_ylabel("Number of events")
ax.set_title("Before training: 128 training events")
ax.legend()
fig.tight_layout()criterion on the same batch: 1.4221 mean of the 128 losses: 1.4221
loss of one event: from 1.073 to 2.581
a model that gives 1/4 to every class has a loss of ln 4 = 1.386 for every event

With random weights the network is close to guessing: most losses are near ln 4, and the loss of the batch is their mean.
4. Optimization¶
Gradient descent uses the entire data set to compute the gradient and step toward the minimum of the loss. Effectively, the batch size is the entire data set.
Mini-batch gradient descent uses batches of data to compute the gradient, updates the weights, and moves on to the next batch. The loss is averaged over the samples in the batch before the gradient is computed.
Stochastic gradient descent (SGD) uses one sample at a time. Effectively, the batch size is 1.
We use mini-batches with the Adam optimizer, a variant of gradient descent that adapts the step size for each parameter from running averages of the gradient and its square. Adam usually converges faster than plain SGD and is the default choice for a first attempt.
Parameters to choose are:
the optimizer (SGD, Adam, or others),
the learning rate (the scale of the step taken along the gradient).
learning_rate = 1e-3
optimizer = optim.Adam(model.parameters(), lr=learning_rate)5. Training¶
Parameters to choose are:
batch size: the number of samples whose losses are averaged before each update of the weights (128 here, so 19 updates per epoch on 2,400 training events);
number of epochs: the number of passes over the entire training set. Models are typically trained for tens to thousands of epochs.
The training loop below is the loop of 4.0, section 2.7, in PyTorch. For each batch:
| 4.0, in NumPy | 4.1, in PyTorch |
|---|---|
| predictions | outputs = model(inputs) (forward pass) |
| loss of each sample, mean over the batch | loss = criterion(outputs, targets) |
| gradient of the loss for every weight (backpropagation) | loss.backward() |
| update: gradient | optimizer.step() |
| (gradients start from zero each time) | optimizer.zero_grad() |
The function records the loss of every batch as it trains, and at the end of each epoch the mean loss and the accuracy on the training and validation sets, computed with gradients disabled (torch.no_grad()), since no learning happens there.

def evaluate(model, loader, criterion):
"""Mean loss and accuracy (%) of the model over one DataLoader."""
model.eval()
total_loss, correct, total = 0.0, 0, 0
with torch.no_grad():
for inputs, targets in loader:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
total_loss += criterion(outputs, targets).item() * targets.size(0)
predicted = outputs.argmax(dim=1)
correct += (predicted == targets).sum().item()
total += targets.size(0)
return total_loss / total, 100 * correct / total
def train(model, n_epochs, train_loader, val_loader, criterion, optimizer):
history = {"train_loss": [], "train_acc": [], "val_loss": [], "val_acc": [], "batch_loss": []}
for epoch in range(n_epochs):
model.train()
for inputs, targets in train_loader:
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad() # gradients start from zero
outputs = model(inputs) # forward pass: predictions
loss = criterion(outputs, targets) # loss: mean over the samples of the batch
loss.backward() # backward pass: gradient of every weight
optimizer.step() # update every weight against its gradient
history["batch_loss"].append(loss.item())
# Evaluate on both sets at the end of the epoch
train_loss, train_acc = evaluate(model, train_loader, criterion)
val_loss, val_acc = evaluate(model, val_loader, criterion)
history["train_loss"].append(train_loss)
history["train_acc"].append(train_acc)
history["val_loss"].append(val_loss)
history["val_acc"].append(val_acc)
if (epoch + 1) % 5 == 0 or epoch == 0:
print(f"[Epoch {epoch + 1:3d}] train loss: {train_loss:.3f} "
f"- val loss: {val_loss:.3f} - val accuracy: {val_acc:.1f}%")
return historyWe train for 40 epochs, which takes a few seconds. Students can raise n_epochs or the hidden-layer size on their own machines to see how far this small model can go.
n_epochs = 40
history = train(model, n_epochs, train_loader, val_loader, criterion, optimizer)[Epoch 1] train loss: 1.157 - val loss: 1.150 - val accuracy: 71.0%
[Epoch 5] train loss: 0.603 - val loss: 0.586 - val accuracy: 81.4%
[Epoch 10] train loss: 0.462 - val loss: 0.461 - val accuracy: 84.9%
[Epoch 15] train loss: 0.401 - val loss: 0.423 - val accuracy: 86.1%
[Epoch 20] train loss: 0.365 - val loss: 0.405 - val accuracy: 86.1%
[Epoch 25] train loss: 0.339 - val loss: 0.388 - val accuracy: 86.9%
[Epoch 30] train loss: 0.320 - val loss: 0.378 - val accuracy: 87.8%
[Epoch 35] train loss: 0.302 - val loss: 0.373 - val accuracy: 88.5%
[Epoch 40] train loss: 0.287 - val loss: 0.369 - val accuracy: 88.5%
Let us plot the learning curves: loss on the left axis, accuracy on the right axis, for both the training and validation sets. Solid lines are the training set, dashed lines the validation set. When the two curves track each other, the model generalizes; when the validation curve flattens or turns while the training curve keeps improving, the model is starting to overfit.
epochs = np.arange(1, n_epochs + 1)
fig, ax1 = plt.subplots(figsize=(7, 4))
loss_color = "tab:red"
ax1.set_xlabel("Epoch")
ax1.set_ylabel("Cross-entropy loss", color=loss_color)
ax1.plot(epochs, history["train_loss"], color=loss_color, label="train loss")
ax1.plot(epochs, history["val_loss"], color=loss_color, linestyle="--", label="validation loss")
ax1.tick_params(axis="y", labelcolor=loss_color)
ax2 = ax1.twinx()
acc_color = "tab:blue"
ax2.set_ylabel("Accuracy (%)", color=acc_color)
ax2.plot(epochs, history["train_acc"], color=acc_color, label="train accuracy")
ax2.plot(epochs, history["val_acc"], color=acc_color, linestyle="--", label="validation accuracy")
ax2.tick_params(axis="y", labelcolor=acc_color)
lines = ax1.get_lines() + ax2.get_lines()
ax1.legend(lines, [l.get_label() for l in lines], loc="center right", fontsize=9)
ax1.set_title("Learning curves")
fig.tight_layout()
plt.show()
The learning curves show one point per epoch. Below, the loss of every batch during training (19 per epoch) with its mean over each epoch. As in 4.0, section 2.7, the batch losses scatter around the mean, because each batch holds different events.
batchLosses = np.array(history["batch_loss"])
perEpoch = len(batchLosses) // n_epochs
fig, ax = plt.subplots(figsize=(7, 3.8))
ax.plot(np.arange(len(batchLosses)) / perEpoch, batchLosses, ".", ms=3, color="tab:gray", label="loss of one batch (128 events)")
ax.plot(np.arange(n_epochs) + 0.5, batchLosses.reshape(n_epochs, perEpoch).mean(axis=1), color="tab:red",
lw=2, label="mean over the batches of the epoch")
ax.set_xlabel("Epoch")
ax.set_ylabel("Cross-entropy loss")
ax.set_title(f"{len(batchLosses)} updates: {perEpoch} batches per epoch")
ax.legend()
fig.tight_layout()
print(f"loss of the first batch {batchLosses[0]:.3f}, of the last {batchLosses[-1]:.3f}; "
f"last epoch: batches from {batchLosses[-perEpoch:].min():.3f} to {batchLosses[-perEpoch:].max():.3f}")loss of the first batch 1.404, of the last 0.287; last epoch: batches from 0.223 to 0.411

6. Evaluate on the Test Set¶
The validation set guided training; the test set gives the final, unbiased score. We report the overall accuracy and the confusion matrix, which shows which classes get mixed up.
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
test_loss, test_acc = evaluate(model, test_loader, criterion)
print(f"Test loss: {test_loss:.3f} - test accuracy: {test_acc:.1f}%")
# Predictions for the whole test set
model.eval()
with torch.no_grad():
logits = model(torch.tensor(X_test, dtype=torch.float32).to(device))
y_pred = logits.argmax(dim=1).cpu().numpy()
cm = confusion_matrix(y_test, y_pred)
disp = ConfusionMatrixDisplay(cm, display_labels=class_names)
fig, ax = plt.subplots(figsize=(5.5, 5))
disp.plot(ax=ax, cmap="Blues", colorbar=False, xticks_rotation=45)
ax.set_title("Test-set confusion matrix")
fig.tight_layout()
plt.show()Test loss: 0.375 - test accuracy: 87.1%

Noise separates cleanly from the rest. Most confusion occurs among the seismic sources, chiefly between earthquakes and explosions, which produce similar waveforms. Compare this matrix with your Chapter 3 results on the same data: a one-hidden-layer network and a tuned random forest land in a similar range, which is common on small tabular datasets.
7. Overfitting and two ways to control it: dropout and batch normalization¶
The network of sections 2 to 6 has one hidden layer of 32 neurons and 2,116 weights for 2,400 training events. At epoch 40 its validation loss was still falling and stayed close to the training loss (0.37 against 0.29): there was little overfitting to control. A network with more weights can fit the training events much better than the validation events. We build one with three hidden layers (128, 64 and 32 neurons) and add two layer types that limit overfitting.
Dropout (nn.Dropout(p)) sets a random fraction p of the hidden outputs to zero for each batch during training, and multiplies the others by so that their sum keeps the same scale. No neuron can rely on one particular neuron of the previous layer, so the network spreads what it learns over many neurons. Dropout acts only in training mode.
Batch normalization (nn.BatchNorm1d) rescales the output of each hidden neuron to zero mean and unit variance over the events of the current batch, then applies a learned scale and shift. It keeps the inputs of the next layer in a stable range while the weights change, which steadies training. Because the mean and variance change from batch to batch, it also adds a little noise, a mild regularization. In evaluation mode it uses running averages of the mean and variance collected during training.
Both layers behave differently in the two modes. The functions train() and evaluate() of section 5 already call model.train() and model.eval(), so we reuse them unchanged.

class DeepMLP(nn.Module):
def __init__(self, n_features, n_classes, p_drop=0.3):
super().__init__()
self.net = nn.Sequential( # layers applied in this order
nn.Linear(n_features, 128),
nn.BatchNorm1d(128),
nn.ReLU(),
nn.Dropout(p_drop),
nn.Linear(128, 64),
nn.BatchNorm1d(64),
nn.ReLU(),
nn.Dropout(p_drop),
nn.Linear(64, 32),
nn.BatchNorm1d(32),
nn.ReLU(),
nn.Linear(32, n_classes), # raw logits; softmax lives in the loss
)
def forward(self, x):
return self.net(x)nn.Sequential chains the layers in the order given, so forward is one line. The new network starts from random weights, drawn right after torch.manual_seed(42) so that they are the same at every run, whatever ran above. Optimizer, learning rate, batch size, loss and number of epochs are those of sections 3 to 5.
torch.manual_seed(42) # random starting weights, fixed by the seed
model_deep = DeepMLP(n_features, n_classes=4, p_drop=0.3).to(device)
print(model_deep)
print(f"trainable parameters: {sum(p.numel() for p in model_deep.parameters())} (one hidden layer: {n_params})")
optimizer_deep = optim.Adam(model_deep.parameters(), lr=learning_rate)
history_deep = train(model_deep, n_epochs, train_loader, val_loader, criterion, optimizer_deep)DeepMLP(
(net): Sequential(
(0): Linear(in_features=61, out_features=128, bias=True)
(1): BatchNorm1d(128, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
(2): ReLU()
(3): Dropout(p=0.3, inplace=False)
(4): Linear(in_features=128, out_features=64, bias=True)
(5): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
(6): ReLU()
(7): Dropout(p=0.3, inplace=False)
(8): Linear(in_features=64, out_features=32, bias=True)
(9): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True)
(10): ReLU()
(11): Linear(in_features=32, out_features=4, bias=True)
)
)
trainable parameters: 18852 (one hidden layer: 2116)
[Epoch 1] train loss: 0.994 - val loss: 0.989 - val accuracy: 76.5%
[Epoch 5] train loss: 0.432 - val loss: 0.445 - val accuracy: 86.5%
[Epoch 10] train loss: 0.302 - val loss: 0.353 - val accuracy: 88.2%
[Epoch 15] train loss: 0.239 - val loss: 0.327 - val accuracy: 89.6%
[Epoch 20] train loss: 0.209 - val loss: 0.316 - val accuracy: 89.8%
[Epoch 25] train loss: 0.178 - val loss: 0.320 - val accuracy: 89.8%
[Epoch 30] train loss: 0.156 - val loss: 0.318 - val accuracy: 89.9%
[Epoch 35] train loss: 0.137 - val loss: 0.318 - val accuracy: 90.4%
[Epoch 40] train loss: 0.124 - val loss: 0.317 - val accuracy: 89.5%
7.1 Learning curves and test accuracy¶
Left, the network of sections 2 to 6; right, the deeper network. Solid lines are the training set, dashed lines the validation set, as in section 5. The training loss is computed in evaluation mode at the end of each epoch, with dropout off, so the two curves of each panel compare the same network.
def plot_loss(ax, h, title):
ep = np.arange(1, len(h["train_loss"]) + 1)
ax.plot(ep, h["train_loss"], color="tab:red", label="train loss")
ax.plot(ep, h["val_loss"], color="tab:red", linestyle="--", label="validation loss")
ax.set_xlabel("Epoch")
ax.set_title(title, fontsize=10)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), sharey=True)
plot_loss(axes[0], history, "One hidden layer (32 neurons)")
plot_loss(axes[1], history_deep, "Three hidden layers, dropout 0.3, batch normalization")
axes[0].set_ylabel("Cross-entropy loss")
axes[0].legend()
fig.tight_layout()
plt.show()
def standard_error(acc, n):
# standard error (in points) of an accuracy acc (%) measured on n events
return 100 * np.sqrt(acc / 100 * (1 - acc / 100) / n)
test_loss_deep, test_acc_deep = evaluate(model_deep, test_loader, criterion)
print(f"test accuracy, one hidden layer: {test_acc:.1f}%")
print(f"test accuracy, three hidden layers, dropout 0.3: {test_acc_deep:.1f}%")
print(f"one standard error on {len(y_test)} test events: about {standard_error(test_acc, len(y_test)):.1f} points")
test accuracy, one hidden layer: 87.1%
test accuracy, three hidden layers, dropout 0.3: 89.4%
one standard error on 800 test events: about 1.2 points
The deeper network fits the training events better (training loss 0.13 against 0.29 at epoch 40) and the validation events too (0.32 against 0.37). Its two curves are further apart, but its validation loss is still falling slowly at epoch 40: dropout and batch normalization keep the extra weights in check. On the test set it reaches 89.2% against 87.1%, 17 more events out of 800. The difference, 2.1 points, is larger than one standard error, on one split and one seed. A random forest reached 88.5% on the same split (computed for lecture 21, book/slides/2026/figscripts/lec21_one_neuron.py).
Your turn (2): remove dropout¶
Retrain the deeper network without dropout and compare the curves. Set p_drop_off to the dropout probability that turns dropout off. The hidden cell builds DeepMLP with it from the same seed, trains it for 40 epochs and plots the three pairs of loss curves. Dropout layers have no weights, so the network without dropout starts from the same weights as model_deep.
Hint: p is the fraction of hidden outputs set to zero.
p_drop_off = None # replace None with your valueAnswer below (click to open it).
Notebook Cell
p_drop_off = 0.0torch.manual_seed(42) # same seed: same starting weights as model_deep
model_nodrop = DeepMLP(n_features, n_classes=4, p_drop=p_drop_off).to(device)
optimizer_nodrop = optim.Adam(model_nodrop.parameters(), lr=learning_rate)
history_nodrop = train(model_nodrop, n_epochs, train_loader, val_loader, criterion, optimizer_nodrop)
test_loss_nodrop, test_acc_nodrop = evaluate(model_nodrop, test_loader, criterion)
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8), sharey=True)
plot_loss(axes[0], history, "One hidden layer (32 neurons)")
plot_loss(axes[1], history_deep, "Three hidden layers, dropout 0.3")
plot_loss(axes[2], history_nodrop, "Three hidden layers, no dropout")
axes[0].set_ylabel("Cross-entropy loss")
axes[0].legend()
fig.tight_layout()
plt.show()
for name, h, acc in [("one hidden layer", history, test_acc),
("three hidden layers, dropout 0.3", history_deep, test_acc_deep),
("three hidden layers, no dropout", history_nodrop, test_acc_nodrop)]:
best = int(np.argmin(h["val_loss"]))
print(f"{name:34s} epoch 40: train loss {h['train_loss'][-1]:.3f}, val loss {h['val_loss'][-1]:.3f} "
f"(lowest {h['val_loss'][best]:.3f} at epoch {best + 1}); test accuracy {acc:.1f}%")[Epoch 1] train loss: 0.916 - val loss: 0.915 - val accuracy: 79.1%
[Epoch 5] train loss: 0.338 - val loss: 0.402 - val accuracy: 87.5%
[Epoch 10] train loss: 0.181 - val loss: 0.348 - val accuracy: 88.4%
[Epoch 15] train loss: 0.107 - val loss: 0.363 - val accuracy: 88.2%
[Epoch 20] train loss: 0.058 - val loss: 0.374 - val accuracy: 88.9%
[Epoch 25] train loss: 0.029 - val loss: 0.405 - val accuracy: 88.0%
[Epoch 30] train loss: 0.034 - val loss: 0.449 - val accuracy: 85.6%
[Epoch 35] train loss: 0.013 - val loss: 0.453 - val accuracy: 87.5%
[Epoch 40] train loss: 0.008 - val loss: 0.485 - val accuracy: 86.5%

one hidden layer epoch 40: train loss 0.287, val loss 0.369 (lowest 0.369 at epoch 40); test accuracy 87.1%
three hidden layers, dropout 0.3 epoch 40: train loss 0.124, val loss 0.317 (lowest 0.309 at epoch 23); test accuracy 89.4%
three hidden layers, no dropout epoch 40: train loss 0.008, val loss 0.485 (lowest 0.343 at epoch 11); test accuracy 86.9%
Without dropout, the training loss falls to 0.006 at epoch 40: the network gives almost every training event its observed class with near certainty. Its validation loss is lowest, 0.34, at epoch 11, and rises to 0.46 by epoch 40. The two curves part: the network memorizes the training events instead of learning what generalizes. This is overfitting, and the test accuracy drops to 87.6%. Both deeper networks have batch normalization, so the difference between the middle and right panels is dropout alone.
8. Saving and restoring a model¶
8.1 The weights live in a state_dict¶
The numbers a PyTorch model learns live in its state_dict, a dictionary that maps the name of each weight and bias tensor to its values. Batch normalization also stores its running mean and variance there. To save a trained model, save this dictionary with torch.save. To restore it, build a new model of the same class, load the dictionary into it with load_state_dict, and call model.eval() before predicting. The argument map_location=device lets weights saved on a GPU load on a computer without one. Files go in a local folder checkpoints/.
import os
os.makedirs("checkpoints", exist_ok=True)
state = model_deep.state_dict()
for name in list(state)[:7]:
print(f"{name:26s} {tuple(state[name].shape)}")
print(f"... {len(state)} entries in all")
torch.save(state, "checkpoints/deep_mlp_weights.pt")
restored = DeepMLP(n_features, n_classes=4).to(device) # new model, new random weights
restored.load_state_dict(torch.load("checkpoints/deep_mlp_weights.pt", map_location=device))
restored.eval()
model_deep.eval()
with torch.no_grad():
X_test_t = torch.tensor(X_test, dtype=torch.float32).to(device)
same = torch.equal(model_deep(X_test_t).argmax(dim=1), restored(X_test_t).argmax(dim=1))
print("restored model gives the same 800 test predictions:", same)net.0.weight (128, 61)
net.0.bias (128,)
net.1.weight (128,)
net.1.bias (128,)
net.1.running_mean (128,)
net.1.running_var (128,)
net.1.num_batches_tracked ()
... 23 entries in all
restored model gives the same 800 test predictions: True
8.2 Keep the best model with a checkpoint¶
The last epoch is not always the best one. When a network overfits, its validation loss stops falling and rises while training continues, and the weights of the last epoch are worse than those of an earlier epoch. A checkpoint saves the model each time the validation loss reaches a new low, together with the epoch and the state of the optimizer, which lets you resume training from that point.
The function below is the loop of train() with the checkpoint added after the evaluation on the validation set. We apply it to the network without dropout, which overfit most in section 7, from the same seed.
def train_with_checkpoint(model, n_epochs, train_loader, val_loader, criterion, optimizer, path):
best_val_loss = float("inf")
val_losses = []
for epoch in range(n_epochs):
model.train()
for inputs, targets in train_loader:
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad() # gradients start from zero
loss = criterion(model(inputs), targets)
loss.backward() # gradient of every weight
optimizer.step() # update every weight
val_loss, val_acc = evaluate(model, val_loader, criterion)
val_losses.append(val_loss)
if val_loss < best_val_loss: # a new lowest validation loss: save this model
best_val_loss = val_loss
torch.save({"epoch": epoch + 1,
"state_dict": model.state_dict(),
"optimizer": optimizer.state_dict(),
"val_loss": val_loss}, path)
return val_losses
torch.manual_seed(42)
model_ckpt = DeepMLP(n_features, n_classes=4, p_drop=0.0).to(device)
optimizer_ckpt = optim.Adam(model_ckpt.parameters(), lr=learning_rate)
val_losses_ckpt = train_with_checkpoint(model_ckpt, n_epochs, train_loader, val_loader, criterion,
optimizer_ckpt, "checkpoints/best_deep_mlp.pt")We restore the checkpoint into a new model and evaluate both versions once on the test set.
ckpt = torch.load("checkpoints/best_deep_mlp.pt", map_location=device)
best_model = DeepMLP(n_features, n_classes=4, p_drop=0.0).to(device)
best_model.load_state_dict(ckpt["state_dict"])
fig, ax = plt.subplots(figsize=(6.5, 3.5))
ax.plot(np.arange(1, n_epochs + 1), val_losses_ckpt, color="tab:red", linestyle="--", label="validation loss")
ax.axvline(ckpt["epoch"], color="k", lw=1, label=f"checkpoint: epoch {ckpt['epoch']}")
ax.set_xlabel("Epoch")
ax.set_ylabel("Cross-entropy loss")
ax.set_title("Three hidden layers, no dropout")
ax.legend()
fig.tight_layout()
plt.show()
_, acc_last = evaluate(model_ckpt, test_loader, criterion)
_, acc_best = evaluate(best_model, test_loader, criterion)
print(f"checkpoint: epoch {ckpt['epoch']}, validation loss {ckpt['val_loss']:.3f} "
f"(epoch {n_epochs}: {val_losses_ckpt[-1]:.3f})")
print(f"test accuracy, weights of epoch {n_epochs}: {acc_last:.1f}%")
print(f"test accuracy, weights of the checkpoint: {acc_best:.1f}%")
checkpoint: epoch 9, validation loss 0.341 (epoch 40: 0.492)
test accuracy, weights of epoch 40: 87.0%
test accuracy, weights of the checkpoint: 88.8%
The validation loss is lowest at epoch 9 and rises afterwards. The checkpoint kept the weights of epoch 9, which reach 88.8% on the test set against 87.1% for the weights of epoch 40. The epoch differs from section 7 (epoch 11) because train() also evaluates the shuffled training set at every epoch, which draws other random numbers for the shuffling. The checkpoint was chosen with the validation set; the test set only reports the result.
9. The same network in scikit-learn¶
scikit-learn has its own fully connected network, MLPClassifier (and MLPRegressor). It trains on batches with Adam by default, behind the fit and predict of Chapter 3. In exchange you give up the training loop, dropout, batch normalization, checkpoints and the GPU. We fit the network of section 2 (one hidden layer of 32 ReLU neurons) on the same scaled training events, with the same batch size, learning rate and number of epochs. MLPClassifier adds by default a small penalty on the size of the weights (alpha=1e-4) and draws its own random starting weights (random_state=42).
import warnings
from sklearn.exceptions import ConvergenceWarning
from sklearn.neural_network import MLPClassifier
mlp = MLPClassifier(hidden_layer_sizes=(32,), batch_size=batch_size, learning_rate_init=learning_rate,
max_iter=n_epochs, random_state=42) # max_iter counts epochs
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning) # we stop at 40 epochs on purpose
mlp.fit(X_train, y_train)
print(f"test accuracy, scikit-learn MLPClassifier: {100 * mlp.score(X_test, y_test):.1f}%")
print(f"test accuracy, PyTorch, section 6: {test_acc:.1f}%")test accuracy, scikit-learn MLPClassifier: 87.4%
test accuracy, PyTorch, section 6: 87.1%
The two versions of the same network differ by 0.3 points, less than one standard error: a tie. They draw different random starting weights and shuffle the batches differently, so they do not end on the same weights.
For regression, the output layer has one neuron per predicted value and no activation, and the loss is the mean squared error between predictions and observations (nn.MSELoss in PyTorch, MLPRegressor in scikit-learn). Notebook 4.2 trains such a network.
Best practices for a fully connected network (classification)¶
Fit a baseline first. The model with no hidden layer reaches 86.8% on the same 800 test events; a network has to beat it.
Fit the scaler on the training samples only, then apply it to the validation and test samples.
Start from random weights drawn with a seed, and report the seed (42 here).
Watch the training and validation loss at every epoch.
Add dropout or batch normalization only when the two curves part.
Keep the model with the lowest validation loss with a checkpoint, not the model of the last epoch.
Evaluate once on the test set, with the accuracy and a confusion matrix.
Report differences smaller than one standard error (about 1.2 points on 800 events) as ties.
Summary¶
You trained a network in PyTorch with the loop of 4.0: forward pass, mean loss over each batch, backward pass (loss.backward(), backpropagation), update (optimizer.step()), from random starting weights, reading the loss at every batch and every epoch. You built a complete workflow: a Dataset and DataLoader for the seismic-source features, a one-hidden-layer network, the cross-entropy loss, the Adam optimizer, and a training loop with learning curves and a held-out test evaluation. Sections 7 to 9 added a deeper network with dropout and batch normalization, a checkpoint that keeps the model with the lowest validation loss, and the same network in scikit-learn; notebook 4.2 applies this workflow to regression. In notebook 4.7 we tune architecture and training hyperparameters systematically instead of picking them by hand.
Baseline. A model with no hidden layer, the multiclass logistic regression of Chapter 3 (61 × 4 + 4 = 248 weights), reaches 86.8% on these same 800 test events (computed for lecture 21, book/slides/2026/figscripts/lec21_one_neuron.py). The hidden layer adds 0.4 points, which is 3 events and less than one standard error of an accuracy measured on 800 events (about 1.2 points). On this table of hand-built features, the network and its linear baseline cannot be told apart.