Sub topic 3
Comparing Models with Cross-Validation
This chapter assumes you can load the California housing data, create X_train, X_test, y_train, and y_test, and understand pandas DataFrames and supervised learning.
Comparing models with cross-validation
A single validation split can make a model look unusually good or bad. Cross-validation gives a steadier estimate. It divides the training data into folds, trains on most folds, and validates on the remaining fold. It repeats this until every fold has been used for validation.
Scikit-learn returns negative values for loss metrics because it treats larger scores as better. Negate neg_mean_absolute_error to read the result as MAE.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
ridge = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(
ridge,
X_train,
y_train,
cv=5,
scoring="neg_mean_absolute_error",
)
print("Ridge CV MAE:", -scores.mean())The pipeline fits StandardScaler separately inside each fold. This prevents validation values from influencing preprocessing.
A stronger model: histogram gradient boosting
Histogram gradient boosting builds many small decision trees in sequence. Each tree corrects errors made by earlier trees. It can model non-linear relationships and does not require feature scaling.
from sklearn.ensemble import HistGradientBoostingRegressor
hgb = HistGradientBoostingRegressor(random_state=42)
scores = cross_val_score(
hgb,
X_train,
y_train,
cv=5,
scoring="neg_mean_absolute_error",
)
print("Gradient boosting CV MAE:", -scores.mean())Compare this MAE with Ridge using the same folds and metric. Choose the model with lower error, while also considering speed and interpretability.
Tuning hyperparameters with a grid search
A hyperparameter is a setting chosen before training. GridSearchCV evaluates every listed combination with cross-validation.
from sklearn.model_selection import GridSearchCV
param_grid = {
"learning_rate": [0.05, 0.1],
"max_leaf_nodes": [15, 31, 63],
}
search = GridSearchCV(
HistGradientBoostingRegressor(random_state=42),
param_grid,
cv=3,
scoring="neg_mean_absolute_error",
)
search.fit(X_train, y_train)
print(search.best_params_)
best_model = search.best_estimator_Scoring the final model on the test set
Use the test set once, after selecting and tuning the model.
from sklearn.metrics import mean_absolute_error, r2_score
pred = best_model.predict(X_test)
print("Test MAE:", mean_absolute_error(y_test, pred))
print("Test R2:", r2_score(y_test, pred))MAE is the average absolute error in units of $100,000. R² measures how much variation the model explains.
Which features matter
Permutation importance shuffles one feature and measures the resulting score drop. A larger drop means the fitted model relied more on that feature. This is model-specific importance, not proof of causation.
from sklearn.inspection import permutation_importance
result = permutation_importance(
best_model, X_test, y_test, n_repeats=5, random_state=42
)
for name, score in sorted(
zip(X.columns, result.importances_mean),
key=lambda item: item[1],
reverse=True,
):
print(f"{name}: {score:.3f}")Saving the pipeline and making predictions
Save the fitted model so you can predict later without retraining.
import joblib
joblib.dump(best_model, "house_price_model.joblib")
loaded = joblib.load("house_price_model.joblib")
print(loaded.predict(X_test.iloc[:3]))Save the environment's scikit-learn version with the model. Loading files created by a different version may fail or produce different results.
Exercise
Why must the test set remain unused during cross-validation and grid search?
Show answer
Repeatedly using it would influence model selection, so its final score would no longer be an honest estimate of performance on new data.