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.

4.2 Regression with a Neural Network

In 4.1 a network sorted seismic events into four classes. Here the same PyTorch loop predicts a number: where a GNSS (Global Navigation Satellite System) station will be, on average, over the next 30 days, in millimeters. Three things change from classification to regression: the last layer of the network gives one number and has no activation, the loss measures the distance between a prediction and an observation, and the evaluation reports that distance in physical units. The five steps are those of 4.1:

  1. Prepare the dataset: data samples of six inputs and one observation, split in time.

  2. Design the model: a fully connected network whose last layer is one neuron with no activation.

  3. Choose the loss function: mean squared error, mean absolute error, or Huber.

  4. Choose the optimizer: Adam, as in 4.1.

  5. Write the training loop, then evaluate in millimeters against two baselines.

🖥️ Lecture slides, Session 21 (Wed Nov 18): fully connected networks

Your turn cells. Three 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.

Accelerator available: cpu
Training on: cpu

0. GNSS station P395 and why it moves

Station P395 stands in the Oregon Coast Range, at 45.022°N, 123.858°W (coordinates from the Nevada Geodetic Laboratory, NGL, file llh.out). It belongs to the Network of the Americas (NOTA), operated by the EarthScope Consortium. A GNSS receiver measures its own position every day to a few millimeters. You downloaded its daily positions from NGL in 1.7; the file holds the east, north and up position relative to the first day, in meters.

P395 sits above the Cascadia subduction zone, where the Juan de Fuca plate goes beneath North America. Between large earthquakes, the plate interface offshore is locked, at least in part, and the upper plate is squeezed: relative to stable North America, stations near the coast move landward, to the northeast. Part of that motion is also attributed to a slow rotation of the Oregon forearc (McCaffrey et al., 2013). The positions in our file are in the global IGS20 frame (International GNSS Service, 2020 realization), which also contains the motion of the whole North American plate. In that frame, P395 moves west.

We use the east position only. It drifts west almost linearly for 20 years, with a seasonal oscillation on top. The cell below reads the file and fits a straight line to the east position, to measure that drift.

7,563 daily positions, from 2006.07 to 2026.87
east position: from -135.2 to 3.4 mm
mean east velocity, least-squares line through all days: -6.53 mm/yr (IGS20 frame)

NGL publishes its own velocity for P395, estimated with the MIDAS method (Median Interannual Difference Adjusted for Skewness; Blewitt et al., 2016), which resists offsets and outliers: −6.39 ± 0.19 mm/yr east in the IGS20 frame (file midas.IGS.txt, read on 2026-11-18). The straight line above agrees with it to within a few tenths of a millimeter per year. In 20 years the station has moved more than 13 centimeters west of where it started, and it keeps going. Remember this drift: it decides the fate of the network in section 6.

The map shows where P395 is; the right panel shows the whole east record.

<Figure size 1300x480 with 2 Axes>

1. The data samples

The question we ask the network: given the last 60 days of positions, where will the station be, on average, over the next 30 days? This is the forecast task of lecture 18 (script book/slides/2026/figscripts/lec18_scores_ensembles_automl.py).

One data sample is one forecast date tt. We take one date every 5 days. For each date:

NameWhat it isUnits
mean_60dmean east position over the 60 days before ttmm
mean_10dmean east position over the 10 days before ttmm
lastlast east position before ttmm
slope_60dslope of a straight line through the 60 days before tt (np.polyfit)mm/day
season_sin, season_cossin⁡(2π year)\sin(2\pi\,\text{year}) and cos⁡(2π year)\cos(2\pi\,\text{year}) at tt: the time of yearnone
observation yymean east position over the 30 days from tt onmm

The six inputs form a row of X; the observation is an entry of Y. “Days” here are daily positions: the record has a few short gaps, so a window of 60 positions can span a few more calendar days.

1,495 data samples; X has shape (1495, 6), Y has shape (1495,)
Loading...

One data sample, drawn on the record: the 60-day input window, the 30-day window whose mean is the observation, and the last position, which is the simplest forecast of all.

<Figure size 1000x400 with 1 Axes>

1.1 Split in time, with a gap

The network will be used to forecast the future from the past, so we split along time: the first 70% of the data samples for training, the next 15% for validation, the last 15% for test. Shuffling the samples before splitting would put validation dates between training dates, and the score would measure interpolation, not forecasting (lecture 18).

Neighboring samples share data. The observation of a sample covers the 30 days after its date, and samples are 5 days apart, so the next 6 samples (30 / 5) have observation windows that overlap it. We drop 6 samples at each boundary: no observation window of the validation set overlaps one of the training set, and the same between validation and test.

Loading...
<Figure size 1000x380 with 1 Axes>

1.2 Scale with the training samples only

As in 4.1, each input is standardized to zero mean and unit standard deviation. We also standardize the observation YY, so that the network predicts numbers of order 1 and the loss values are comparable between models. The means and standard deviations come from the training samples only; the validation and test samples are scaled with the same numbers. Predictions are converted back to millimeters before any evaluation.

training mean of Y: -45.0 mm, standard deviation: 27.1 mm

2. Baselines: without and with learning

A network is worth its weights only if it beats simpler forecasts. We report every score as the mean absolute error (MAE) in millimeters: the mean over the samples of |prediction − observation|.

Persistence learns nothing: the forecast for the next 30 days is the last observed position. For a station that drifts a fraction of a millimeter per week, it is hard to beat.

Your turn (1): the persistence forecast

Write yPersist, the persistence forecast of every data sample: the column last of the table samples, as a NumPy array.

Hint: samples["last"].to_numpy().

Answer below (click to open it).

Notebook Cell
persistence MAE: validation 1.26 mm, test 1.00 mm

Linear regression learns seven numbers: one weight per input and an intercept, fit on the training samples by least squares (Chapter 3).

weights on mean_60d, mean_10d, last: [0.31 0.51 0.17]  sum: 1.0
Loading...

The three weights on the positions add up to about 1: the linear regression learned “the forecast is a weighted mean of recent positions, plus small terms for the slope and the season”. That rule holds wherever the station is. Keep this in mind for section 6.

3. The model

The network is a multi-layer perceptron (MLP): two hidden layers of 32 neurons with ReLU activations, then a last layer of one neuron.

6 inputs -> Linear(6, 32) -> ReLU -> Linear(32, 32) -> ReLU -> Linear(32, 1) -> prediction (standardized)

The difference with 4.1 is the last layer. A classifier ends with one score per class, turned into probabilities by the softmax inside the loss. A regression network ends with one neuron and no activation: its prediction can be any real number, positive or negative. A ReLU there would forbid negative predictions, and a sigmoid would keep them between 0 and 1; the standardized positions we predict take both signs.

The last layer decides the task: one number with no activation for a regression, one score per class for a classification (lecture 21b)
MLP(
  (layers): Sequential(
    (0): Linear(in_features=6, out_features=32, bias=True)
    (1): ReLU()
    (2): Linear(in_features=32, out_features=32, bias=True)
    (3): ReLU()
    (4): Linear(in_features=32, out_features=1, bias=True)
  )
)
weights and biases: 1,313  (6x32 + 32 + 32x32 + 32 + 32x1 + 1)

As in 4.1, section 2.1, nn.Linear draws its starting weights at random, never zeros, so that the 32 neurons of a layer receive different gradients and learn different things. The seed (torch.manual_seed(0) just before creating the model) makes the draw the same at every run.

first-layer weights: 192, between -0.407 and 0.406, bound 1/sqrt(6) = 0.408; equal to zero: 0

4. Losses for regression

For sample ii, the error is the prediction minus the observation, ei=y^i−yie_i = \hat{y}_i - y_i. The loss of each sample is a function of that error, and training lowers the mean loss over the batch. Three common choices:

LossLoss of each sample Li\mathcal{L}_iPyTorchWhat it does to large errors
Mean squared error (MSE)ei2e_i^2nn.MSELoss()squares them: one error of 4 weighs as much as 16 errors of 1
Mean absolute error (MAE, also L1)∣ei∣\lvert e_i \rvertnn.L1Loss()counts them in proportion to their size
Huber, threshold δ\delta12ei2\frac{1}{2} e_i^2 if ∣ei∣≤δ\lvert e_i \rvert \le \delta, else δ(∣ei∣−δ2)\delta \left(\lvert e_i \rvert - \frac{\delta}{2}\right)nn.HuberLoss(delta=1.0)squares the small ones, counts the large ones in proportion

The gradient tells the same story. For MSE it is 2ei2 e_i: the larger the error, the harder that one sample pulls on the weights. For MAE it is ±1\pm 1: every sample pulls with the same strength, whatever the size of its error. Huber behaves like MSE below δ\delta and like MAE above.

Which one to choose depends on the errors you expect. If they follow a Gaussian distribution, MSE is the natural choice; minimizing it predicts the mean. If the data contain occasional large errors (outliers, offsets from an earthquake or an antenna change, heavy tails), MAE or Huber keep a few samples from steering the fit; minimizing MAE predicts the median. Because YY is standardized, δ=1\delta = 1 means one training standard deviation.

The loss of one sample against its error: squared, absolute, and Huber (lecture 21b)
<Figure size 600x400 with 1 Axes>

Below ∣e∣=1|e| = 1 (shaded) Huber is half the MSE, and both are below MAE: small errors weigh little. Beyond it, MSE climbs fastest. At an error of 3, MSE gives 9, MAE 3, and Huber 2.5.

5. Training

The training loop is the loop of 4.1. For each batch:

What happensPyTorch
gradients start from zerooptimizer.zero_grad()
predictions for the batchpred = model(xb)
loss of each sample, mean over the batchloss = criterion(pred, yb)
gradient of the loss for every weight (backpropagation)loss.backward()
update: w−α×w - \alpha \times gradient (Adam adapts α\alpha for each weight)optimizer.step()

The data samples go into a TensorDataset, which does what the custom Dataset class of 4.1 did, and a DataLoader cuts them into batches of 64, shuffled at each epoch with its own seeded random generator. With 1,037 training samples, one epoch is 17 updates. At the end of each epoch we record the mean loss on the training and validation samples, with gradients off.

The function below builds the model from a seed, trains it, and returns the model and its history. We use it for every network of this notebook.

The same loop as 4.1: one update per batch, one validation check per epoch (lecture 23)

First, the direct question: the network sees the six inputs and predicts the 30-day mean position itself. Loss MSE, Adam with learning rate 10-3, batches of 64, 300 epochs, seed 0.

trained in 3.4 s; final MSE (standardized): train 0.0006, validation 0.0025
  train_loss: root of the MSE = 0.67 mm
  val_loss: root of the MSE = 1.37 mm
<Figure size 700x400 with 1 Axes>

Both losses fall fast in the first 20 epochs and then flatten. After 300 epochs the mean MSE is 0.0007 on the training samples and 0.0029 on the validation samples, in standardized units: a typical error of 0.73 mm and 1.44 mm once converted back (printed above). The validation loss is four times the training loss, a first warning. Otherwise these curves look like a training that worked. Whether the network is useful is a question for the test samples, in millimeters.

6. Evaluation in physical units

A loss in standardized units does not tell a geodesist much. We convert the predictions back to millimeters and compute the MAE on the test samples, the last three years of the record, which played no part in training or in any choice so far.

Your turn (2): the test MAE of the network

yAbs holds the network’s predictions in mm for all samples. Write maeAbsTest, the mean absolute error on the test samples (indices test), with NumPy.

Hint: np.mean(np.abs(yAbs[test] - Y[test])).

Answer below (click to open it).

Notebook Cell
Loading...
mean error of the MLP on the test samples (prediction minus observation): +1.34 mm
<Figure size 1000x400 with 1 Axes>

The network follows the shape of the test series, its seasonal ups and downs, but it sits above the observations: its mean error is +1.56 mm (printed above). Its test MAE, 1.59 mm, is worse than persistence (1.02 mm) and two and a half times that of the linear regression (0.63 mm). On the validation samples it was already behind the linear regression (1.12 against 0.87 mm).

Why does a network with 1,313 weights fail where seven numbers succeed? Compare the range of the observations in each set.

Observation Y, 30-day mean east position:
Loading...
<Figure size 1000x380 with 1 Axes>

Every test observation, from −131.7 to −110.9 mm, lies west of the westernmost training observation, −93.7 mm; most validation observations do too. The station keeps moving west, so the future always lies outside the range of the past.

A ReLU network is made of straight pieces fitted where it saw data. Outside that region it continues its last pieces in straight lines whose slopes no training sample constrained, and its predictions drift away from the observations. The linear regression has a single form everywhere, “a weighted mean of recent positions” (its three position weights add up to 1.0, section 2), and that rule is as true at −130 mm as at −30 mm.

Is the failure bad luck with one seed? The cell below trains the same network with seeds 1 and 2.

seed 1: MLP predicting the position, test MAE 4.77 mm (persistence 1.00 mm)
seed 2: MLP predicting the position, test MAE 1.22 mm (persistence 1.00 mm)

Seed 0 gave 1.59 mm, seed 1 gives 4.60 mm, seed 2 gives 1.15 mm. All three are worse than persistence (1.02 mm), and they differ by a factor of four. That spread is itself a sign of extrapolation. Inside the training range, the data decide what the network learns, and different seeds land on nearly the same function (section 7.1 measures a spread of 0.01 mm). Outside it, nothing in the data decides, and each random start drifts its own way.

7. Predict the change instead of the position

The fix is to ask a question whose answer stays in the same range in 2010 and in 2026: how far will the station move from its last position? The new quantity to predict is the change Δy=y−last\Delta y = y - \text{last}. The inputs become relative too: mean_60d − last, mean_10d − last, slope_60d, and the two season terms. None of them depends on where the station has drifted. After training, the forecast of the position is last + predicted change, and we score it in mm against the same observations as before.

Your turn (3): the change to predict

Write dY, the change from the last position for every data sample, in mm. You have Y (observations) and yPersist (the last positions).

Hint: Y - yPersist.

Answer below (click to open it).

Notebook Cell
position Y: 219 of the 219 test samples lie outside the training range
change dY: 1 of the 219 test samples lie outside the training range
Change dY = y - last (mm):
Loading...

Measured as a change, the test samples fall almost entirely inside the training range. We scale the new inputs and the change with the training samples only, fit a linear regression on the change as a second baseline, and train the same MLP three times, once with each loss of section 4.

three networks trained in 7.9 s
Loading...
MSE: lowest validation loss at epoch 15
MAE: lowest validation loss at epoch 20
Huber: lowest validation loss at epoch 17
<Figure size 1300x360 with 3 Axes>

Three things to read here.

  • The training loss keeps falling for 300 epochs, but the validation loss is lowest after 13 to 19 epochs (printed above) and rises afterwards. The network learns details of the training years that do not repeat in the validation years: it overfits. Stopping at the lowest validation loss (early stopping, notebook 4.7) is the usual remedy. We keep 300 epochs so that every network of this notebook is trained the same way.

  • Predicting the change, every network scores between 0.69 and 0.72 mm on the test samples: better than persistence (1.02 mm) and far better than the network that predicted the position (1.59 mm).

  • None of them beats the linear regression (0.63 mm, on the position or on the change).

7.1 How much of the difference is the seed?

A score from one training run depends on the random starting weights and on the order of the batches. We pick the loss with the lowest validation MAE (the test samples must not choose the model), train that network with three seeds, and report the mean and standard deviation of the test MAE.

loss with the lowest validation MAE: Huber (0.921 mm)
seed 0: test MAE 0.748 mm
seed 1: test MAE 0.729 mm
seed 2: test MAE 0.757 mm
MLP (Huber loss, predicts the change), seeds [0, 1, 2]: test MAE 0.74 ± 0.01 mm
difference with linear regression: +0.12 mm, that is 9.7 seed standard deviations
Mean absolute error, mm. GNSS station P395 east, 30-day mean forecast from 60 days of positions.
Loading...
<Figure size 1000x400 with 1 Axes>

All numbers are MAE in mm on the 217 test samples (2023.60 to 2026.64) or the 216 validation samples (2020.55 to 2023.51), from the cells above.

  • Changing the question did what no choice of loss could: the network went from 1.59 mm (predicting the position) to 0.69 mm (predicting the change, MAE loss).

  • The loss mattered less. MAE beat MSE and Huber by 0.03 mm, on both validation and test.

  • Over three seeds, the best network scores 0.70 ± 0.01 mm. The linear regression is better by 0.07 mm, about 12 seed standard deviations. The gap is not seed noise.

On this problem we would use the linear regression. Its six inputs already summarize the past 60 days with means and a slope, and a weighted mean of recent positions captures what is predictable over 30 days; the 1,313 weights of the network found nothing more. Networks earn their weights when the inputs are raw (the 60 daily positions themselves, many stations at once) and the relations are not linear. That is where the rest of Chapter 4 goes.

8. Best practices for a fully connected network (regression)

What this notebook showed, as a checklist for your own regression problems:

  1. Name the data sample, X, Y and their units before writing a model. Here: one forecast date every 5 days; six numbers from the past 60 days; the 30-day mean east position in mm.

  2. Split along the axis the model will be used on, here time, and leave a gap as long as the overlap between neighboring samples (6 samples = 30-day horizon / 5-day spacing).

  3. Compute the baselines first: one without learning (persistence) and one with the simplest learning (linear regression). They set the score a network must beat.

  4. End a regression network with one neuron and no activation, so that the prediction can take any value.

  5. Choose the loss for the errors you expect: MSE for Gaussian errors, MAE or Huber when a few large errors (outliers, offsets) should not steer the fit.

  6. Scale inputs and observations with the training samples only, and convert predictions back to physical units before scoring.

  7. Check that the test observations lie inside the training range. A network does not extrapolate. If the quantity drifts, predict a change or an anomaly instead.

  8. Report the MAE in physical units and its spread over seeds. A network that does not beat the linear baseline by more than that spread is not the model to use.

9. Reflection

Answer in a few sentences each, in a markdown cell below.

  1. What did you learn? Which result surprised you the most, and why?

  2. What did you learn from working with AI agents, if you used them? Where did an agent help, and where did you have to check or correct it?

  3. How would you improve this notebook? Think of a clearer explanation, a missing figure, or another geoscience time series where the same lessons apply.