Sub topic 9
A First Real Model: Ridge Regression
This chapter builds the first real model for the housing project. It assumes you have loaded the California housing data, made the train/test split with random_state=42, and measured a baseline MAE with DummyRegressor. It also assumes you know why scaling belongs inside a pipeline, which the previous chapter covered.
Why start with a linear model
A linear model predicts the target as a weighted sum of the features:
prediction = intercept + w1 * x1 + w2 * x2 + ...
Training chooses the weights that make the predictions closest to the known prices. Linear models train fast, are easy to inspect, and give a stronger reference point than the baseline. If a more complex model later fails to beat one, the extra complexity is not worth it.
Ridge regression is a linear model with a penalty. Plain least squares can produce very large weights when features are correlated. In this dataset, AveRooms and AveBedrms move together. Ridge adds the sum of the squared weights, multiplied by alpha, to the training loss. This pulls the weights toward zero and makes them more stable.
| `alpha` | Effect |
|---|---|
| 0 | No penalty. Same as ordinary least squares. |
| Small (such as 1.0) | Mild shrinkage. A sensible starting value. |
| Large (such as 1000) | Strong shrinkage. The model drifts toward the baseline. |
Why scaling matters here
The penalty adds up the weights of all features, so it treats them equally. Features measured in different units need different weights to have the same effect. Population has values in the thousands, and MedInc has values around 3. Without scaling, the penalty falls unevenly on the features. StandardScaler rescales each feature to mean 0 and standard deviation 1, so the penalty is fair.
The scaler learns each feature's mean and standard deviation from the data it is fitted on. Putting it in a pipeline with the model means it is fitted on training data only, which avoids leakage.
Building and scoring the pipeline
The code below builds the pipeline and scores it with 5-fold cross-validation on the training set. Cross-validation is covered fully in the next chapter. For now, treat it as a way to get a more reliable score than a single fit would give.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
df = fetch_california_housing(as_frame=True).frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
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())Scikit-learn scorers follow the rule that higher is better. Error metrics are therefore returned as negative numbers, and the code negates the mean to report a normal MAE.
The result is about 0.53, in units of $100,000, so the typical error is roughly $53,000. The mean-predicting baseline scores around 0.89 on the test set, so Ridge is a clear improvement. Your exact figures may differ slightly between library versions.
Reading the fitted model
After fitting, the weights are available on the last pipeline step. Because the features are scaled, the weights can be compared with each other.
ridge.fit(X_train, y_train)
weights = ridge[-1].coef_
for name, w in sorted(zip(X.columns, weights), key=lambda p: abs(p[1]), reverse=True):
print(f"{name}: {w:.3f}")MedInc has the largest positive weight. Latitude and Longitude have large negative weights, but a straight line cannot represent how price varies across the state. This is the main limit of a linear model here, and it motivates gradient boosting later.
Common errors
- Scaling the full dataset before splitting. This leaks test statistics into training. Use a pipeline.
- Comparing weights of unscaled features. Their sizes depend on units, so they say little about importance.
- Reading a negative score as a bug. It is the sign convention for error scorers.
Exercise
Why is StandardScaler placed inside the pipeline instead of being applied to X before train_test_split?
Show answer
Scaling before the split computes the means and standard deviations from all rows, including the test rows, so test information influences training (leakage). Inside a pipeline, the scaler is fitted on training data only, and cross-validation refits it on each training fold.
Exercise
A cross-validation run reports scores of about -0.53 with scoring="neg_mean_absolute_error". What is the MAE, and what does it mean in dollars for this dataset?
Show answer
The MAE is 0.53. The target is in units of $100,000, so the typical prediction error is about $53,000.