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:
Prepare the dataset: data samples of six inputs and one observation, split in time.
Design the model: a fully connected network whose last layer is one neuron with no activation.
Choose the loss function: mean squared error, mean absolute error, or Huber.
Choose the optimizer: Adam, as in 4.1.
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.
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
from torch.utils.data import TensorDataset, DataLoader
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
# Device-agnostic setup, as in 4.1: report the accelerator if there is one.
accelerator = torch.device("cuda" if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available()
else "cpu")
print("Accelerator available:", accelerator)
# The network of this notebook has about 1,300 weights and 1,037 training samples.
# Moving such small batches to a GPU costs more time than it saves, so we train on the CPU.
device = torch.device("cpu")
print("Training on:", device)
torch.manual_seed(0)
np.random.seed(0)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.
gnss = pd.read_csv("../Chapter1-GettingStarted/data/gps_P395_relative_position.csv")
year = gnss["decimal_year"].to_numpy()
east = gnss["east_m"].to_numpy() * 1000 # east position relative to the first day, in mm
velocity, intercept = np.polyfit(year, east, 1) # least-squares line over the whole record
print(f"{len(gnss):,} daily positions, from {year[0]:.2f} to {year[-1]:.2f}")
print(f"east position: from {east.min():.1f} to {east.max():.1f} mm")
print(f"mean east velocity, least-squares line through all days: {velocity:.2f} mm/yr (IGS20 frame)")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.
import geopandas as gpd
import pooch
pooch.get_logger().setLevel("WARNING")
# Basemap layers, the same pinned files as in 1.7.
land = gpd.read_file(pooch.retrieve(
"https://naciscdn.org/naturalearth/50m/physical/ne_50m_land.zip",
known_hash="sha256:0b8e670cf80dce9cbebe2a193bc44ba5602758c22e1fa603980553646d7ff162",
fname="ne_50m_land.zip"))
states = gpd.read_file(pooch.retrieve(
"https://naciscdn.org/naturalearth/50m/cultural/ne_50m_admin_1_states_provinces_lines.zip",
known_hash="sha256:464e762020d198257a07f5f62eb7cbfc287fccbc0a6db788d8068b49844d951e",
fname="ne_50m_admin_1_states_provinces_lines.zip"))
plates = gpd.read_file(pooch.retrieve( # PB2002 plate boundaries (Bird, 2003)
"https://raw.githubusercontent.com/fraxen/tectonicplates/"
"339b0c56563c118307b1f4542703047f5f698fae/GeoJSON/PB2002_boundaries.json",
known_hash="sha256:42b3e0876a7e40f133e958ba7ab85f8851b5c693a046fbc3b138e7751863d92a",
fname="PB2002_boundaries.json"))
lat395, lon395 = 45.022, -123.858 # NGL llh.out
fig, (axMap, axTs) = plt.subplots(1, 2, figsize=(13, 4.8), gridspec_kw={"width_ratios": [1, 2.4]})
axMap.set_facecolor("#eef3f8")
land.plot(ax=axMap, color="#f4efe6", edgecolor="0.5", lw=0.6)
states.plot(ax=axMap, color="0.55", lw=0.5, ls="--")
plates.plot(ax=axMap, color="k", lw=1.6)
axMap.plot(lon395, lat395, "^", ms=13, color="C0", mec="white", mew=1.5, zorder=5)
axMap.text(lon395 + 0.4, lat395 + 0.3, "P395", fontsize=12, fontweight="bold")
axMap.text(-129.6, 44.0, "Juan de Fuca\nplate", color="0.4", style="italic", fontsize=9)
axMap.text(-121.5, 47.6, "North America\nplate", color="0.4", style="italic", fontsize=9)
axMap.set_xlim(-130, -116)
axMap.set_ylim(40, 50)
axMap.set_aspect(1 / np.cos(np.deg2rad(45)))
axMap.set_xlabel("Longitude (°)")
axMap.set_ylabel("Latitude (°)")
axMap.set_title("Location")
axTs.plot(year, east, ".", ms=1.5, color="0.35", label="daily east position")
axTs.plot(year, intercept + velocity * year, color="C1", lw=2, label=f"straight line, {velocity:.2f} mm/yr")
axTs.set_xlabel("Year")
axTs.set_ylabel("East position (mm)")
axTs.set_title("GNSS station P395, Oregon Coast Range, NGL: east position, IGS20 frame")
axTs.legend()
fig.text(0.01, 0.0, "Positions and coordinates: NGL · plate boundaries: PB2002 (Bird, 2003) · land: Natural Earth",
fontsize=8, color="0.4")
fig.tight_layout(rect=(0, 0.03, 1, 1))
plt.show()
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 . We take one date every 5 days. For each date:
| Name | What it is | Units |
|---|---|---|
mean_60d | mean east position over the 60 days before | mm |
mean_10d | mean east position over the 10 days before | mm |
last | last east position before | mm |
slope_60d | slope of a straight line through the 60 days before (np.polyfit) | mm/day |
season_sin, season_cos | and at : the time of year | none |
| observation | mean east position over the 30 days from on | mm |
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.
HISTORY, HORIZON, STRIDE = 60, 30, 5 # days of input, days to forecast, days between samples
rows = []
for i in range(HISTORY, len(east) - HORIZON, STRIDE):
past = east[i - HISTORY:i]
rows.append({"year": year[i],
"mean_60d": past.mean(),
"mean_10d": east[i - 10:i].mean(),
"last": east[i - 1],
"slope_60d": np.polyfit(np.arange(HISTORY), past, 1)[0],
"season_sin": np.sin(2 * np.pi * year[i]),
"season_cos": np.cos(2 * np.pi * year[i]),
"y_mm": east[i:i + HORIZON].mean()})
samples = pd.DataFrame(rows)
FEATURES = ["mean_60d", "mean_10d", "last", "slope_60d", "season_sin", "season_cos"]
X = samples[FEATURES].to_numpy()
Y = samples["y_mm"].to_numpy()
print(f"{len(samples):,} data samples; X has shape {X.shape}, Y has shape {Y.shape}")
samples.head()1,495 data samples; X has shape (1495, 6), Y has shape (1495,)
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.
k = 1000 # one data sample, picked to be well inside the record
i = HISTORY + k * STRIDE # index of its forecast date t in the daily record
s = samples.iloc[k]
sel = slice(i - HISTORY - 40, i + HORIZON + 40)
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(year[sel], east[sel], ".", ms=4, color="0.6", label="daily east position")
ax.axvspan(year[i - HISTORY], year[i - 1], color="C0", alpha=0.15, label="60-day input window")
ax.axvspan(year[i], year[i + HORIZON - 1], color="C1", alpha=0.2, label="30-day window of the observation")
ax.hlines(s["mean_60d"], year[i - HISTORY], year[i - 1], color="C0", lw=2, label=f"mean_60d = {s['mean_60d']:.1f} mm")
ax.plot(year[i - 1], s["last"], "o", color="k", label=f"last = {s['last']:.1f} mm")
ax.hlines(s["y_mm"], year[i], year[i + HORIZON - 1], color="C1", lw=3, label=f"observation y = {s['y_mm']:.1f} mm")
ax.set_xlabel("Year")
ax.set_ylabel("East position (mm)")
ax.ticklabel_format(axis="x", useOffset=False)
ax.set_title(f"One data sample, forecast date {s['year']:.2f}. GNSS station P395, Oregon Coast Range, NGL")
ax.legend(fontsize=8, loc="lower left")
fig.tight_layout()
plt.show()
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.
n = len(samples)
GAP = HORIZON // STRIDE # 6 samples
i1, i2 = int(0.7 * n), int(0.85 * n)
train = np.arange(0, i1)
val = np.arange(i1 + GAP, i2)
test = np.arange(i2 + GAP, n)
split = pd.DataFrame({"samples": [len(train), len(val), len(test)],
"first date": [year_ for year_ in samples["year"].iloc[[train[0], val[0], test[0]]]],
"last date": [year_ for year_ in samples["year"].iloc[[train[-1], val[-1], test[-1]]]]},
index=["train", "validation", "test"]).round(2)
splitfig, ax = plt.subplots(figsize=(10, 3.8))
for idx, name, color in [(train, "train", "0.5"), (val, "validation", "C0"), (test, "test", "C3")]:
ax.plot(samples["year"].iloc[idx], Y[idx], ".", ms=4, color=color, label=f"{name}: {len(idx)} samples")
ax.set_xlabel("Forecast date (year)")
ax.set_ylabel("Observation y: 30-day mean east position (mm)")
ax.set_title("Train on the past, validate and test on the future. GNSS station P395, NGL")
ax.legend()
fig.tight_layout()
plt.show()
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 , 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.
xScaler = StandardScaler().fit(X[train])
yScaler = StandardScaler().fit(Y[train, None])
Xs = xScaler.transform(X).astype(np.float32)
Ys = yScaler.transform(Y[:, None]).astype(np.float32)
print(f"training mean of Y: {yScaler.mean_[0]:.1f} mm, standard deviation: {yScaler.scale_[0]:.1f} mm")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().
def mae(pred, obs):
# mean absolute error, in the units of the observations
return np.mean(np.abs(pred - obs))
yPersist = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
yPersist = samples["last"].to_numpy()print(f"persistence MAE: validation {mae(yPersist[val], Y[val]):.2f} mm, test {mae(yPersist[test], Y[test]):.2f} mm")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).
linear = LinearRegression().fit(Xs[train], Y[train])
yLinear = linear.predict(Xs)
# Weights in physical units: how many mm of forecast per mm of each position input.
wPhys = linear.coef_ / xScaler.scale_
print("weights on mean_60d, mean_10d, last:", wPhys[:3].round(2), " sum:", wPhys[:3].sum().round(3))
scores = pd.DataFrame({"validation MAE (mm)": [mae(yPersist[val], Y[val]), mae(yLinear[val], Y[val])],
"test MAE (mm)": [mae(yPersist[test], Y[test]), mae(yLinear[test], Y[test])]},
index=["persistence", "linear regression"]).round(2)
scoresweights on mean_60d, mean_10d, last: [0.31 0.51 0.17] sum: 1.0
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.

class MLP(nn.Module):
def __init__(self, n_inputs, n_hidden=32):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(n_inputs, n_hidden), nn.ReLU(),
nn.Linear(n_hidden, n_hidden), nn.ReLU(),
nn.Linear(n_hidden, 1)) # last layer: one number, no activation
def forward(self, x):
return self.layers(x)
torch.manual_seed(0) # seed of the random starting weights
model = MLP(n_inputs=X.shape[1]).to(device)
print(model)
n_weights = sum(p.numel() for p in model.parameters())
print(f"weights and biases: {n_weights:,} (6x32 + 32 + 32x32 + 32 + 32x1 + 1)")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.
W1 = model.layers[0].weight.detach().cpu().numpy()
print(f"first-layer weights: {W1.size}, between {W1.min():.3f} and {W1.max():.3f}, "
f"bound 1/sqrt(6) = {1 / np.sqrt(6):.3f}; equal to zero: {int((W1 == 0).sum())}")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 , the error is the prediction minus the observation, . The loss of each sample is a function of that error, and training lowers the mean loss over the batch. Three common choices:
| Loss | Loss of each sample | PyTorch | What it does to large errors |
|---|---|---|---|
| Mean squared error (MSE) | nn.MSELoss() | squares them: one error of 4 weighs as much as 16 errors of 1 | |
| Mean absolute error (MAE, also L1) | nn.L1Loss() | counts them in proportion to their size | |
| Huber, threshold | if , else | 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 : the larger the error, the harder that one sample pulls on the weights. For MAE it is : every sample pulls with the same strength, whatever the size of its error. Huber behaves like MSE below 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 is standardized, means one training standard deviation.

errors = torch.linspace(-3, 3, 301)
zeros = torch.zeros_like(errors)
fig, ax = plt.subplots(figsize=(6, 4))
for crit, label, color in [(nn.MSELoss(reduction="none"), "MSE: $e^2$", "C0"),
(nn.L1Loss(reduction="none"), "MAE: $|e|$", "C1"),
(nn.HuberLoss(delta=1.0, reduction="none"), r"Huber, $\delta = 1$", "C2")]:
ax.plot(errors, crit(errors, zeros), color=color, lw=2, label=label) # prediction = error, observation = 0
ax.axvspan(-1, 1, color="C2", alpha=0.08)
ax.set_ylim(0, 4)
ax.set_xlabel("Error of one sample, prediction minus observation (standardized units)")
ax.set_ylabel("Loss of the sample")
ax.set_title("Three losses for regression")
ax.legend()
fig.tight_layout()
plt.show()
Below (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 happens | PyTorch |
|---|---|
| gradients start from zero | optimizer.zero_grad() |
| predictions for the batch | pred = model(xb) |
| loss of each sample, mean over the batch | loss = criterion(pred, yb) |
| gradient of the loss for every weight (backpropagation) | loss.backward() |
| update: gradient (Adam adapts 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.

def train_model(Xs, Ys, criterion, seed=0, n_epochs=300, batch_size=64, learning_rate=1e-3):
torch.manual_seed(seed) # random starting weights, seeded
model = MLP(n_inputs=Xs.shape[1]).to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
xAll, yAll = torch.tensor(Xs).to(device), torch.tensor(Ys).to(device)
loader = DataLoader(TensorDataset(xAll[train], yAll[train]), batch_size=batch_size, shuffle=True,
generator=torch.Generator().manual_seed(seed)) # seeded shuffling
history = {"train_loss": [], "val_loss": []}
for epoch in range(n_epochs):
model.train()
for xb, yb in loader:
optimizer.zero_grad() # gradients start from zero
pred = model(xb) # predictions for the batch
loss = criterion(pred, yb) # mean loss over the batch
loss.backward() # gradient of every weight
optimizer.step() # update every weight
model.eval()
with torch.no_grad(): # no learning here: only measure
history["train_loss"].append(criterion(model(xAll[train]), yAll[train]).item())
history["val_loss"].append(criterion(model(xAll[val]), yAll[val]).item())
return model, history
def predict_mm(model, Xs, scaler):
# predictions for all samples, converted back from standardized units to mm
model.eval()
with torch.no_grad():
p = model(torch.tensor(Xs).to(device)).cpu().numpy()
return scaler.inverse_transform(p)[:, 0]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.
import time
t0 = time.time()
modelAbs, histAbs = train_model(Xs, Ys, nn.MSELoss(), seed=0)
print(f"trained in {time.time() - t0:.1f} s; final MSE (standardized): "
f"train {histAbs['train_loss'][-1]:.4f}, validation {histAbs['val_loss'][-1]:.4f}")
# square root of the MSE, times the training standard deviation of Y: a typical error in mm
for name in ("train_loss", "val_loss"):
print(f" {name}: root of the MSE = {np.sqrt(histAbs[name][-1]) * yScaler.scale_[0]:.2f} mm")
fig, ax = plt.subplots(figsize=(7, 4))
ax.semilogy(histAbs["train_loss"], color="tab:red", label="training samples")
ax.semilogy(histAbs["val_loss"], color="tab:red", ls="--", label="validation samples")
ax.set_xlabel("Epoch")
ax.set_ylabel("Mean MSE loss (standardized units)")
ax.set_title("Predicting the position: learning curves")
ax.legend()
fig.tight_layout()
plt.show()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

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])).
yAbs = predict_mm(modelAbs, Xs, yScaler)
maeAbsTest = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
maeAbsTest = np.mean(np.abs(yAbs[test] - Y[test]))scores.loc["MLP, predicts the position (MSE)"] = [round(mae(yAbs[val], Y[val]), 2), round(maeAbsTest, 2)]
scorestYear = samples["year"].to_numpy()
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(tYear[test], Y[test], "k.", ms=5, label="observation")
ax.plot(tYear[test], yPersist[test], color="0.6", label=f"persistence, MAE {mae(yPersist[test], Y[test]):.2f} mm")
ax.plot(tYear[test], yLinear[test], color="C0", label=f"linear regression, MAE {mae(yLinear[test], Y[test]):.2f} mm")
ax.plot(tYear[test], yAbs[test], color="C3", lw=2, label=f"MLP, predicts the position, MAE {maeAbsTest:.2f} mm")
ax.set_xlabel("Forecast date (year)")
ax.set_ylabel("30-day mean east position (mm)")
ax.set_title("Test samples: GNSS station P395, Oregon Coast Range, NGL")
print(f"mean error of the MLP on the test samples (prediction minus observation): {np.mean(yAbs[test] - Y[test]):+.2f} mm")
ax.legend(fontsize=9)
fig.tight_layout()
plt.show()mean error of the MLP on the test samples (prediction minus observation): +1.34 mm

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.
ranges = pd.DataFrame({"min (mm)": [Y[idx].min() for idx in (train, val, test)],
"max (mm)": [Y[idx].max() for idx in (train, val, test)]},
index=["train", "validation", "test"]).round(1)
print("Observation Y, 30-day mean east position:")
rangesObservation Y, 30-day mean east position:
fig, ax = plt.subplots(figsize=(10, 3.8))
ax.axhspan(Y[train].min(), Y[train].max(), color="0.85", label="range of the training observations")
for idx, name, color in [(train, "train", "0.5"), (val, "validation", "C0"), (test, "test", "C3")]:
ax.plot(tYear[idx], Y[idx], ".", ms=4, color=color, label=name)
ax.plot(tYear[test], yAbs[test], color="C3", lw=1.5, ls="--", label="MLP prediction, test")
ax.set_xlabel("Forecast date (year)")
ax.set_ylabel("30-day mean east position (mm)")
ax.set_title("The test observations lie outside the training range. GNSS station P395, NGL")
ax.legend(fontsize=8, loc="lower left")
fig.tight_layout()
plt.show()
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.
for seed in (1, 2):
m, _ = train_model(Xs, Ys, nn.MSELoss(), seed=seed)
p = predict_mm(m, Xs, yScaler)
print(f"seed {seed}: MLP predicting the position, test MAE {mae(p[test], Y[test]):.2f} mm "
f"(persistence {mae(yPersist[test], Y[test]):.2f} mm)")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 . 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.
lastPos = yPersist # last position before each forecast date, mm
Xc = np.column_stack([samples["mean_60d"] - lastPos, samples["mean_10d"] - lastPos,
samples["slope_60d"], samples["season_sin"], samples["season_cos"]])
dY = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
dY = Y - yPersistfor name, q in [("position Y", Y), ("change dY", dY)]:
outside = int(np.sum((q[test] < q[train].min()) | (q[test] > q[train].max())))
print(f"{name}: {outside} of the {len(test)} test samples lie outside the training range")
print("Change dY = y - last (mm):")
pd.DataFrame({"min (mm)": [dY[idx].min() for idx in (train, val, test)],
"max (mm)": [dY[idx].max() for idx in (train, val, test)]},
index=["train", "validation", "test"]).round(1)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):
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.
xcScaler = StandardScaler().fit(Xc[train])
dyScaler = StandardScaler().fit(dY[train, None])
Xcs = xcScaler.transform(Xc).astype(np.float32)
dYs = dyScaler.transform(dY[:, None]).astype(np.float32)
linearChange = LinearRegression().fit(Xcs[train], dY[train])
yLinearChange = lastPos + linearChange.predict(Xcs)
scores.loc["linear regression, predicts the change"] = [round(mae(yLinearChange[val], Y[val]), 2),
round(mae(yLinearChange[test], Y[test]), 2)]
losses = {"MSE": nn.MSELoss(), "MAE": nn.L1Loss(), "Huber": nn.HuberLoss(delta=1.0)}
yChange, histChange = {}, {}
t0 = time.time()
for name, crit in losses.items():
m, h = train_model(Xcs, dYs, crit, seed=0)
yChange[name] = lastPos + predict_mm(m, Xcs, dyScaler) # forecast of the position, mm
histChange[name] = h
scores.loc[f"MLP, predicts the change ({name})"] = [round(mae(yChange[name][val], Y[val]), 2),
round(mae(yChange[name][test], Y[test]), 2)]
print(f"three networks trained in {time.time() - t0:.1f} s")
scoresthree networks trained in 7.9 s
fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
for ax, (name, h) in zip(axes, histChange.items()):
ax.semilogy(h["train_loss"], color="tab:red", label="training samples")
ax.semilogy(h["val_loss"], color="tab:red", ls="--", label="validation samples")
ax.set_xlabel("Epoch")
ax.set_ylabel(f"Mean {name} loss (standardized)")
ax.set_title(f"Predicting the change, {name} loss")
print(f"{name}: lowest validation loss at epoch {int(np.argmin(h['val_loss'])) + 1}")
axes[0].legend()
fig.tight_layout()
plt.show()MSE: lowest validation loss at epoch 15
MAE: lowest validation loss at epoch 20
Huber: lowest validation loss at epoch 17

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.
valMAE = {name: mae(yChange[name][val], Y[val]) for name in losses}
best = min(valMAE, key=valMAE.get)
print(f"loss with the lowest validation MAE: {best} ({valMAE[best]:.3f} mm)")
seeds = [0, 1, 2]
seedTest = []
for seed in seeds:
m, _ = train_model(Xcs, dYs, losses[best], seed=seed)
pred = lastPos + predict_mm(m, Xcs, dyScaler)
seedTest.append(mae(pred[test], Y[test]))
print(f"seed {seed}: test MAE {seedTest[-1]:.3f} mm")
seedMean, seedStd = np.mean(seedTest), np.std(seedTest)
gapLinear = seedMean - mae(yLinear[test], Y[test])
print(f"MLP ({best} loss, predicts the change), seeds {seeds}: test MAE {seedMean:.2f} ± {seedStd:.2f} mm")
print(f"difference with linear regression: {gapLinear:+.2f} mm, that is {abs(gapLinear) / seedStd:.1f} seed standard deviations")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
final = scores.copy()
final.loc[f"MLP, predicts the change ({best}), seeds 0-2: mean"] = [np.nan, round(seedMean, 2)]
final.loc[f"MLP, predicts the change ({best}), seeds 0-2: std"] = [np.nan, round(seedStd, 2)]
print("Mean absolute error, mm. GNSS station P395 east, 30-day mean forecast from 60 days of positions.")
finalMean absolute error, mm. GNSS station P395 east, 30-day mean forecast from 60 days of positions.
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(tYear[test], Y[test], "k.", ms=5, label="observation")
ax.plot(tYear[test], yPersist[test], color="0.6", label=f"persistence, MAE {mae(yPersist[test], Y[test]):.2f} mm")
ax.plot(tYear[test], yLinear[test], color="C0", label=f"linear regression, MAE {mae(yLinear[test], Y[test]):.2f} mm")
ax.plot(tYear[test], yChange[best][test], color="C2", lw=2,
label=f"MLP, predicts the change ({best}), MAE {mae(yChange[best][test], Y[test]):.2f} mm")
ax.set_xlabel("Forecast date (year)")
ax.set_ylabel("30-day mean east position (mm)")
ax.set_title("Test samples after the change of question. GNSS station P395, NGL")
ax.legend(fontsize=9)
fig.tight_layout()
plt.show()
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:
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.
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).
Compute the baselines first: one without learning (persistence) and one with the simplest learning (linear regression). They set the score a network must beat.
End a regression network with one neuron and no activation, so that the prediction can take any value.
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.
Scale inputs and observations with the training samples only, and convert predictions back to physical units before scoring.
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.
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.
What did you learn? Which result surprised you the most, and why?
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?
How would you improve this notebook? Think of a clearer explanation, a missing figure, or another geoscience time series where the same lessons apply.