Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A linear regression is a single, fully connected neuron.

One neuron: inputs, weights, weighted sum plus bias, activation

Figure: one neuron. Each input is multiplied by its weight, the products are added with the bias to give the score zz, 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:

y^=f(∑i=1nwixi+b)\hat{y} = f\left( \sum_{i=1}^n w_i x_i + b \right),

where y^\hat{y} is the prediction, wiw_i are the weights, bb is the bias of the neuron (one per neuron, not one per input), and ff is an activation function (e.g., sigmoid, ReLU, etc).

The choice of ff 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:

  1. Prepare the dataset.

  2. Design the model.

  3. Choose the loss function.

  4. Choose the optimizer.

  5. 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.

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

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.

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.

Why scale: in raw units the loss is a narrow valley and gradient descent crawls; scaled, the same steps reach the lowest loss (lecture 21b)
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.

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.

batch 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.

The network of this section: 61 features in, 32 hidden neurons with ReLU, 4 scores out (lecture 21b)One dense layer by hand: each neuron is a weighted sum of all inputs plus its bias, then ReLU; in matrix form z = Wx + b (lecture 21b)Counting weights: outputs × (inputs + 1) for each layer (lecture 21b)

We 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.

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 −1/n-1/\sqrt{n} and 1/n1/\sqrt{n}, where nn 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.

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 zz goes through the sigmoid, y^=1/(1+e−z)\hat{y} = 1 / (1 + e^{-z}), the predicted probability that the sample belongs to class 1. The loss of one sample is the log-loss (or binary cross-entropy):

Li=−(yilog⁡y^i+(1−yi)log⁡(1−y^i))\mathcal{L}_i = - \left( y_i \log \hat{y}_i + (1 - y_i) \log (1 - \hat{y}_i) \right),

where the observation yiy_i 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.

Cross-entropy looks only at the probability given to the observed class (lecture 21b)

KK classes. The network now has KK outputs, one score zkz_k per class (here K=4K = 4). The softmax turns the scores into probabilities that add up to 1:

y^k=ezk∑j=1Kezj\hat{y}_k = \frac{e^{z_k}}{\sum_{j = 1}^K e^{z_j}}.

The predicted class is the one with the largest probability. The loss of one sample is the cross-entropy:

Li=−∑k=1Kyiklog⁡y^ik=−log⁡y^i,true class\mathcal{L}_i = - \sum_{k = 1}^K y_{ik} \log \hat{y}_{ik} = - \log \hat{y}_{i,\text{true class}},

where yik=1y_{ik} = 1 for the observed class of sample ii 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.

CrossEntropyLoss()

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().

Answer below (click to open it).

Notebook Cell
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
<Figure size 600x350 with 1 Axes>

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).

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 NumPy4.1, in PyTorch
predictionsoutputs = model(inputs) (forward pass)
loss of each sample, mean over the batchloss = criterion(outputs, targets)
gradient of the loss for every weight (backpropagation)loss.backward()
update: w−α×w - \alpha \times gradientoptimizer.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.

The loop of this section, and of every network in Chapter 4: one update per batch, one validation check per epoch (lecture 23)

We 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.

[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.

<Figure size 700x400 with 2 Axes>

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.

loss of the first batch 1.404, of the last 0.287; last epoch: batches from 0.223 to 0.411
<Figure size 700x380 with 1 Axes>

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.

Test loss: 0.375 - test accuracy: 87.1%
<Figure size 550x500 with 1 Axes>

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 1/(1−p)1/(1-p) 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.

Dropout: at each update a random share of the hidden neurons is switched off; at evaluation all are on (lecture 21b)

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.

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.

<Figure size 1000x380 with 2 Axes>
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.

Answer below (click to open it).

Notebook Cell
[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%
<Figure size 1300x380 with 3 Axes>
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/.

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.

We restore the checkpoint into a new model and evaluate both versions once on the test set.

<Figure size 650x350 with 1 Axes>
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).

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)

  1. 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.

  2. Fit the scaler on the training samples only, then apply it to the validation and test samples.

  3. Start from random weights drawn with a seed, and report the seed (42 here).

  4. Watch the training and validation loss at every epoch.

  5. Add dropout or batch normalization only when the two curves part.

  6. Keep the model with the lowest validation loss with a checkpoint, not the model of the last epoch.

  7. Evaluate once on the test set, with the accuracy and a confusion matrix.

  8. 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.