Sub topic 3
Overfitting and Underfitting
Assume you know basic Python, pandas-style tables, statistics, and supervised learning. This chapter focuses on judging whether a model will work on unseen data.
Overfitting and underfitting
Overfitting happens when a model learns training details, including noise, instead of general patterns. Its training score is high, but its validation score is lower. Underfitting happens when the model is too simple to capture useful patterns. Both training and validation scores remain low.
| Pattern | Training score | Validation score |
|---|---|---|
| Underfitting | Low | Low |
| Good fit | High | Similar and high |
| Overfitting | Very high | Much lower |
Cross-validation for reliable estimates
Cross-validation repeatedly divides the training data into folds. Each fold becomes validation data once. The average score gives a more stable estimate than one random validation split.
Tuning hyperparameters
A hyperparameter is a setting chosen before training, such as logistic regression’s regularization strength C. Tuning tries several values with cross-validation. Keep the test set separate so it remains an unbiased final check.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
search = GridSearchCV(
model, {"clf__C": [0.1, 1, 10]}, cv=5, scoring="f1"
)
search.fit(X_train, y_train)
print("CV F1:", search.best_score_)
print("Test F1:", f1_score(y_test, search.predict(X_test)))
new_row = X_test.iloc[[0]]
print("Prediction:", search.predict(new_row))One final evaluation on the test set
Report the test score once after selecting the model and settings. Do not tune again after seeing it. If the test score is much lower than the cross-validation score, investigate leakage, drift, or overfitting.
Making predictions on new data
New rows must have the same columns and compatible meanings as the training data. The pipeline applies scaling and prediction in the same order used during training.
Monitoring, drift and retraining
After deployment, monitor prediction quality when labels arrive, input distributions, missing values, and important business outcomes. Data drift means new inputs differ from training inputs. Retrain when performance or data quality falls below an agreed threshold, then repeat the held-out evaluation process.
Exercise
A model has a training F1 of 0.99 and a cross-validation F1 of 0.72. What is the likely problem?
Show answer
The model is probably overfitting. Reduce complexity, add regularization, improve data quality, or collect more representative training data.