What is underfitting and overfitting?
Underfitting happens when a model lacks the capacity to learn the underlying data structure, causing high error on both training and validation sets (high bias). Overfitting happens when an overly flexible model memorizes noise and training-set quirks, producing near-zero training error alongside poor generalization on unseen test data (high variance). Good machine learning practice balances model complexity, regularization, and data size to hit the validation-error minimum between these regimes.
Study Card: Underfitting vs. Overfitting
Direct Answer
Underfitting and overfitting represent the two classic failure modes of model generalization:
- Underfitting (high bias): The model is too simple or overly constrained to capture the true input–output signal, resulting in poor performance on both the training set and the test set.
- Overfitting (high variance): The model has excess capacity relative to the data and fits random noise or spurious sample correlations, yielding very low training error but high error on unseen test data.
The goal of model selection and regularization is to match model complexity and inductive bias to the problem so validation error is minimized between these two extremes.
Key Terms
- Underfitting: High training error and high validation/test error due to insufficient model capacity or excessive regularization.
- Overfitting: Very low training error paired with much higher validation/test error due to memorizing training noise.
- Bias: Systematic error from overly restrictive modeling assumptions.
- Variance: Sensitivity of learned parameters and predictions to random sampling of the training set.
- Generalization Gap: Difference between test/validation error and training error, indicating overfitting when large.
Example
Suppose observations follow a true quadratic trend with random Gaussian noise . Fitting a straight line underfits: it misses the curvature, producing high MSE on both training and test splits. Fitting a 15th-degree polynomial overfits: it twists aggressively through training noise to achieve near-zero training error, yet diverges wildly at test inputs. A 2nd-degree polynomial achieves the best test generalization.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
# Generate noisy sine data
rng = np.random.default_rng(0)
X = np.sort(5 * rng.random((80, 1)), axis=0)
y = np.sin(X).ravel() + rng.normal(0, 0.2, X.shape[0])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
models = {
"Underfit (deg=1)": LinearRegression(),
"Good Fit (deg=3)": make_pipeline(PolynomialFeatures(3), LinearRegression()),
"Overfit (deg=15)": make_pipeline(PolynomialFeatures(15), LinearRegression()),
}
X_plot = np.linspace(0, 5, 200).reshape(-1, 1)
plt.figure(figsize=(10, 6))
plt.scatter(X_train, y_train, color="blue", s=22, label="Training Data")
plt.scatter(X_test, y_test, color="green", s=30, marker="x", label="Test Data")
for name, model in models.items():
model.fit(X_train, y_train)
train_mse = mean_squared_error(y_train, model.predict(X_train))
test_mse = mean_squared_error(y_test, model.predict(X_test))
print(f"{name:18s} -> Train MSE: {train_mse:.4f} | Test MSE: {test_mse:.4f}")
plt.plot(X_plot, model.predict(X_plot), lw=2, label=f"{name} (Test MSE: {test_mse:.2f})")
plt.ylim(-2.0, 2.0)
plt.title("Underfitting vs. Good Fit vs. Overfitting")
plt.xlabel("X")
plt.ylabel("y")
plt.legend()
plt.grid(True)
plt.show()
Related Concepts
- Bias–Variance Tradeoff: Classical framework decomposing expected squared generalization error into (and noting modern overparameterized deep learning can exhibit double descent past the interpolation threshold).
- Learning Curves: Plotting training and validation error against dataset size distinguishes underfitting (both curves plateau at high error) from overfitting (wide gap between low train error and higher validation error).
- Remedies for Overfitting: Collect more training data, add L1/L2 regularization or dropout, apply data augmentation, use early stopping, or simplify the model.
- Remedies for Underfitting: Increase model capacity or feature richness, reduce excessive regularization, or train longer with better optimization.