Sub topic 2
Model capacity: how flexible a model is
This chapter assumes you know basic Python and NumPy, what features, labels, and a loss function are, how linear regression fits parameters by minimising a loss, and how scikit-learn's fit and predict work. It introduces model capacity, the idea behind both underfitting and overfitting. Later chapters build on it.
What capacity means
Model capacity is the range of patterns a model can represent. A model with low capacity can only draw simple shapes. A model with high capacity can draw very wiggly shapes, including ones that pass through every training point.
Capacity belongs to a model family together with its settings. A straight line has less capacity than a degree-4 polynomial. A degree-4 polynomial has less capacity than a degree-15 polynomial. In each case the larger family contains the smaller one, because a degree-15 polynomial can set its higher-order coefficients to zero and act like a line.
Capacity describes what a model could fit, not what it did fit. A high-capacity model fitted with a strong penalty may behave like a simple one. Later chapters cover that effect.
Where capacity comes from
Capacity is not a single dial. Several choices change it, and the effect differs by model type.
| Model type | Settings that raise capacity | Settings that lower capacity |
|---|---|---|
| Linear or polynomial regression | More features, higher polynomial degree, interaction terms | Fewer features, lower degree |
| Decision tree | Greater `max_depth`, smaller `min_samples_leaf` | Shallower depth, larger leaves |
| k-nearest neighbours | Smaller k | Larger k |
| Neural network | More layers, more units per layer | Fewer layers, fewer units |
| Any penalised model | Weaker penalty | Stronger penalty |
The last row matters for this tutorial. Regularisation lowers effective capacity without changing the model family.
A count of parameters is a rough guide only. A model with more parameters than training examples can still generalise well if training stops early or a penalty is applied. A model with few parameters can still overfit if each parameter is very flexible, as with a high-frequency sine term.
Capacity and the data you have
Whether a given capacity is too much depends on how much data you have and how noisy it is. Forty points with noise can pin down a gentle curve. They cannot pin down fifteen polynomial coefficients. With the same model and 40,000 points, the extra capacity would cause much less harm.
So "this model is too complex" is always a claim relative to the dataset. This is why you judge capacity by error on data the model did not train on, not by inspecting the model.
How training error and capacity relate
Training error is the loss measured on the data the model was fitted to. When one model family contains another, the larger family can always fit the training data at least as well as the smaller one, so training error never rises as capacity grows. In practice, tools like gradient descent may not find the best fit, but the trend holds.
Validation error behaves differently. It usually falls at first, as the model gains the ability to capture the real pattern. Then it flattens and often rises, because the extra flexibility is used to fit noise in the training set.
The gap between the two errors is a useful signal. A small gap with both errors high suggests too little capacity. A large gap suggests too much capacity for the data. Later chapters name these cases underfitting and overfitting.
Experiment: polynomial degree as a capacity dial
The polynomial degree is the easiest capacity setting to vary. The code below fits noisy sine data with degrees 1, 4, and 15. It holds out 30% of the points to measure validation error.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(40, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=40)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=0)
for degree in (1, 4, 15):
model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
model.fit(X_train, y_train)
train_mse = mean_squared_error(y_train, model.predict(X_train))
val_mse = mean_squared_error(y_val, model.predict(X_val))
print(degree, round(train_mse, 3), round(val_mse, 3))Each line prints the degree, the training mean squared error (MSE), and the validation MSE. Run it yourself and look for these patterns.
- Degree 1 is a straight line. It cannot follow the sine wave, so both errors are high and close to each other.
- Degree 4 can follow one full cycle of the wave. Both errors should be much lower, and near the noise level.
- Degree 15 has the lowest training error of the three. Its validation error is usually worse than degree 4, because the curve bends to follow noise in 28 training points.
Exact numbers depend on the random seed and the split, so do not expect a specific value. Check the pattern, not the digits.
The StandardScaler in the pipeline is there because polynomial features have very different scales. A degree-15 term of a value near 3 is enormous. Scaling keeps the fit numerically stable. Chapters on penalised models explain why it matters even more there.
Common mistakes
- Treating low training error as success. Higher capacity always helps training error. Only held-out error tells you whether the capacity was useful.
- Choosing capacity on the test set. If you try many degrees and keep the one with the best test score, the test score is no longer an honest estimate. Use a validation set or cross-validation to choose, and keep the test set for the end.
- Counting parameters as capacity. Parameter count is a rough guide. Penalties, early stopping, and the structure of the model all change how much of the capacity is used.
- Assuming more capacity is always bad. Large neural networks often generalise well when regularised and given enough data. The goal is the right capacity for the data and the regularisation you apply, not the smallest one.
Exercises
Exercise
A degree-15 polynomial and a degree-4 polynomial are fitted to the same 28 training points. Which one will have training error that is lower or equal, and why does that not prove it is the better model?
Show answer
The degree-15 model has lower or equal training error, because its family contains every degree-4 polynomial, so it can fit the training points at least as well. That does not prove it is better, because the extra flexibility can be spent fitting noise. Only error on held-out data shows whether the model generalises.
Exercise
Name two settings that raise the capacity of a decision tree and one setting that lowers the capacity of a k-nearest neighbours model.
Show answer
Increasing maxdepth and decreasing minsamples_leaf both raise a tree's capacity. Increasing k in k-nearest neighbours lowers its capacity, because predictions average over more neighbours and become smoother.