Unit 1, lesson 10

Overfitting, Underfitting, and Model Complexity

How training error and validation error reveal overfitting and underfitting, how the number of neighbors sets model complexity, and why a memorizing predictor's zero training error proves little.

  • Video 10
  • A First Model and Overfitting

When the training inputs are all distinct, a one-nearest-neighbor model reproduces every training target exactly, so its training error is zero. Does that make it the best choice for the next case? It has shown that it can recall answers it has already seen, while the reason for building it is to predict answers it has not seen. This lesson compares nearest-neighbor models of different flexibility on one constructed data set, separates training error from validation error, and shows how to read a gap between them without treating every gap as a complexity problem.

Key terms

Training error

Definition Fit a learning procedure to a training set of nn examples (x1,y1),…,(xn,yn)(\mathbf{x}_1, y_1), \dots, (\mathbf{x}_n, y_n) to get a predictor f^\hat{f}, and let L(y,y^)≥0L(y, \hat{y}) \ge 0 be the loss charged when the target is yy and the prediction is y^\hat{y}. The training error is the average loss of f^\hat{f} on the same examples,

err⁡train=1n∑i=1nL(yi,y^i),\operatorname{err}_{\text{train}} = \frac{1}{n} \sum_{i=1}^{n} L(y_i, \hat{y}_i),

where y^i=f^(xi)\hat{y}_i = \hat{f}(\mathbf{x}_i). With squared loss it is the training mean squared error (MSE), the average of ei2e_i^2 for the errors ei=y^i−yie_i = \hat{y}_i - y_i, each a prediction minus the actual value. Every target in this average helped shape the predictor that is scored on it, so training error measures how closely the procedure reproduces answers it has already seen. It tends to understate the error on new cases, and the more freely a procedure can adapt to individual examples, the more it tends to understate it. When a nearest-neighbor model is scored on its own training inputs, each training example takes part in the neighbor search for its own prediction, at distance zero.

In plain words Training error asks how well a model recalls the answers it studied. A small value shows that the model describes its training data closely. It does not show that the model will predict the next case well, because a model can recall noise as faithfully as pattern.

Example The examples on this page use constructed data with one feature. The signal is y=xy = x, which is known only because the data were built that way. The seven training inputs are x=0,1,…,6x = 0, 1, \dots, 6 with recorded targets 0,1,5,3,4,5,60, 1, 5, 3, 4, 5, 6. Every target equals the signal except at x=2x = 2, where one deliberately perturbed value 55 replaces 22. Each model is a kk-nearest neighbor regressor that predicts the equally weighted average of the targets of the kk closest training inputs and breaks distance ties in favor of the smaller training index. With k=3k = 3 the training predictions are 2,2,3,4,4,5,52, 2, 3, 4, 4, 5, 5, the squared errors are 4,1,4,1,0,0,14, 1, 4, 1, 0, 0, 1, and the training MSE is 11/7≈1.5711/7 \approx 1.57. With k=1k = 1 each training input finds itself, so every prediction equals its target and the training MSE is 00.

Validation error

Definition A validation set is a collection of mm examples (x1′,y1′),…,(xm′,ym′)(\mathbf{x}'_1, y'_1), \dots, (\mathbf{x}'_m, y'_m) that take no part in fitting, including any preprocessing learned from data, and that are used to compare candidate procedures, for example different values of a hyperparameter. The validation error of a fitted predictor f^\hat{f} is its average loss on these examples,

err⁡val=1m∑j=1mL(yj′,y^j′),\operatorname{err}_{\text{val}} = \frac{1}{m} \sum_{j=1}^{m} L(y'_j, \hat{y}'_j),

where y^j′=f^(xj′)\hat{y}'_j = \hat{f}(\mathbf{x}'_j). If the validation examples are independent draws from the population the model will be applied to, and independent of the training data, then for one fixed predictor the validation error is an unbiased estimate of the expected loss on a new case from that population. It is still random, it changes with the particular validation cases, and it can be far from that expected loss when mm is small. When validation error picks the best of several candidates, the winner’s value tends to understate its error on new cases, so the final assessment uses a test set that played no part in any choice. Generalization, good performance on new cases from the intended deployment setting, is what validation error is meant to estimate, and it does so only as far as the validation cases resemble that setting.

In plain words Validation error is a practice exam on questions the model never studied. It is the honest score for comparing candidates, but it comes from a limited sample of questions, and once it has chosen the winner, a separate final exam is needed to say how well the winner will do.

Example The six validation inputs x=0.4,1.4,…,5.4x = 0.4, 1.4, \dots, 5.4 have targets equal to the signal, so each target equals its input. The table lists the predictions for three neighbor counts.

Validation xxTargetk=1k = 1k=3k = 3k=7k = 7
0.40.40.40.4002224/724/7
1.41.41.41.4112224/724/7
2.42.42.42.4553324/724/7
3.43.43.43.4334424/724/7
4.44.44.44.4444424/724/7
5.45.45.45.4555524/724/7

The one-neighbor model is 0.40.4 too low at five of the inputs, and at x=2.4x = 2.4 it copies the perturbed target 55 of the nearest training input x=2x = 2. That single error of 2.62.6 has square 6.766.76, so the total is 6.76+5⋅0.16=7.566.76 + 5 \cdot 0.16 = 7.56 and the validation MSE is 7.56/6=1.267.56/6 = 1.26. For k=3k = 3 the squared errors are 2.56,0.36,0.36,0.36,0.16,0.162.56, 0.36, 0.36, 0.36, 0.16, 0.16, which give 3.96/6=0.663.96/6 = 0.66. For k=7k = 7 every prediction is the training mean 24/7≈3.4324/7 \approx 3.43, and the validation MSE is about 3.203.20.

Model complexity

Definition Model complexity, or flexibility, describes how wide a range of prediction functions a learning procedure can produce, and so how closely it can follow the particular training sample it is given. No single measure fits every kind of model. Within one family it is usually set by a hyperparameter, a setting chosen before fitting instead of learned by the fitting step, such as the degree of a polynomial or the number of neighbors kk. In kk-nearest neighbor regression with equal weights, kk is an integer with 1≤k≤n1 \le k \le n, and each prediction is the average of kk training targets. The neighbors of a query depend only on the inputs and the tie rule, so changing one training target by Δ\Delta moves every prediction by either 00 or Δ/k\Delta / k. The choice k=1k = 1 gives the most flexible and most sample-sensitive rule, and k=nk = n predicts the training mean for every query. Complexity therefore decreases as kk grows, the opposite direction from polynomial degree. Like any hyperparameter, the neighbor count is chosen with validation evidence and never tuned on the test set.

In plain words A flexible model can bend to follow individual training points, while a rigid one can follow only broad trends. With few neighbors, a prediction listens closely to the nearest points, noise included. With many neighbors, it averages over a wide region and smooths away noise and real local detail alike.

Example Keep every training row except the one at x=2x = 2, and give that row the target −1-1, 22 or 55 in three constructed training sets. At the query x=2.4x = 2.4, the one-neighbor predictions are −1-1, 22 and 55, copying the changed target. The three-neighbor predictions are 11, 22 and 33, since the changed target is one of three averaged values, and the seven-neighbor predictions are 18/718/7, 33 and 24/724/7. A change of 66 in one target moves the three predictions by 66, 22 and 6/76/7. Lower sensitivity is not automatically better, because the averaging that damps noise also flattens the real increase of the signal.

Overfitting

Definition A fitting or model-selection procedure overfits when it adapts to details of its particular training sample that do not carry over to the cases it will predict, such as noise in individual targets, so that its predictions on relevant new cases are worse than those of an available less flexible alternative. The usual evidence combines low training error, clearly higher validation error, and a less flexible candidate with lower validation error. A gap between training and validation error does not prove overfitting by itself. Some gap is common even for a well-chosen model, because training error reuses the targets that shaped the predictor. A small validation set makes any comparison noisy, a gap measured on a validation set from a different population may reflect that mismatch rather than overfitting, and leakage or a faulty split can distort either number. So check the roles and comparability of the data before treating a gap as a complexity problem.

In plain words An overfitted model has learned its sample, quirks included, instead of only the pattern that carries over. The quirks do not repeat in new data, so the closer fit to the past buys worse predictions for the future. This does not mean simpler always wins. How much flexibility pays depends on how noisy the targets are, how much real detail the signal has and how much data there is.

Example The three models compare as follows on the constructed data.

Neighbors kkTraining MSEValidation MSE
11001.261.26
3311/7≈1.5711/7 \approx 1.570.660.66
77208/49≈4.24208/49 \approx 4.24≈3.20\approx 3.20

The one-neighbor model has the lowest training error and a higher validation error than the three-neighbor model, and 6.766.76 of its total squared validation error 7.567.56 comes from copying the perturbed target. Here it overfits relative to k=3k = 3. The perturbed target is what makes it lose. If the target at x=2x = 2 were the signal value 22, the one-neighbor validation MSE would be 0.160.16 and the three-neighbor value 29/150≈0.1929/150 \approx 0.19, so of these three rules the most flexible would predict best.

Underfitting

Definition A model or training procedure underfits when it is too restricted, or trained too incompletely, to capture structure in the data that is real and useful for prediction. The typical sign is that training error and validation error are both high, and that an available alternative that is more flexible, better trained or given more informative features lowers the validation error. Common causes are too little flexibility, such as a large kk or a straight line for a curved relationship, features that leave out information the target depends on, and an optimization stopped before it converged. High error alone does not prove underfitting, since noise in the targets limits how small the error on new cases can be for any predictor. The evidence is a justified change that lowers validation error, not only training error.

In plain words An underfitted model is too blunt to see the pattern, so it does poorly even on the data it was fitted to. The remedy is more flexibility, better features or more complete training, chosen according to what the validation evidence shows and not by adding complexity by default.

Example The seven-neighbor model averages all seven targets, so it predicts 24/7≈3.4324/7 \approx 3.43 for every query and ignores the increasing signal. Its training MSE 208/49≈4.24208/49 \approx 4.24 and its validation MSE of about 3.203.20 are both far above the values 1.571.57 and 0.660.66 of the three-neighbor model, so here it underfits relative to k=3k = 3. Its validation error is even below its training error, a reminder that the two numbers come in no fixed order. Running every kk from 11 to 77 gives validation MSEs of 1.261.26, 0.860.86, 0.660.66, 1.071.07, 1.171.17, 2.032.03 and 3.203.20, so k=3k = 3 also wins among all seven choices on these six validation cases. The values happen to fall and then rise. That shape is a fact about this constructed data set and not a law, and a different validation sample could favor a different kk. The formal split of expected squared error into bias, variance and noise comes later, in Bias, Variance, and Irreducible Error.

Memorizing predictor

Definition A memorizing predictor stores the training examples and answers any query whose input exactly matches a stored training input with a stored target for that input. Every other input needs a fallback rule, such as the training mean or the target of the nearest stored input. If the training inputs are all distinct, a memorizer has training error 00 under any loss with L(y,y)=0L(y, y) = 0. If one input appears with different targets, no rule that depends only on the input can reproduce them all, so under squared loss the training error stays above 00. A one-nearest-neighbor regressor is a memorizer whose fallback is the target of the nearest stored input. For a memorizer, zero training error shows only that the answers were stored, and its performance on new inputs depends entirely on the fallback.

In plain words A memorizer is a lookup table. It answers every question it has seen before and has to guess on everything else, and its perfect training score says nothing about the guesses. Zero training error together with poor validation error is a warning sign worth investigating, though not every failure on new data comes from memorizing.

Example A lookup table on the seven training rows that falls back on the training mean has training MSE 00. None of the validation inputs 0.4,1.4,…,5.40.4, 1.4, \dots, 5.4 matches a training input, so it predicts 24/724/7 for all of them, and its validation MSE is about 3.203.20, the same as the seven-neighbor model. The one-neighbor model also has training MSE 00 and reaches 1.261.26 on the same cases. Two predictors with identical training scores differ by a factor of about 2.52.5 on new cases, and the whole difference comes from the fallback rule.

Check yourself

  1. Constructed training data have inputs x=0,1,2,3,4x = 0, 1, 2, 3, 4 with targets 1,2,9,4,51, 2, 9, 4, 5, and two validation cases are x=1.7x = 1.7 with target 33 and x=3.4x = 3.4 with target 44. For equal-weight nearest-neighbor regression with k=1k = 1 and with k=3k = 3, find the training MSE and the validation MSE. Which neighbor count does each kind of error favor, and what can two validation cases establish?
Show the answer

With k=1k = 1 the training inputs are distinct and each finds itself, so the training MSE is 00. At x=1.7x = 1.7 the nearest training input is 22, so the prediction is 99 and the squared error is 62=366^2 = 36. At x=3.4x = 3.4 the nearest input is 33, the prediction is 44 and the squared error is 00. The validation MSE is 36/2=1836/2 = 18.

With k=3k = 3 the training predictions at x=0,1,2,3,4x = 0, 1, 2, 3, 4 average the targets at the inputs {0,1,2}\{0, 1, 2\}, {0,1,2}\{0, 1, 2\}, {1,2,3}\{1, 2, 3\}, {2,3,4}\{2, 3, 4\} and {2,3,4}\{2, 3, 4\}, which gives 4,4,5,6,64, 4, 5, 6, 6. The squared errors are 9,4,16,4,19, 4, 16, 4, 1, so the training MSE is 34/5=6.834/5 = 6.8. At x=1.7x = 1.7 the three nearest inputs are 22, 11 and 33, with average target (9+2+4)/3=5(9 + 2 + 4)/3 = 5 and squared error 44. At x=3.4x = 3.4 they are 33, 44 and 22, with average target (4+5+9)/3=6(4 + 5 + 9)/3 = 6 and squared error 44. The validation MSE is 44.

Training error favors k=1k = 1 and validation error favors k=3k = 3. Only the validation comparison speaks to new cases, but two cases are far too few to establish a stable best kk. Sensible next steps are more representative validation cases or repeated development splits, and a check of whether the target 99 was recorded correctly, without deleting it merely because it is unusual.

  1. A training set lists four rows in this order, (x,y)=(1,2)(x, y) = (1, 2), (2,3)(2, 3), (2,7)(2, 7) and (4,4)(4, 4). A one-nearest-neighbor model breaks distance ties in favor of the earlier row. Someone claims its training MSE must be 00 because each training query finds itself. Find the actual training MSE, and the smallest training MSE that any predictor using only xx can reach on these rows.
Show the answer

The rows at x=1x = 1 and x=4x = 4 find themselves. Both rows with x=2x = 2 are at distance 00 from a query at x=2x = 2, and the tie goes to the earlier row, whose target is 33. So the row with target 77 is predicted as 33, its squared error is 1616, and the training MSE is 16/4=416/4 = 4. The claim fails because it needs distinct training inputs.

Any predictor that uses only xx gives a single value cc at x=2x = 2, and the two rows there contribute (c−3)2+(c−7)2(c - 3)^2 + (c - 7)^2. This sum is smallest at their mean c=5c = 5, where it equals 88, and the other two rows can be predicted exactly. The smallest possible training MSE is 8/4=28/4 = 2. Repeated inputs with different targets are worth checking as possible duplicate or mistaken records, but if both rows are genuine, no predictor of xx alone can fit them both.

  1. A team fits nearest-neighbor regression to 2,000 training rows and scores 200 validation rows drawn from the population the model will serve, with the results below. Which neighbor counts show signs of overfitting or underfitting? Should the team choose k=50k = 50 and report 5.15.1 as the error to expect, and what experiment should come next?
Neighbors kkTraining MSEValidation MSE
11009.89.8
10104.14.15.25.2
50505.05.05.15.1
4004008.78.78.98.9
Show the answer

At k=1k = 1 the training MSE is 00, which only shows that each training row recalled its own target, while the validation MSE of 9.89.8 is far above the 5.25.2 and 5.15.1 of the models with 1010 and 5050 neighbors. That pattern suggests overfitting relative to those models. At k=400k = 400 both errors are high, and both fall when kk drops to 5050. That suggests underfitting, with an average over 400400 neighbors washing out local structure that smaller neighborhoods capture. The gaps at k=10k = 10 and k=50k = 50 do not show overfitting by themselves, because a neighbor model’s training predictions include each row’s own target.

The team should not report 5.15.1. It is the smallest of four validation scores and it made the choice, so it tends to understate the chosen model’s error on new cases. The difference between 5.25.2 and 5.15.1 is also small, and whether it is real depends on how much the squared errors vary from case to case. A justified next experiment compares the two models case by case on the same validation rows, or runs cross-validation on the development data over a finer grid of kk between 1010 and 5050, keeping linked records in one fold and respecting time order when the deployment requires it. Once kk is fixed, the model is assessed once on an untouched test set, and that score is the one to report.

How this lesson connects