Overfitting and Cross-Validation
A model that performs great on training data but poorly on new data has overfit, it memorized noise and quirks specific to the training set instead of learning patterns that generalize. This lesson shows how to spot it, and how to evaluate and tune models more robustly than a single train/test split allows.
Spotting overfitting
model.score(X, y) is a shortcut that fits/predicts/scores in one call (accuracy for classifiers, R² for regressors). A wide gap between train accuracy (often near 1.0, an unconstrained tree can memorize the training set almost perfectly) and test accuracy is the classic signature of overfitting.
Cross-validation: don't trust a single split
A single train/test split can be lucky or unlucky, by chance, the test set might be unusually easy or hard. k-fold cross-validation splits the data into k chunks, trains and evaluates k times (each time using a different chunk as the "test" fold), and averages the results, a far more reliable estimate.
cv=5 means 5-fold cross-validation, the data is split 5 ways, and the model is trained and scored 5 separate times. scores holds one accuracy per fold, its mean is a much sturdier estimate than any single train_test_split result.
Tuning hyperparameters with GridSearchCV
GridSearchCV automates exactly what you'd otherwise do by hand: try every value in param_grid, cross-validate each one, and report which setting scored best, max_depth limits how many yes/no questions deep a tree can grow, a smaller number fights overfitting at the risk of underfitting if set too low.
NOTE
Limiting max_depth is one of the simplest ways to fight a decision tree's tendency to overfit, an unconstrained tree can always find a rule that perfectly separates the training data, whether or not that rule means anything for new data.