Sub topic 2
A Baseline to Beat
This chapter assumes you know basic Python, pandas DataFrames, and the difference between features and a target. You should also have X_train, X_test, y_train, and y_test from a train/test split of the California housing data.
A baseline to beat
A baseline is a simple reference model. It tells us whether a more complex model learns useful patterns. For regression, a useful baseline always predicts the mean target value from the training set.
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error
baseline = DummyRegressor(strategy="mean")
baseline.fit(X_train, y_train)
baseline_pred = baseline.predict(X_test)
print("Baseline MAE:", mean_absolute_error(y_test, baseline_pred))Mean absolute error (MAE) is the average absolute difference between predictions and actual values. The target in this dataset is measured in hundreds of thousands of dollars, so an MAE of 0.5 means an average error of $50,000.
| Metric | Meaning |
|---|---|
| MAE | Average size of prediction errors |
| R² | Fraction of target variation explained by the model |
A real model should beat the baseline on data it did not use for training.
How information leaks from test data into training
Data leakage happens when training uses information that would be unavailable when making a real prediction. Leakage makes evaluation look better than real-world performance.
Common examples include:
- Scaling all rows before splitting the data.
- Choosing features after inspecting test-set performance.
- Using the target, or a value calculated from the target, as a feature.
- Repeatedly changing the model after checking the test score.
Keep the test set untouched until the final evaluation.
Scaling features inside a pipeline
Feature scaling changes numeric columns to comparable ranges. Ridge regression benefits from scaling because its regularization treats coefficients consistently.
A pipeline chains preprocessing and modeling. During cross-validation, it fits the scaler separately inside each training fold, preventing leakage.
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())A first real model: Ridge regression
Ridge regression is linear regression with a penalty on large coefficients. The alpha parameter controls the penalty. A larger value reduces coefficient size more strongly, which can reduce overfitting but also cause underfitting.
Exercise
Why should StandardScaler be inside the pipeline rather than fitted on the full dataset?
Show answer
The pipeline fits it only on each training portion, so information from validation or test rows cannot influence the learned scaling values.