TExcelTAD

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, y^=fθ(x)\hat{y} = f_\theta(x) y^=wx+b\hat{y} = wx + b
Parameters θ\theta the adjustable numbers, learned from data ww and bb
Prediction y^\hat{y} the model's output for an input xx wx+bwx + b for a given xx
Loss L(θ)L(\theta) 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 ww, bb
Hyperparameters settings chosen before training, not learned by it the degree of the polynomial, the learning rate

The hat in y^\hat{y} marks a prediction; plain yy is the true value. For a straight line, the most common loss is the mean squared error over the nn training examples:

L(w,b)=1n∑i=1n(y^i−yi)2=1n∑i=1n(wxi+b−yi)2L(w, b) = \frac{1}{n} \sum_{i=1}^{n} \left( \hat{y}_i - y_i \right)^2 = \frac{1}{n} \sum_{i=1}^{n} \left( w x_i + b - y_i \right)^2

Squaring makes every error positive and punishes large errors more than small ones. Training then means solving

θ^=arg⁡min⁡θL(θ)\hat{\theta} = \arg\min_{\theta} L(\theta)

that is, finding the parameter values θ^\hat{\theta} 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.

python · try it yourself
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 (w=3w = 3, b=5b = 5).
  • The best fit is not the true line. Least squares finds w=2.882w = 2.882, b=5.394b = 5.394 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 dd has d+1d + 1 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.

python · try it yourself
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:

  1. choose a model family fθf_\theta (line, tree, neural network) and its hyperparameters;
  2. choose a loss that fits the task (squared error for numbers, cross-entropy for classes);
  3. run an optimiser that finds parameters with a small training loss;
  4. 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 yy and the noise level. Compare models on the same data.

Practice

  1. How many parameters does the model y^=w1x1+w2x2+w3x3+b\hat{y} = w_1 x_1 + w_2 x_2 + w_3 x_3 + b have? Which of these is a hyperparameter: the value of w2w_2, the number of features used, or the learning rate of the optimiser?
Answer

Four parameters: w1,w2,w3,bw_1, w_2, w_3, b. The value of w2w_2 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.

  1. Compute by hand the mean squared error of the model y^=2x\hat{y} = 2x on the three points (1,3)(1, 3), (2,4)(2, 4), (3,5)(3, 5).
Answer

Predictions 2, 4, 6; errors −1,0,1-1, 0, 1; squares 1, 0, 1. The mean is 23≈0.667\frac{2}{3} \approx 0.667.

  1. 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?

  1. The degree of a polynomial model
  2. The learning rate
  3. The weights ww and bias bb of a linear model
  4. The number of neighbours kk in kNN

Least squares found a line with training loss 3.885, lower than the true line's 4.02. Why?

  1. Least squares is wrong
  2. The best fit to 30 noisy points differs slightly from the line that generated them
  3. The true line was computed incorrectly
  4. Grid search was used

The degree-9 polynomial had train MSE 0.010 and test MSE 0.824. What is this called?

  1. Underfitting
  2. Overfitting
  3. Regularisation
  4. A good fit

What is the mean squared error of predictions [2,2][2, 2] for true values [1,3][1, 3]?

  1. 0
  2. 1
  3. 2
  4. 0.5