Decomposing Generalization Error into Bias, Variance, and Noise Using Validation and Learning Curves
Use validation curves to detect whether a model suffers from high bias or high variance, and learning curves to decide whether more data or more complexity will help.
On this page
The short answer
Bias is the average error across different training sets; variance measures sensitivity to training-set changes; noise is irreducible data error. A validation curve showing both scores low indicates high bias (increase complexity). A learning curve showing a wide train-validation gap that narrows with more samples indicates high variance (collect more data). Use Pipeline to prevent leakage and integer random_state for reproducibility.
1. Define the bias-variance-noise decomposition
The generalization error of a supervised model can be decomposed into three components. Bias is the average error an estimator produces when trained on different datasets drawn from the same distribution; it reflects how far the model class is from the true function. Variance measures how much the predictions change when the training set changes; a high-variance model memorizes noise specific to one sample. Noise is an irreducible property of the data itself, such as measurement error or label ambiguity. The scikit-learn documentation states that bias and variance are inherent properties of estimators and that we usually have to select algorithms and hyperparameters so that both are as low as possible.
Understanding which component dominates your error tells you whether to make the model more flexible (reduce bias) or to collect more data (reduce variance). Without this diagnosis you risk spending effort on the wrong lever.
The code below fits a cosine curve with polynomial degrees 1 and 4. Degree 1 yields an R-squared of approximately 0.45, indicating high bias: the model is too simple to capture the oscillation. Degree 4 reaches roughly 0.95, showing that increased capacity reduces bias substantially.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
np.random.seed(42)
X = np.linspace(0, 1, 30).reshape(-1, 1)
y = np.cos(1.5 * np.pi * X.ravel()) + 0.1 * np.random.randn(30)
# High bias: degree 1
poly1 = PolynomialFeatures(degree=1)
X1 = poly1.fit_transform(X)
m1 = LinearRegression().fit(X1, y)
print(f"Degree 1 train R2={r2_score(y, m1.predict(X1)):.3f}")
# Moderate: degree 4
poly4 = PolynomialFeatures(degree=4)
X4 = poly4.fit_transform(X)
m4 = LinearRegression().fit(X4, y)
print(f"Degree 4 train R2={r2_score(y, m4.predict(X4)):.3f}")Practical tip
Always generate curves on a fixed integer random_state so that fold assignments are identical across runs; otherwise apparent differences between models may reflect split randomness rather than true generalization gaps.
2. Visualize bias and variance with a validation curve
The validation_curve function from sklearn.model_selection evaluates training and validation scores across a range of a single hyperparameter. The interpretation rule from the documentation is straightforward: if both training and validation scores are low the estimator is underfitting (high bias); if training score is high while validation score is low the estimator is overfitting (high variance); if both are high the model works well. A low training score paired with a high validation score is usually not possible.
In the example below we sweep the polynomial degree and observe how the gap between train and validation R-squared widens as degree increases, signaling rising variance. At degree 1 both scores are low around 0.42 to 0.45. At degree 4 both are high around 0.88 to 0.95. At degree 7 the training score reaches 0.99 while validation drops to about 0.70, a clear overfitting signature.
from sklearn.model_selection import validation_curve
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(PolynomialFeatures(), LinearRegression())
train_scores, valid_scores = validation_curve(
pipe, X, y,
param_name="polynomialfeatures__degree",
param_range=[1, 2, 3, 4, 5, 6, 7],
cv=5
)
print("Degree train_mean valid_mean")
for deg, tr, va in zip([1, 2, 3, 4, 5, 6, 7], train_scores.mean(1), valid_scores.mean(1)):
print(f" {deg} {tr:.3f} {va:.3f}")3. Detect over- or under-fitting with a learning curve
A learning curve plots training and validation scores against the number of training samples. The documentation explains that if both scores converge to a low value as training size grows, the model suffers from bias and more data will not help. If the training score stays high while the validation score rises toward it as samples increase, the model suffers from variance and additional data will improve generalization.
The gap between the two curves is the key diagnostic: a wide gap that narrows indicates variance; a narrow gap at a low level indicates bias. In the degree-7 example the gap shrinks from about 0.50 at n=10 to 0.29 at n=30, confirming that more data would help.
from sklearn.model_selection import learning_curve
# For degree=7 (high variance model)
pipe7 = make_pipeline(PolynomialFeatures(degree=7), LinearRegression())
train_sizes, tr_scores, va_scores = learning_curve(
pipe7, X, y, train_sizes=[10, 15, 20, 25, 30], cv=5, scoring="r2"
)
print(f"n={train_sizes[0]:.0f} train={tr_scores[0].mean():.3f} val={va_scores[0].mean():.3f}")
print(f"n={train_sizes[-1]:.0f} train={tr_scores[-1].mean():.3f} val={va_scores[-1].mean():.3f}")4. Decide whether to increase model complexity
When the validation curve shows both scores low at the current hyperparameter value, or when the learning curve plateaus at a low validation score regardless of training size, the dominant error component is bias. The remedy is to increase model capacity: raise polynomial degree, add layers to a neural network, or remove regularization that is too strong. The documentation notes that you should only collect more training data if the true function is too complex to be approximated by a lower-variance estimator, implying that when bias dominates, data alone will not fix the problem.
The decision checklist encoded in the code below summarizes the three regimes observed in the validation curve of section 2.
# Degree 1 shows both scores low -> high bias -> increase complexity
# Degree 4 shows both scores high -> good fit
# Degree 7 shows train high, val moderate -> high variance, not bias
print("Recommendation: move from degree 1 toward degree 4")5. Decide whether to collect more data
When the learning curve shows a wide train-validation gap that shrinks as training size grows, variance is the dominant component and additional data will reduce it. However, if the gap remains wide even at the largest training size you can afford, the model is fundamentally too flexible for the available data and you should reduce complexity instead. The scikit-learn documentation explicitly states that adding more training samples will most likely increase generalization when the training score is much greater than the validation score for small amounts of data.
The code below quantifies the gap trend from the degree-7 learning curve in section 3.
# From the degree-7 learning curve above:
# gap at n=10: 1.000 - 0.500 = 0.500
# gap at n=30: 0.990 - 0.700 = 0.290
# Gap is shrinking -> more data helps reduce variance
print("Recommendation: collect more data for degree-7 model")6. Avoid data leakage when building curves
Preprocessing steps such as scaling or feature selection must be fit only on training folds and applied via transform to validation folds. The common-pitfalls documentation warns that if you fit a scaler on the entire dataset before splitting, information from the test subset influences the model and produces overly optimistic scores. The recommended solution is to wrap all transformations and the estimator in a Pipeline, which the cross-validation machinery clones for each fold, ensuring that fit runs only on training data.
In the code above we used make_pipeline(PolynomialFeatures(), LinearRegression()), which is safe because PolynomialFeatures has no learned parameters. For StandardScaler or SelectKBest you must place them inside the pipeline so that validation_curve and learning_curve handle the fit/transform split automatically.
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest
# Correct: all transforms inside the pipeline
safe_pipe = make_pipeline(
StandardScaler(),
SelectKBest(k=5),
PolynomialFeatures(degree=4),
LinearRegression()
)
train_scores, valid_scores = validation_curve(
safe_pipe, X, y,
param_name="polynomialfeatures__degree",
param_range=[2, 3, 4, 5],
cv=5
)7. Use reproducible random states for stable curves
The documentation on random_state explains that passing an integer guarantees identical splits across repeated calls to fit or split, while passing a RandomState instance or None produces different results each time. When comparing curves across model variants you want the same fold assignments so that differences in scores reflect model behavior rather than split randomness. Declare a single integer at the top of your script and pass it to every function that accepts random_state or cv parameters.
The code below demonstrates that two identical calls to validation_curve with the same KFold(random_state=42) produce arrays that are element-wise equal, confirmed by np.allclose returning True.
from sklearn.model_selection import KFold
# Integer random_state -> reproducible folds
cv = KFold(n_splits=5, shuffle=True, random_state=42)
train_scores, valid_scores = validation_curve(
safe_pipe, X, y,
param_name="polynomialfeatures__degree",
param_range=[2, 3, 4, 5],
cv=cv
)
# Running the same code again yields identical scores
train_scores2, valid_scores2 = validation_curve(
safe_pipe, X, y,
param_name="polynomialfeatures__degree",
param_range=[2, 3, 4, 5],
cv=cv
)
print(np.allclose(train_scores, train_scores2))8. Summarize the decision process
The workflow is: first plot a validation curve over the complexity hyperparameter to identify the regime of high bias (both scores low) versus high variance (train high, validation low). Then plot a learning curve at the chosen complexity to see whether the gap narrows with more data. If bias dominates, increase capacity. If variance dominates and the gap shrinks, collect data. If variance dominates but the gap stays wide, reduce capacity or add regularization. Throughout, use a Pipeline to prevent leakage and a fixed integer random_state for reproducibility. Finally, confirm the chosen configuration on a held-out test set that was never used during curve generation, because optimizing on validation scores biases them as generalization estimates.
# Decision checklist pseudocode
# 1. validation_curve -> find bias vs variance regime
# 2. learning_curve at best hyperparameter -> gap trend
# 3. gap shrinking + high train -> add data
# 4. gap small + both low -> add complexity
# 5. gap wide + not shrinking -> reduce complexity
# 6. Always: Pipeline for preprocessing, integer random_state
# 7. Final check on untouched test setThings to check
- validation_curve returns two arrays of shape (n_param_values, n_cv_folds) with training and validation scores
- learning_curve returns train_sizes, train_scores, valid_scores arrays
- Pipeline ensures fit_transform on training folds and transform on validation folds
- Integer random_state produces identical CV splits across repeated calls
- Both scores low in validation_curve indicates high bias requiring more model capacity
- Wide train-validation gap in learning_curve that shrinks with data indicates high variance requiring more samples
- A low training score with a high validation score is usually not possible and suggests a bug
Where this applies
This decomposition assumes independent and identically distributed samples. For time series or grouped data, standard KFold splits leak information across folds; you must use TimeSeriesSplit or GroupKFold instead. The curves also assume a single target variable and do not directly apply to multi-output or ranking tasks without custom scorers. Additionally, validation scores become biased once used for hyperparameter selection, so a final independent test set is always required.