Models, Parameters and Loss
Every machine-learning method, from a straight line to a large language model, is built from the same four ingredients: a model with parameters, a loss that measures how wrong it is, an optimiser that lowers the loss, and hyperparameters that we choose. This lesson names them precisely, because the rest of the track uses these words constantly.
The vocabulary
| Term | Meaning | In a straight-line model |
|---|---|---|
| Model (model family) | a function with adjustable numbers, | |
| Parameters | the adjustable numbers, learned from data | and |
| Prediction | the model's output for an input | for a given |
| Loss | one number that says how wrong the predictions are on the training data | mean squared error |
| Training (fitting) | searching for the parameters with the smallest loss | finding the best , |
| Hyperparameters | settings chosen before training, not learned by it | the degree of the polynomial, the learning rate |
The hat in marks a prediction; plain is the true value. For a straight line, the most common loss is the mean squared error over the training examples:
Squaring makes every error positive and punishes large errors more than small ones. Training then means solving
that is, finding the parameter values at which the loss is smallest.
Fitting a line by searching, from scratch
The example generates 30 points around a line, then measures the loss of three guesses, searches a grid of 121 by 401 grid of parameter pairs for the best one, and finally solves the problem exactly with least squares.
import numpy as np
rng = np.random.default_rng(3)
x = rng.uniform(0, 10, size=30)
y = 3.0 * x + 5 + rng.normal(0, 2, size=30) # data from a line we pretend not to know
def predict(w, b, x): # the model family: straight lines f(x) = w*x + b
return w * x + b
def mse(w, b): # the loss: mean squared error on the training data
return np.mean((predict(w, b, x) - y) ** 2)
for w, b in [(0, 0), (1, 10), (3, 5)]:
print(f"w={w}, b={b:>2}: loss {mse(w, b):8.2f}")
# Fitting = searching the parameters (w, b) for the smallest loss.
grid_w = np.arange(0, 6.01, 0.05)
grid_b = np.arange(-5, 15.01, 0.05)
losses = np.array([[mse(w, b) for b in grid_b] for w in grid_w])
i, j = np.unravel_index(np.argmin(losses), losses.shape)
print("grid search: w =", round(grid_w[i], 2), " b =", round(grid_b[j], 2), " loss", round(losses[i, j], 3))
# Least squares finds the exact minimum in one step.
A = np.column_stack([x, np.ones_like(x)])
(w_best, b_best), *_ = np.linalg.lstsq(A, y, rcond=None)
print("least squares: w =", round(w_best, 3), " b =", round(b_best, 3), " loss", round(mse(w_best, b_best), 3))w=0, b= 0: loss 433.78
w=1, b=10: loss 50.11
w=3, b= 5: loss 4.02
grid search: w = 2.9 b = 5.3 loss 3.887
least squares: w = 2.882 b = 5.394 loss 3.885
Reading the output:
- The loss falls from 433.78 for a flat line through zero to 4.02 for the true line (, ).
- The best fit is not the true line. Least squares finds , with loss 3.885, slightly lower than the true line's 4.02. With noisy data, the line that fits these 30 points best differs a little from the line that generated them. The loss only knows the training data.
- Grid search gets close (loss 3.887) but needs 48,521 loss evaluations and is limited by the grid spacing. With two parameters that is affordable; with a million parameters, as in a neural network, a grid is impossible. Real optimisers follow the slope of the loss instead: that is gradient descent, shown in the training vs inference lesson.
The least-squares solution has a closed form derived from linear algebra; the Linear Regression lesson of math-ml shows where it comes from.
Parameters versus hyperparameters, and generalisation
A polynomial of degree has parameters (its coefficients), and these are learned. The degree itself is a hyperparameter: the fit cannot choose it, because a higher degree always fits the training data at least as well. The next example fits 15 noisy points from a sine curve with degrees 1, 3 and 9 and measures the error on the training points and on 200 new points.
import numpy as np
rng = np.random.default_rng(0)
def make(n):
x = rng.uniform(0, 1, size=n)
return x, np.sin(2 * np.pi * x) + rng.normal(0, 0.2, size=n)
x_train, y_train = make(15)
x_test, y_test = make(200)
# The degree is a hyperparameter: chosen by us, not learned by the fit.
for degree in [1, 3, 9]:
coefs = np.polyfit(x_train, y_train, degree) # the parameters, learned
train = np.mean((np.polyval(coefs, x_train) - y_train) ** 2)
test = np.mean((np.polyval(coefs, x_test) - y_test) ** 2)
print(f"degree {degree}: {degree + 1:>2} parameters, train MSE {train:.3f}, test MSE {test:.3f}")degree 1: 2 parameters, train MSE 0.147, test MSE 0.379
degree 3: 4 parameters, train MSE 0.017, test MSE 0.050
degree 9: 10 parameters, train MSE 0.010, test MSE 0.824
| Degree | What happened | Name |
|---|---|---|
| 1 | a line cannot follow a sine wave: both errors are high | underfitting |
| 3 | a cubic follows the wave: both errors are low | a good fit |
| 9 | the lowest training error (0.010) but the worst test error (0.824): the curve wiggles through the noise | overfitting |
The ability to do well on new data is called generalisation, and it is what we want. Hyperparameters such as the degree are therefore chosen by looking at data that was not used for fitting, a validation set. The Training, Evaluation & Improvement course treats this in depth, and the Machine Learning course's overfitting lesson has a hands-on version.
The general recipe
Every supervised method in this track can be read as:
- choose a model family (line, tree, neural network) and its hyperparameters;
- choose a loss that fits the task (squared error for numbers, cross-entropy for classes);
- run an optimiser that finds parameters with a small training loss;
- evaluate on data the model has not seen, and go back to step 1 if needed.
In math terms, step 3 minimises the average loss over the training examples, called the empirical risk. The Empirical Risk lesson of math-ml gives the formal version.
Pitfalls
- Confusing parameters and hyperparameters. If a value is chosen by
fit, it is a parameter. If you set it in the constructor, it is a hyperparameter. - Choosing hyperparameters by training loss. The most flexible setting always wins on training data and usually loses on new data.
- Comparing losses across data sets. A loss of 4 means nothing on its own: it depends on the units of and the noise level. Compare models on the same data.
Practice
- How many parameters does the model have? Which of these is a hyperparameter: the value of , the number of features used, or the learning rate of the optimiser?
Answer
Four parameters: . The value of is a parameter (learned). The learning rate is a hyperparameter. The choice of features is also a design decision made before training, so it acts like a hyperparameter.
- Compute by hand the mean squared error of the model on the three points , , .
Answer
Predictions 2, 4, 6; errors ; squares 1, 0, 1. The mean is .
- In the polynomial example, why can a degree-9 polynomial reach a lower training error than a cubic, whatever the data?
Answer
Every cubic is also a degree-9 polynomial (with the top six coefficients set to zero). The degree-9 fit searches a larger family that contains all cubics, so its best training loss can only be equal or lower.
Test yourself
Which of these is learned during training?
- The degree of a polynomial model
- The learning rate
- The weights and bias of a linear model
- The number of neighbours in kNN
Least squares found a line with training loss 3.885, lower than the true line's 4.02. Why?
- Least squares is wrong
- The best fit to 30 noisy points differs slightly from the line that generated them
- The true line was computed incorrectly
- Grid search was used
The degree-9 polynomial had train MSE 0.010 and test MSE 0.824. What is this called?
- Underfitting
- Overfitting
- Regularisation
- A good fit
What is the mean squared error of predictions for true values ?
- 0
- 1
- 2
- 0.5