Detecting Overfitting with scikit-learn’s learning_curve
Learn how to spot and fix overfitting using scikit-learn’s learning_curve on the Iris dataset, with concrete checks and fixes.
15 Aug 2025, 12:16 UTC

Problem and Takeaway
When a scikit‑learn model predicts the training data with near‑perfect accuracy but scores much lower on unseen data, you are observing overfitting. The fastest diagnostic is to plot learning_curve and watch the gap between training and validation scores widen as the training set grows. Recognizing this pattern early can prevent wasted effort on hyper‑parameter tuning that would not improve generalisation.
Recognizable Condition
The condition is a training accuracy close to 100 % while validation or test accuracy remains at least 10 % lower. This numeric gap indicates that the model memorizes training samples instead of learning generalizable patterns. The gap is calculated on the same metric used for evaluation, such as accuracy or F1, to keep the comparison meaningful.
Diagnostic Overview
| Metric | Training Score | Validation Score | Interpretation |
|---|---|---|---|
| Training set size → largest | ≈1.0 (100 %) | Significantly lower (≥10 % gap) | Indicates overfitting |
Ordered Checks
- Choose a high‑capacity model (e.g., SVC with RBF kernel) and fix
random_statefor reproducibility. - Call
learning_curvewithcv=5(or a stratified splitter) and plot training and validation scores versus training set size. - Compute the mean and standard deviation of the scores; a large standard deviation signals unstable estimates, while the mean gap at the largest training size is the key diagnostic metric.
- Verify that the random_state and CV strategy remain consistent across runs.
- Check that the training score approaches 1.0 and the validation score plateaus; the difference between these means at the largest training size confirms the overfitting diagnosis.
Fixes Tied to Findings
- Increase regularization: use Ridge or Lasso linear models, or lower the
Cparameter for SVM to penalize complex decision boundaries. - Reduce model complexity: limit
max_features, decrease kernel degree, or select a simpler algorithm such as logistic regression. - Gather more training data or apply data augmentation/noise injection to make the learning problem less noisy.
- Use early stopping in iterative solvers (e.g., SGD) to halt training before the model memorizes the data.
Escalation Criteria
If after applying regularization, simplifying the model, and adding data the learning curve still shows a persistent >10 % gap, consider switching to a less expressive model family, performing feature selection, or using nested cross‑validation for a more reliable estimate before redesigning the pipeline.
Concrete Example
Load the Iris dataset, train an RBF SVM, compute learning_curve with cv=5, and plot the results. The script requires only numpy, scikit‑learn, and matplotlib, which are standard in most Python environments.
import numpy as np
from sklearn import datasets, svm
from sklearn.model_selection import learning_curve
import matplotlib.pyplot as plt
# Load data
X, y = datasets.load_iris(return_X_y=True)
# High‑capacity model (RBF SVM)
model = svm.SVC(kernel='rbf', C=1000, random_state=42)
# Compute learning curve
train_sizes, train_score, val_score = learning_curve(
model, X, y,
cv=5,
train_sizes=np.linspace(0.1, 1.0, 100),
scoring='accuracy',
n_jobs=-1,
shuffle=True,
random_state=42
)
# Plot
plt.figure(figsize=(8,5))
plt.plot(train_sizes, train_score.mean(axis=1), 'o-', label='Training accuracy')
plt.plot(train_sizes, val_score.mean(axis=1), 's-', label='Validation accuracy')
plt.xlabel('Training set size')
plt.ylabel('Accuracy')
plt.title('Learning Curve – Iris (RBF SVM)')
plt.legend()
plt.grid(True)
plt.savefig('learning_curve.png')
plt.show()
The script must have write permission to save learning_curve.png. It may be computationally heavy on large datasets; using a subset or n_jobs can alleviate memory pressure. Monitor RAM usage to avoid out‑of‑memory errors. If you run the script on a machine with less than 2 GB RAM, you may see a memory warning; reducing train_sizes or using n_jobs=1 can mitigate this.
Verification
Run the example script, then examine the plot at the largest training size. Compute the gap as train_score - val_score at that point; if the gap exceeds 0.10 (10 %), the model is overfitting. Re‑run with a Ridge regression (tune alpha) and verify that the validation score rises and the curve gap narrows. You can also compute the gap programmatically by printing train_score[-1] - val_score[-1] to obtain a numeric confirmation.
Limitations and Risks
learning_curve can be computationally heavy on very large datasets; using a subset or setting n_jobs may help but increases memory pressure. Monitor RAM usage to avoid out‑of‑memory errors. Older scikit-learn 0.20 releases behaved differently with shuffle and refit; always pin to a recent 1.x version. Class imbalance can distort accuracy, so prefer StratifiedKFold when classes are uneven. Improper random_state causes varying curves; fix the seed when comparing results. On a CPU‑only environment, the plot generation may take several seconds for larger datasets, which is normal.
Conclusion
By systematically plotting learning_curve, interpreting score gaps, and applying the fixes above, you can reliably detect and mitigate overfitting in scikit-learn models. This disciplined approach works for any supervised learning task where a learning curve can be computed.