Two ways of being wrong, and a trade-off that can be measured
A model fails on new data for two opposite reasons. It can be too simple for the reality it describes, like a line drawn over a curve: the systematic error is called bias and produces underfitting. Or it can be so flexible that it chases even the noise of the training data, changing shape with every different sample: the sensitivity to the sample is called variance and produces overfitting. On top of these comes the irreducible noise of the data, which no model can remove. Increasing complexity reduces bias and increases variance; the art is finding the point where their sum is minimal. This article measures it instead of describing it, then shows how to diagnose the problem with learning curves and how to fix it with regularization and early stopping. It assumes linear and logistic regression and the way of reading an evaluation described in Evaluation Metrics, where you also find cross-validation.
Bias and variance measured with 300 training sets
The decomposition of the expected error into squared bias, variance and noise is a mathematical fact, and it can be observed with an experiment. The listing knows the true function (a sine) and can therefore generate as many training sets as it wants: it draws 300 of 30 points with noise of standard deviation 0.3, trains a polynomial of a given degree on each, and compares the predictions. The squared bias is how far the mean prediction of the 300 models is from the true function; the variance is how much the predictions of the 300 models differ from each other; the noise is 0.3² = 0.09 whatever model you use. The sum of the three must coincide with the mean error measured on fresh test data, and the listing checks it.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
def vera(x):
return np.sin(2 * np.pi * x) # the function the model does not know
rng = np.random.default_rng(0)
SIGMA = 0.3 # noise of the observations
x_test = np.linspace(0.02, 0.98, 50)
X_test = x_test.reshape(-1, 1)
print("deg. bias^2 variance noise total mean test error")
for grado in (1, 3, 5, 9):
previsioni, err_test, err_train = [], [], []
for _ in range(300): # 300 different training sets of 30 points
x = rng.uniform(0, 1, 30)
y = vera(x) + rng.normal(0, SIGMA, 30)
m = make_pipeline(PolynomialFeatures(grado), LinearRegression()).fit(x.reshape(-1, 1), y)
p = m.predict(X_test)
previsioni.append(p)
err_test.append(np.mean((vera(x_test) + rng.normal(0, SIGMA, 50) - p) ** 2))
err_train.append(np.mean((y - m.predict(x.reshape(-1, 1))) ** 2))
previsioni = np.array(previsioni)
bias2 = np.mean((previsioni.mean(axis=0) - vera(x_test)) ** 2)
varianza = np.mean(previsioni.var(axis=0))
print(f"{grado:5d} {bias2:6.3f} {varianza:8.3f} {SIGMA**2:6.3f} {bias2 + varianza + SIGMA**2:5.3f} {np.mean(err_test):6.3f} (training error: {np.mean(err_train):.3f})")
# Output:
# deg. bias^2 variance noise total mean test error
# 1 0.182 0.022 0.090 0.294 0.293 (training error: 0.265)
# 3 0.004 0.015 0.090 0.108 0.109 (training error: 0.082)
# 5 0.000 0.034 0.090 0.124 0.126 (training error: 0.070)
# 9 0.106 60.364 0.090 60.560 60.555 (training error: 0.063)
Degree 1 (a line) has a squared bias of 0.182 and a variance of only 0.022: it is always wrong in the same way, and its training error (0.265) is almost equal to the test one (0.293). This is the signature of underfitting: the two errors are high and close. Degree 3 lowers the bias to 0.004, almost zero, with a variance of 0.015, and the total error drops to 0.109, close to the theoretical minimum of 0.09 imposed by the noise. Degree 5 still has zero bias but the variance rises to 0.034 and the error to 0.126. Degree 9 with 30 points explodes: variance 60.4, test error 60.6, while the training error is the lowest of all (0.063). This is overfitting: the model fits the sample so well that it becomes useless on the next one. In every row the sum of bias plus variance plus noise coincides with the error measured on the test set (0.294 against 0.293, 0.108 against 0.109, and so on), so the decomposition holds.
The value of 60 is also a numerical consequence of high-degree polynomials on unscaled variables, but that is precisely the point: a model too flexible for the amount of data amplifies every small irregularity.
Diagnosis: learning curve and validation curve
In a real project you do not know the true function, so you cannot decompose the error. You do have two tools, though. The learning curve plots the performance on the training and validation sets as the number of examples used grows. The validation curve plots them as a complexity hyperparameter varies, here the max_depth depth of a tree. The pattern you look for is only one: two high and close curves indicate an adequate model; two close but low curves indicate underfitting (you need more capacity or better variables, not more data); a very high training score with a lower validation score and a gap that does not close indicate overfitting (you need more data, less complexity or regularization). The listing uses the breast cancer dataset with an unlimited tree and a depth-1 one.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import learning_curve, validation_curve
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
def curva(modello, nome):
dimensioni, tr, va = learning_curve(modello, X, y, train_sizes=[0.1, 0.3, 0.5, 0.8, 1.0], cv=5, random_state=0, shuffle=True)
print(nome)
for n, a, b in zip(dimensioni, tr.mean(axis=1), va.mean(axis=1)):
print(f" {n:4d} samples: training {a:.3f} validation {b:.3f} gap {a - b:+.3f}")
curva(DecisionTreeClassifier(random_state=0), "unlimited tree")
curva(DecisionTreeClassifier(max_depth=1, random_state=0), "tree of depth 1")
profondita = [1, 2, 3, 4, 6, 10]
tr, va = validation_curve(DecisionTreeClassifier(random_state=0), X, y, param_name="max_depth", param_range=profondita, cv=5)
print("validation curve on max_depth:")
for d, a, b in zip(profondita, tr.mean(axis=1), va.mean(axis=1)):
print(f" max_depth={d:2d}: training {a:.3f} validation {b:.3f}")
# Output:
# unlimited tree
# 45 samples: training 1.000 validation 0.894 gap +0.106
# 136 samples: training 1.000 validation 0.914 gap +0.086
# 227 samples: training 1.000 validation 0.910 gap +0.090
# 364 samples: training 1.000 validation 0.895 gap +0.105
# 455 samples: training 1.000 validation 0.917 gap +0.083
# tree of depth 1
# 45 samples: training 0.960 validation 0.910 gap +0.050
# 136 samples: training 0.949 validation 0.926 gap +0.022
# 227 samples: training 0.930 validation 0.910 gap +0.019
# 364 samples: training 0.929 validation 0.896 gap +0.033
# 455 samples: training 0.924 validation 0.900 gap +0.025
# validation curve on max_depth:
# max_depth= 1: training 0.924 validation 0.900
# max_depth= 2: training 0.952 validation 0.928
# max_depth= 3: training 0.974 validation 0.917
# max_depth= 4: training 0.985 validation 0.916
# max_depth= 6: training 0.996 validation 0.914
# max_depth=10: training 1.000 validation 0.917
The unlimited tree has a training accuracy of 1.000 at every size, because it memorizes everything, while the validation score stays between 0.894 and 0.917: the gap remains between 0.083 and 0.106 even with 455 samples, and does not close, a sign that the model is too complex for the data it has. The depth-1 tree has a training score of 0.92-0.96, a gap of only 0.02-0.03, and a validation score that stops around 0.90: it is more stable but limited by its own simplicity. The validation curve shows the balance: validation rises up to depth 2 (0.928), then falls slightly and settles between 0.914 and 0.917 while training reaches 1.000. With five folds and a typical dispersion of one or two points, the difference between 0.928 and 0.917 is not proof that depth 2 is the best: it is the indication that beyond the first two levels adding complexity gains nothing. A numerical rule of the type "a gap over 5% means overfitting" does not exist: it depends on the problem, and must be read together with the shape of the curves.
Regularization: paying for complexity
Regularization adds to the cost function a penalty that grows with the size of the model weights, thus discouraging solutions that bend too much around the noise. Ridge (L2) penalizes the sum of the squares of the weights: it shrinks them all, without zeroing them. Lasso (L1) penalizes the sum of the absolute values: it can bring many weights exactly to zero, and therefore also does variable selection. The Elastic Net combines them. The alpha parameter sets the strength: the higher, the simpler the model. Variables must be scaled first, because the penalty treats all weights in the same way.
The listing creates a dataset tailored to overfitting: 80 samples and 60 variables, of which only 5 really influence the result. It compares regression without penalty with three values of Ridge and three of Lasso, printing the R² on training and test, the number of non-zero coefficients and the norm of the coefficients.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Lasso, LinearRegression, Ridge
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# 80 samples and 60 variables, of which only 5 really matter: ideal ground for overfitting
X, y = make_regression(n_samples=80, n_features=60, n_informative=5, noise=15, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
print("model R2 train R2 test non-zero coefficients L2 norm of the coefficients")
modelli = [("no penalty", LinearRegression())]
modelli += [(f"Ridge alpha={a}", Ridge(alpha=a)) for a in (1, 10, 100)]
modelli += [(f"Lasso alpha={a}", Lasso(alpha=a, max_iter=100000)) for a in (0.1, 1, 5)]
for nome, stimatore in modelli:
m = make_pipeline(StandardScaler(), stimatore).fit(X_train, y_train)
w = m[-1].coef_
print(f"{nome:22s} {m.score(X_train, y_train):8.3f} {m.score(X_test, y_test):7.3f} {int(np.sum(np.abs(w) > 1e-8)):28d} {np.linalg.norm(w):10.1f}")
# Output:
# model R2 train R2 test non-zero coefficients L2 norm of the coefficients
# no penalty 1.000 0.766 60 109.8
# Ridge alpha=1 0.999 0.740 60 100.6
# Ridge alpha=10 0.971 0.582 60 77.6
# Ridge alpha=100 0.711 0.281 60 37.7
# Lasso alpha=0.1 1.000 0.968 45 123.7
# Lasso alpha=1 0.996 0.978 30 121.4
# Lasso alpha=5 0.980 0.976 8 113.3
Without a penalty the training R² is 1.000 (with 48 training samples and 60 variables the line passes through all the points) and the test one is 0.766. Ridge surprises: with alpha = 1 the test score drops slightly (0.740), and with higher values it gets worse (0.582, 0.281) because it shrinks all the weights uniformly, including the 5 that are needed. Here the true solution is sparse, and Ridge is not the suitable tool; Ridge gives its best with numerous, correlated variables that each contribute a little. Lasso, instead, brings the test score to 0.968-0.978: with alpha = 1 it keeps 30 coefficients out of 60 and with alpha = 5 only 8, close to the 5 true ones, and the test R² stays at 0.976. The result depends on the structure of the data I generated, so it must not be generalized: it says that the choice between L1 and L2 is a hypothesis about the problem, to be verified with cross-validation, not a preference.
For logistic regression the strength of the penalty is expressed by C, which is the inverse of regularization: a small C means a strong penalty. The listing tests it on the breast cancer dataset with L2 and L1.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
print(" C penalty accuracy cv coefficient norm non-zero coefficients (of 30)")
for penalita in ("l2", "l1"):
for C in (0.001, 0.01, 0.1, 1, 100):
modello = make_pipeline(StandardScaler(), LogisticRegression(C=C, penalty=penalita, solver="liblinear"))
acc = cross_val_score(modello, X, y, cv=5).mean()
w = modello.fit(X, y)[-1].coef_[0]
print(f"{C:>6} {penalita:>8} {acc:11.3f} {np.linalg.norm(w):18.2f} {int(np.sum(np.abs(w) > 1e-8)):>10}")
# Output:
# C penalty accuracy cv coefficient norm non-zero coefficients (of 30)
# 0.001 l2 0.946 0.34 30
# 0.01 l2 0.965 0.92 30
# 0.1 l2 0.982 1.97 30
# 1 l2 0.979 3.85 30
# 100 l2 0.965 21.73 30
# 0.001 l1 0.373 0.00 0
# 0.01 l1 0.933 0.65 4
# 0.1 l1 0.972 2.72 8
# 1 l1 0.972 5.13 16
# 100 l1 0.958 49.70 29
With L2 the norm of the coefficients grows as C grows, from 0.34 to 21.73, but the cross-validation accuracy has a maximum at C = 0.1 (0.982) and drops at C = 100 (0.965): too much freedom makes it worse. With C = 0.001 the penalty is so strong that the model is too rigid (0.946). L1 shows variable selection: at C = 0.01, 4 out of 30 remain with 0.933, at C = 0.1, 8 remain with 0.972, at C = 100 almost all. At C = 0.001 all the coefficients are zero, and the model always predicts the same class, the minority one (0.373 is the share of malignant tumors in the dataset): a limiting case that shows what happens when the penalty wins over everything. With 8 variables out of 30 the accuracy is 0.972, just below the 0.982 of the best L2, and it is the reason why L1 is appreciated when a readable model is needed.
Early stopping: stop when validation stops improving
In models trained in steps, like the gradient boosting you will see in the article on ensembles, every additional tree reduces the error on the training set but at some point worsens generalization. Early stopping measures the performance on a validation set at every step and stops training when it no longer improves. Scikit-learn implements it in HistGradientBoostingClassifier with early_stopping, validation_fraction and n_iter_no_change (active by default only beyond 10000 samples). To see the mechanism without black boxes, the listing does it by hand with GradientBoostingClassifier and staged_predict, which returns the predictions after 1, 2, 3 trees: you look for the maximum on validation and look at the test set only once at the end. The data have 15% wrong labels, to make the overfitting visible.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1500, n_features=20, n_informative=5, flip_y=0.15, random_state=1)
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
X_train, X_val, y_train, y_val = train_test_split(X_rest, y_rest, test_size=0.2, random_state=1)
modello = GradientBoostingClassifier(n_estimators=300, learning_rate=0.1, max_depth=3, random_state=0).fit(X_train, y_train)
# staged_predict returns the predictions after 1, 2, 3... trees
def curva(Xs, ys):
return np.array([np.mean(p == ys) for p in modello.staged_predict(Xs)])
tr, va, te = curva(X_train, y_train), curva(X_val, y_val), curva(X_test, y_test)
print("trees training validation test")
for k in (10, 50, 100, 200, 300):
print(f"{k:6d} {tr[k - 1]:8.3f} {va[k - 1]:11.3f} {te[k - 1]:.3f}")
migliore = int(np.argmax(va)) + 1 # manual early stopping: the maximum of the validation score
print(f"number of trees chosen on the validation set: {migliore}")
print(f"test with {migliore} trees: {te[migliore - 1]:.3f} test with all 300: {te[-1]:.3f}")
# Output:
# trees training validation test
# 10 0.811 0.748 0.778
# 50 0.889 0.738 0.796
# 100 0.932 0.762 0.793
# 200 0.983 0.771 0.776
# 300 0.996 0.762 0.767
# number of trees chosen on the validation set: 128
# test with 128 trees: 0.796 test with all 300: 0.767
The training accuracy rises continuously from 0.811 with 10 trees to 0.996 with 300: the model is memorizing the wrong labels. Validation does not follow it, and oscillates between 0.738 and 0.771. The test set shows the typical shape: it rises up to 0.796 around 50-100 trees and then falls to 0.767. The number chosen on validation, 128, gives a test score of 0.796 against 0.767 with all 300 trees: three points gained by stopping earlier. An honest caveat: the validation set has 280 samples, so a difference of 0.02 amounts to about six samples, and the "128" is a noisy choice. That is why the scikit-learn implementation uses a patience (n_iter_no_change) instead of stopping at the first drop.
Data augmentation, often cited among the defenses, belongs mostly to images, audio and text: it creates new examples with transformations that do not change the label (rotations, crops, synonyms). For tabular data there is no equally safe analogous recipe, and the most reliable remedy remains collecting more real data.
What you can do now
You can decompose the error into bias, variance and noise when you can simulate the data, and recognize in learning curves a model that is too simple, one that is too complex and one that is adequate. You can choose between Ridge, Lasso and the C parameter as hypotheses to verify, and you can stop an iterative model with a validation set. The next step puts many models together to reduce variance: bagging, boosting and gradient boosting.
The trade-off between bias and variance reappears in decision trees (pruning), in recommendation systems (the number of latent factors) and in transfer learning (few labels and a model from scratch).
Frequently asked questions
How do I recognize overfitting from a learning curve?
If the training error is much lower than the validation error and the gap does not close as data increase, the model is too complex: in the example the unlimited tree has training 1.000 and validation 0.917 even with 455 samples.
Ridge or Lasso?
It depends on the structure of the problem: Lasso zeroes the weights and works well when few variables matter, Ridge shrinks all the weights and works better with many correlated variables. It is decided with cross-validation.
What does C mean in LogisticRegression?
It is the inverse of the regularization strength: a small C means a strong penalty and small coefficients, a large C means a weak penalty.
Sources
- scikit-learn User Guide: Validation curves and learning curves - how to read the two curves, consulted on 2026-11-12
- scikit-learn User Guide: Linear Models - Ridge, Lasso, Elastic Net and sparse coefficients, consulted on 2026-11-12
- scikit-learn API: LogisticRegression - C as the inverse of regularization and the liblinear solver for L1, consulted on 2026-11-12
- scikit-learn API: HistGradientBoostingClassifier - early_stopping, validation_fraction and n_iter_no_change, consulted on 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment