Loss functions, gradient descent and regularisation explained
Implement gradient descent on a 1D loss, plot train and validation curves, and show how regularisation changes them.
By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.
In short
Training a model means finding the weights that make a loss function as small as possible. Gradient descent does this by repeatedly measuring the slope of the loss and taking a small step downhill, with the learning rate controlling the step size. Regularisation adds a penalty for large weights, which trades a little training accuracy for better results on new data.
Think of it like this: Gradient descent is walking down a foggy hill: you cannot see the bottom, so you feel which way the ground slopes and take a careful step.
Explained simply
A model starts with random or zero weights and makes poor predictions. Training means adjusting the weights until predictions get better. To do that, we need one number that says how bad the predictions are. That number is the loss. Lower is better.
Imagine the loss as a landscape, with the weights as your position. Gradient descent looks at the slope where you stand and takes a small step downhill. It repeats this many times until the ground is nearly flat. The size of each step is the learning rate.
If steps are too small, training takes forever. If they are too big, you leap over the valley and may climb higher with each step. Picking a sensible learning rate is one of the first practical skills in ML.
A model can also fit its training data too well, memorising noise. Regularisation adds a small penalty for large weights so the model stays simpler. You check the effect by watching loss on a separate validation set, not just the training data.
Press Play on a diagram to walk through it one step at a time.
- 1Predict
Use the current weights.
- 2Measure loss
For example, mean squared error.
- 3Compute gradient
Slope of the loss for each weight.
- 4Step downhill
w = w - learning_rate x gradient.
- Back to step 1
- Tiny steps
- Loss falls very slowly
- Wastes compute
- May stop before converging
- Steady fall in loss
- Settles near the minimum
- Smooth training curve
- Overshoots the minimum
- Loss bounces or grows
- Can produce inf or nan values
- Training loss high
- Validation loss high
- Curves close together
- Fix: richer model or less penalty
- Training loss low
- Validation loss low
- Small, stable gap
- Keep this setting
- Training loss very low
- Validation loss rising
- Gap keeps widening
- Fix: more penalty, data or early stop
In depth
Loss functions turn errors into one number
For regression, mean squared error (MSE) averages the squared differences between predictions and true values. Squaring makes all errors positive and punishes big errors much more than small ones. Mean absolute error (MAE) averages the absolute differences and is less sensitive to outliers. For classification, log loss (cross-entropy) punishes confident wrong probabilities heavily: predicting 0.99 for the wrong class costs far more than predicting 0.6.
The loss you train on does not have to be the metric you report. Models often minimise log loss because it is smooth and has clean gradients, while the business reads recall or cost per decision. Choose the training loss for good optimisation, then judge the model with the success measure agreed earlier.
- MSE: mean of (prediction minus truth) squared
- MAE: mean of absolute errors, robust to outliers
- Log loss: for predicted probabilities
Deriving and following the gradient
The gradient is the derivative of the loss with respect to each weight. For one weight with loss (w - 3) squared, the derivative is 2(w - 3). At w = 0 it is -6: the loss falls as w rises, so the update w = w - lr x gradient moves w up towards 3.
For linear regression with MSE, the gradient for all weights at once is (2 / n) X.T @ (X @ w - y). Each step costs one pass over the data. Stochastic gradient descent (SGD) estimates the gradient from a small random batch instead, which is noisier but much cheaper per step and is how neural networks train. scikit-learn's SGDRegressor and SGDClassifier implement this for linear models.
- Step 1w = 0.0
Gradient -6, loss 9.0
- Step 2w = 0.6
Gradient -4.8, loss 5.76
- Step 3w = 1.08
Gradient -3.84, loss 3.69
- Step 4w = 1.464
Each step closes 20 percent of the gap to 3
Choosing a learning rate
On the loss (w - 3) squared, each update multiplies the distance to 3 by (1 - 2 x lr). With lr = 0.1 the distance shrinks by 20 percent per step. With lr = 0.5 you land on 3 in one step. With lr = 1.0 you bounce between two points forever, and with lr above 1.0 the distance grows each step and training diverges.
Real losses have many weights and curved valleys, so there is no exact formula. A practical method is to try values spaced by factors of 10, such as 0.001, 0.01 and 0.1, plot the training loss for each, and pick the largest that falls smoothly. Scaling the features first makes one learning rate suit all weights.
L1 and L2 regularisation
Regularisation adds a penalty to the loss. L2 (ridge) adds lambda times the sum of squared weights; its gradient pulls every weight towards zero in proportion to its size, so weights shrink but rarely reach zero. L1 (lasso) adds lambda times the sum of absolute weights; its constant pull can push small weights to exactly zero, which removes features. Elastic net mixes both.
Lambda sets the strength. In scikit-learn it is called alpha in Ridge, Lasso and SGD models, where larger alpha means a stronger penalty. LogisticRegression and SVMs use C instead, which is the inverse: smaller C means stronger regularisation. Too little penalty overfits; too much underfits, flattening the model so both training and validation loss stay high.
- L2: shrinks all weights smoothly
- L1: sets some weights to exactly zero
- alpha up means stronger penalty; C down means stronger penalty
Reading train and validation curves
Plot loss against training steps, or against model complexity, for both the training set and a held-out validation set. Three patterns matter. Both curves high and flat: underfitting, so the model is too simple or the learning rate is too low. Training loss falling while validation loss turns upwards: overfitting, so add regularisation, use more data or stop earlier. Both curves low and close: a healthy fit.
Regularisation changes the picture predictably. As the penalty grows, training loss rises a little, and validation loss first falls and then rises. The best penalty sits at the bottom of the validation curve. Choose it on validation data, never on the final test set.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Define a loss function~35m
- 2Derive and step along the gradient~35m
- 3Choose a learning rate~35m
- 4Add L1 and L2 regularisation~35m
- 5Plot train and validation loss~35m
Key points
- A loss function turns prediction errors into one number to minimise.
- The gradient points uphill, so each update subtracts it, scaled by the learning rate.
- L2 regularisation shrinks all weights; L1 can push some exactly to zero.
- Plot training and validation loss together: a widening gap means overfitting.
Key terms
Tap a card to flip it. 0/5 known
Examples
# Minimise loss(w) = (w - 3)^2; its gradient is 2 * (w - 3)
w, lr = 0.0, 0.1
for step in range(25):
grad = 2 * (w - 3)
w = w - lr * grad
if step % 5 == 0:
print(step, round(w, 4), round((w - 3) ** 2, 6))
print("final w:", round(w, 4)) # close to 3Try lr=1.1: each step overshoots further and the loss grows instead of falling.
Watching a learning rate diverge
Step 1: run gradient descent on (w - 3) squared for 6 steps with three learning rates. Step 2: print w after each run. Expected evidence: lr = 0.1 moves steadily towards 3, lr = 0.5 lands on 3 at the first step, and lr = 1.1 swings further away each step. This makes the learning-rate rule visible before you meet it in noisy real training.
def run(lr, steps=6, w=0.0):
path = []
for _ in range(steps):
w = w - lr * 2 * (w - 3)
path.append(round(w, 2))
return path
for lr in (0.1, 0.5, 1.1):
print(lr, run(lr))
# 1.1 gives values that swing around 3 with growing sizeRegularisation on a train and validation curve
Step 1: create a small noisy regression problem with many polynomial features, so overfitting is easy. Step 2: fit Ridge for alpha values from 0.0001 to 100. Step 3: record training and validation MSE. Expected evidence: training error rises steadily with alpha, while validation error dips and then rises. Plot both with matplotlib and pick the alpha at the validation minimum. The data is synthetic.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error as mse
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0)
x = rng.uniform(-3, 3, (60, 1)); y = np.sin(x).ravel() + rng.normal(0, 0.3, 60)
xa, xb, ya, yb = train_test_split(x, y, test_size=0.4, random_state=0)
for a in [1e-4, 1e-2, 1, 100]:
m = make_pipeline(PolynomialFeatures(12), StandardScaler(), Ridge(alpha=a)).fit(xa, ya)
print(a, round(mse(ya, m.predict(xa)), 3), round(mse(yb, m.predict(xb)), 3))Quick reference
- Update rule: w = w - learning_rate x gradient
- MSE punishes big errors; MAE is robust to outliers; log loss is for probabilities
- Try learning rates 10x apart (0.001, 0.01, 0.1) and keep the largest that falls smoothly
- Loss rising or nan during training usually means the learning rate is too high
- L2 shrinks weights; L1 zeroes some; Ridge and Lasso use alpha, LogisticRegression uses C
- Train loss down, validation loss up: overfitting
- Tune the penalty on validation data, never on the test set
Common mistakes
- Judging training only by training loss; it almost always keeps falling even while the model overfits.
- Using unscaled features with gradient descent, which makes some weights learn far faster than others.
- Mixing up scikit-learn's alpha (bigger means stronger penalty) with C in LogisticRegression (smaller means stronger).
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
By hand, do two gradient descent steps on loss (w + 2) squared starting at w = 0 with learning rate 0.25.
- Exercise 2medium
Implement gradient descent for linear regression with MSE in NumPy on synthetic data with true weights [2, -3], and check the result against np.linalg.lstsq.
- Exercise 3hard
Add an L2 penalty lam x sum(w squared) to your gradient descent from the medium exercise. Show how the learned weights and validation MSE change for lam in 0, 0.1 and 1.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a loss function and a metric?
- The loss is what the training algorithm minimises, chosen so it is smooth and easy to optimise. A metric is what you report and decide with, such as recall or MAE; they can differ.
- What learning rate should I start with?
- There is no universal value. Try a few spaced by factors of ten, plot the training loss, and choose the largest one where the loss falls smoothly.
- Does scikit-learn use gradient descent for every model?
- No. LinearRegression uses a direct least-squares solver, and LogisticRegression uses solvers such as lbfgs by default. SGDRegressor and SGDClassifier use stochastic gradient descent explicitly.