Sub topic 3
Cross-validation for a steadier estimate
Assume basic Python, NumPy, pandas, and train/test splitting. You should also know how fit, predict, and regression metrics work.
Cross-validation for a steadier estimate
A single train/test split can give a noisy score. Cross-validation repeatedly splits the training data into folds. Each fold becomes validation data once. The mean score is a steadier estimate.
Use cross_val_score for comparison. Keep the final test set untouched until model selection is complete.
Mixing numeric and categorical columns
A categorical feature contains labels such as a city. OneHotEncoder converts each label into numeric indicator columns. Use ColumnTransformer to apply different preparation steps to different columns.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"area": [50, 80, 120, 65, 95, 150, 70, 110],
"city": ["a", "b", "a", "c", "b", "c", "a", "b"],
"price": [150, 260, 330, 190, 300, 420, 200, 340],
})
X, y = df[["area", "city"]], df["price"]
preprocess = ColumnTransformer([
("num", StandardScaler(), ["area"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = make_pipeline(preprocess, Ridge(alpha=1.0))
scores = cross_val_score(model, X, y, cv=4, scoring="r2")
print(scores.mean())Overfitting and correlated features
Overfitting occurs when a model learns noise in its training data. Its training score is high, but its validation score is poor. Multicollinearity means that features contain overlapping information. It can make ordinary least squares coefficients large and unstable, even when predictions remain acceptable.
Ridge, Lasso, and ElasticNet
Regularization adds a penalty for large coefficients.
| Model | Penalty | Typical use |
|---|---|---|
| Ridge | Squared coefficients | Correlated features |
| Lasso | Absolute coefficients | Feature selection |
| ElasticNet | Both penalties | Mixed situations |
Choosing alpha
alpha controls penalty strength. RidgeCV searches values internally. GridSearchCV can compare models and preprocessing choices. Select it using training data and cross-validation, then evaluate once on the held-out test set.
Curved relationships
PolynomialFeatures adds powers such as \(x^2\). The resulting model is linear in its coefficients but can represent a curve. Combine it with Ridge when many generated features could cause overfitting.
Exercise
Why should StandardScaler be inside a cross-validation pipeline?
Show answer
The scaler must learn means and variances from each training fold only, preventing validation information from leaking into the fit.