MLDay 32 of 50Deep Learning
The Training Loop
A network with about 5,000 weights and a table of 10,000 rows won't train itself.
A network with about 5,000 weights and a table of 10,000 rows won't train itself. Someone has to feed it the rows, measure the miss, and nudge the weights, thousands of times. In PyTorch that someone is a loop of five lines, and every model you train uses the same five.
The idea
Training repeats one step over and over. Each step takes a batch, a small group of rows, and does five things:
- Forward: run the batch through the model to get predictions.
- Loss: score the predictions against the true values.
- Backward: call
.backward()to fill in every weight's gradient, as in D31. - Step: move every weight a little downhill.
- Zero: clear the gradients, so the next batch starts fresh.
One pass over every training row is an epoch. Small batches give many cheap, slightly noisy steps per epoch. One giant batch gives one careful step.
After each epoch, a separate evaluation pass scores rows the model never trains on, the validation set. Nothing is updated in it. Comparing the two losses, epoch by epoch, shows whether the model is learning something that carries over to new rows.
A tiny example
Fit , starting from , with learning rate . One batch holds two rows: and .
| Step | Calculation | Result |
|---|---|---|
| 1 forward | for both rows | 0 and 0 |
| 2 loss | mean squared error: | 17 |
| 3 backward | ; | −13 and −8 |
| 4 step | ; | 0.13 and 0.08 |
| 5 zero | set both gradients back to 0 | 0 and 0 |
The new predictions are 0.21 and 0.34, and the loss falls from 17 to 14.75. The next batch repeats the five steps from there.
The formula
The number of steps in one epoch depends on the number of rows and the batch size:
| Symbol | Meaning |
|---|---|
| the number of training rows | |
| the batch size: rows per step | |
| round up: a smaller last batch still gets its own step |
Worked: and give , rounded up to 16 steps. The last batch holds the 40 rows left over.
Try it
Train it batch by batch
Training starts at w = 0, b = 0. Every epoch shuffles the 10 points and takes one step per batch. Change the batch size and the learning rate η and watch the loss curve.
Dashed vertical lines mark the end of each epoch.
steps per epoch ⌈10 / 10⌉ = 15 epochs = 5 stepsfinal ŷ = 0.895·x + 0.266final L 16.951
The widget fits a line to ten points near . It starts with batch size 10, so each epoch is one step, and 5 epochs only bring the loss from 50.8 to 17.0. Drop the batch size to 2: the same 5 epochs now take 25 steps, and the loss ends near 0.27. Then try batch size 1 with learning rate 0.05, and watch the curve jump around instead of falling smoothly.
In code
The real task is Day 8's: predict hourly bike rentals from 12 columns, using
Day 6's time split.
The newest 20% of the training rows become the validation set. A TensorDataset pairs each row with its
target, and a DataLoader shuffles the rows and serves them in batches.
# script_id: day_032_training_loop/bike_mlp
import os
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import torch
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
features = ["season", "yr", "mnth", "hr", "holiday", "weekday", "workingday",
"weathersit", "temp", "atemp", "hum", "windspeed"]
train, test = train_test_split(df, test_size=0.25, shuffle=False) # Day 6's time split
fit, val = train_test_split(train, test_size=0.2, shuffle=False) # newest 20% of training: validation
scaler = StandardScaler().fit(fit[features]) # learned from training rows only
def tensors(part: pd.DataFrame) -> tuple[torch.Tensor, torch.Tensor]:
X = torch.tensor(scaler.transform(part[features]), dtype=torch.float32)
y = torch.tensor(part["cnt"].to_numpy() / 100, dtype=torch.float32) # hundreds of rentals
return X, y.unsqueeze(1) # y as a column: shape (n, 1)
X_fit, y_fit = tensors(fit)
X_val, y_val = tensors(val)
X_test, y_test = tensors(test)
loader = DataLoader(TensorDataset(X_fit, y_fit), batch_size=64, shuffle=True,
generator=torch.Generator().manual_seed(42))
print(f"{len(X_fit):,} training rows, {len(X_val):,} validation rows, {len(loader)} batches per epoch")
10,427 training rows, 2,607 validation rows, 163 batches per epoch
That's . The target is in hundreds of rentals, so it sits near 1, like the scaled features; the network learns faster that way.
The model is an nn.Sequential, a ready-made nn.Module (PyTorch's base class for anything with weights)
that applies its layers in order: two hidden layers of 64 ReLU units. The optimizer,
Adam, does the step; it's gradient descent that adapts each weight's step size
(D34).
# script_id: day_032_training_loop/bike_mlp
def make_mlp() -> nn.Sequential:
return nn.Sequential(nn.Linear(12, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1))
torch.manual_seed(42) # the same starting weights on every run
model = make_mlp()
loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
history = []
for epoch in range(1, 31):
model.train()
total = 0.0
for xb, yb in loader: # one step per batch
loss = loss_fn(model(xb), yb) # 1 forward, 2 loss
loss.backward() # 3 backward: fill every .grad
optimizer.step() # 4 step: update every weight
optimizer.zero_grad() # 5 zero, ready for the next batch
total += loss.item() * len(xb)
model.eval()
with torch.no_grad(): # evaluate: no gradients, no updates
val_loss = loss_fn(model(X_val), y_val).item()
history.append((total / len(X_fit), val_loss))
if epoch in (1, 5, 10, 20, 30):
train_rmse, val_rmse = (100 * mse**0.5 for mse in history[-1])
print(f"epoch {epoch:2d}: train RMSE {train_rmse:5.1f}, validation RMSE {val_rmse:5.1f}")
epoch 1: train RMSE 121.1, validation RMSE 179.6
epoch 5: train RMSE 82.4, validation RMSE 150.9
epoch 10: train RMSE 66.7, validation RMSE 134.2
epoch 20: train RMSE 45.6, validation RMSE 116.1
epoch 30: train RMSE 38.0, validation RMSE 99.5
model.eval() switches off layers that behave differently in training, such as dropout
(D36). This model has none, but the habit
prevents a silent bug, and model.train() switches them back on for the next epoch. torch.no_grad() skips the gradient bookkeeping, which evaluation doesn't need.
Last, score the test hours once, and save the weights. A state_dict maps each layer's name to its weights.
# script_id: day_032_training_loop/bike_mlp
with torch.no_grad():
test_rmse = 100 * loss_fn(model(X_test), y_test).item() ** 0.5
print(f"test RMSE: {test_rmse:.1f} (Day 8's linear model: 183.5; Day 14's one-hot hours: 136.5)")
torch.save(model.state_dict(), "bike_mlp.pt") # the learned weights, by layer name
copy = make_mlp()
copy.load_state_dict(torch.load("bike_mlp.pt"))
copy.eval()
with torch.no_grad():
print("reloaded copy gives the same predictions:", torch.equal(copy(X_test), model(X_test)))
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
epochs = range(1, len(history) + 1)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(epochs, [100 * t**0.5 for t, _ in history], color="#2a78d6", lw=2, label="training")
ax.plot(epochs, [100 * v**0.5 for _, v in history], color="#eb6834", lw=2, label="validation")
ax.set(title="Validation error falls too, but stays far above training",
xlabel="Epoch", ylabel="RMSE (rentals per hour)")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(FIG_DIR / "loss_curves.png", dpi=120)
plt.close(fig)
test RMSE: 125.7 (Day 8's linear model: 183.5; Day 14's one-hot hours: 136.5)
reloaded copy gives the same predictions: True

The network beats both linear models, with the hour still a plain number: its ReLU layers can bend where one weight couldn't. The gap is large partly because the validation hours, mid-March to early July 2012, average 260 rentals against 145 in training. A validation curve that turns upward is the signal to stop training early (D25).
Quick check
Quick check
1. A training set has 2,000 rows and the batch size is 64. How many steps is one epoch?
2. What does the evaluation pass with model.eval() and torch.no_grad() change?
3. In the widget, at learning rate 0.005, batch size 10 and batch size 2 both run 5 epochs. Why does batch size 2 get much further?
Next
The loss here was MSE, for a number; D33: Losses, Logits and Softmax matches the output layer and the loss to a classification task.
Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.