Regression, L1 loss and Adam
Fitting a straight line in PyTorch, and why the parameters never quite settle.
- Set up a train/test split, a model, a loss and an optimizer in PyTorch
- Explain why the L1 loss and a fixed step size keep circling the minimum
- Separate training on a range of inputs from extrapolating beyond it
The smallest complete PyTorch project: learn \(y = 0.7x + 0.3\) from 50 points. __main__.py builds the data, splits it, and trains a single nn.Linear(1, 1) with the L1 loss and Adam:
X = t.arange(0, 1, 0.02).unsqueeze(dim=1) # 50 x 1
y = weights * X + bias
train_split = int(0.8 * len(X))
X_train, y_train = X[:train_split], y[:train_split]
X_test, y_test = X[train_split:], y[train_split:]
loss_fn = nn.L1Loss()
optimizer = t.optim.Adam(params=model_1.parameters(), lr=5e-2)
Note what the split means: the first 40 points (\(x < 0.8\)) train, the last 10 (\(x \ge 0.8\)) test. Testing here measures extrapolation — the model has never seen an \(x\) as large as those it is graded on. For a straight line that is harmless; for anything curved, a random split is the fairer test.
A minimum with a crease
The data are noise-free, so the loss can reach zero. It never quite does, because of how the L1 loss and Adam interact. The gradient of \(\lvert e \rvert\) is \(\pm 1\): it does not shrink as the error does. Adam normalises the step by the gradient’s own running size, so near the optimum it keeps taking steps of roughly the learning rate, hopping back and forth across the crease at the bottom of the loss.
A NumPy re-run of the same updates, starting from \(w = 0.76\), \(b = 0.83\), shows the effect over the script’s 1,000 epochs:
Over the last 100 epochs the test loss averages 0.0051 at lr = 0.05 and 0.0009 at lr = 0.005. A learning-rate schedule — large first, small later — gets both benefits; with MSE instead of L1, the gradient itself shrinks near the optimum and the jitter disappears.
Training and evaluation modes
The loop switches between model.train() and model.eval() and evaluates under t.inference_mode(). For a single linear layer the mode makes no difference, but the habit matters: dropout and batch normalisation behave differently in the two modes (lesson 5), and inference_mode skips the bookkeeping autograd would otherwise do.
Try it yourself. Add t.optim.lr_scheduler.StepLR(optimizer, step_size=300, gamma=0.1) and call scheduler.step() once per epoch. Print the learned weight and bias: how close do they get compared with the fixed learning rate? Then swap nn.L1Loss for nn.MSELoss without a scheduler and compare.