Editor

Detect Overfitting

Advanced · Write the code · from Evaluating ML Models: Cross-Validation, Metrics, and Overfitting

From the lesson: Evaluating ML Models: Cross-Validation, Metrics, and Overfitting

You've trained a model and it gets 95% accuracy. Should you celebrate? Not yet. That number might be lying to you. Maybe your test set was too easy. Maybe the model memorized the training data. Maybe accuracy is the wrong metric entirely.

Read the lesson

Train two decision trees: one with max_depth=2 and one with max_depth=None (unlimited). For each, print the training accuracy and the mean 5-fold CV accuracy (both rounded to 4 decimal places). Format: "Depth-2 train: X.XXXX cv: X.XXXX" and "No-limit train: X.XXXX cv: X.XXXX".

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=200, n_features=6,
n_informative=3, random_state=42)
# Compare shallow vs deep tree

More Model Evaluation exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz