⚡0 XP🔥0

Model Evaluation, Overfitting and Tuning

Lesson 7 of 11 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

Underfitting vs overfitting, the bias-variance trade-off, k-fold cross-validation, pipelines with ColumnTransformer, hyper-parameter tuning with GridSearchCV, and comparing models fairly.

Training a model is easy; knowing whether it is good, and making it better without fooling yourself, is the real skill.

Underfitting vs overfitting#

Underfitting (high bias) Good fit Overfitting (high variance)
Training score low high very high
Test score low high much lower than training
Cause model too simple right complexity model too complex / too little data
Fix more features, more complex model - more data, simpler model, regularisation, pruning
▶ Try it YourselfPython
Ctrl + Enter to run
Output
degree  1: train MSE 0.206   test MSE 0.199
degree  3: train MSE 0.052   test MSE 0.008
degree 15: train MSE 0.020   test MSE 0.998

Degree 1 (a straight line) underfits the sine wave; degree 15 hugs the noisy training points (lowest training error) but generalises worse than degree 3.

हिंदी में समझें

Underfitting - model इतना सरल है कि training data भी ठीक से नहीं सीख पाता। Overfitting - model ने training data रट लिया (noise समेत), इसलिए नए data पर गलत होता है - जैसे कोई छात्र सवाल समझने की बजाय पिछले साल के जवाब रट ले। लक्ष्य है बीच का संतुलन (bias-variance trade-off)।

Cross-validation - a more reliable score#

A single train/test split can be lucky or unlucky. k-fold cross-validation splits the data into k folds, trains k times (each time holding out a different fold) and averages the scores:

Fold 1:  [TEST] [train] [train] [train] [train]
Fold 2:  [train] [TEST] [train] [train] [train]
 ...
Fold 5:  [train] [train] [train] [train] [TEST]
→ score = average of the 5 test scores (plus their spread)
▶ Try it YourselfPython
Ctrl + Enter to run
Output
fold scores: [0.956 0.974 0.982 1.    0.982]
mean 0.979 +/- 0.014

Report the mean and the standard deviation - a model scoring 0.95 ± 0.01 is more trustworthy than one scoring 0.96 ± 0.05.

Pipelines and ColumnTransformer#

Real datasets mix numeric and categorical columns with missing values. A Pipeline chains preprocessing and the model into one object, so it is fitted correctly inside every cross-validation fold and is easy to save and deploy:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
pass rate in data: 0.55
5-fold accuracy: 0.825
predictions for 2 new students: [1 0]

Notice the new student from "Dewas" (a city never seen in training) and a missing attendance value are handled automatically.

Hyper-parameter tuning with GridSearchCV#

Parameters (weights, split thresholds) are learned from data. Hyper-parameters (max_depth, n_neighbors, C, learning_rate) are chosen by you. GridSearchCV tries every combination with cross-validation and keeps the best:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
best params: {'max_depth': 6, 'min_samples_leaf': 1, 'n_estimators': 50}
best CV F1 : 0.97
test F1    : 0.956
Common Mistake

Tune with cross-validation on the training data, and touch the test set once at the very end. If you keep checking the test score while tuning, you are tuning to the test set and your final number is optimistic.

Tip

For large search spaces, RandomizedSearchCV samples a fixed number of random combinations - often just as good and much faster.

A baseline first#

Always compare against a trivial baseline. If your fancy model barely beats "always predict the most common class", something is wrong:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
baseline accuracy: 0.627

Summary#

  • Compare training and test scores to diagnose underfitting vs overfitting.
  • Use k-fold cross-validation for reliable estimates (mean ± std).
  • Put preprocessing and the model in a Pipeline (ColumnTransformer for mixed columns) to avoid leakage.
  • Tune hyper-parameters with GridSearchCV/RandomizedSearchCV on training data; evaluate on the test set once; always beat a baseline.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Cross-validate three models

Using cross_val_score(model, X, y, cv=5) on the breast cancer data, compute the mean accuracy of: a scaled LogisticRegression(max_iter=1000), a DecisionTreeClassifier(random_state=0) and a RandomForestClassifier(n_estimators=100, random_state=0). Store them in a dict cv with keys "logreg", "tree", "forest" and print the name of the best model.

2

Grid search for KNN

Use GridSearchCV with a pipeline StandardScaler + KNeighborsClassifier on the wine data to search n_neighbors in [1, 3, 5, 7, 9, 11] and weights in ["uniform", "distance"] with cv=5. Store the fitted search in grid and print grid.best_params_.

Quick Quiz

Q1.

A model with 99% training accuracy and 70% test accuracy is...

Q2.

In 5-fold cross-validation, how many times is the model trained?

Q3.

What is a hyper-parameter?

Q4.

Why use a Pipeline when cross-validating?