Sub topic 9
A First Real Model: Ridge Regression
This chapter fits a linear model to the California housing data and checks that it beats the baseline. It assumes you have read the earlier chapters of this project: the train/test split with random_state=42, the mean-predicting DummyRegressor baseline, and the idea of wrapping a scaler and a model in a pipeline. You should also be comfortable with NumPy arrays and pandas Series.
What a linear model does
A linear regression model predicts the target as a weighted sum of the features plus a constant:
prediction = intercept + w1 * x1 + w2 * x2 + ... + w8 * x8Each weight w is a coefficient. Training picks the coefficients that make the squared differences between predictions and true values as small as possible on the training set. For house prices, the model learns a number for each of the eight features, such as median income, house age and latitude. The prediction is then a single multiplication-and-addition step.
Linear models are a good first real model for three reasons.
- They train in milliseconds, so you can iterate quickly.
- Each coefficient has a direct reading: "one unit more of this feature changes the prediction by this much, holding the others fixed".
- They set a stronger bar than the baseline. If a more complex model later fails to beat a linear one, something is wrong.
Why Ridge instead of plain linear regression
Ordinary least squares has no restraint. When features are correlated, as AveRooms and AveBedrms are, the fit can assign large positive weight to one and large negative weight to the other. Those weights nearly cancel on the training data but swing wildly on new data. Small changes in the training set then produce very different coefficients.
Ridge regression adds a penalty on the size of the coefficients. It minimizes:
sum of squared errors + alpha * (w1² + w2² + ... + w8²)The alpha parameter sets the strength of the penalty:
alpha = 0is ordinary least squares.- A larger
alphapulls every coefficient toward zero, which makes the model simpler and more stable. It also adds bias, because the model can no longer fit the training data as tightly. - The intercept is not penalized.
This trade is the core of regularization: you accept slightly worse training fit in exchange for coefficients that are less sensitive to noise.
Why scaling is required here
The penalty adds up squared coefficients, so it treats all coefficients as comparable. They are not comparable if the features use different units. In this dataset MedInc ranges from about 0.5 to 15, while Population ranges into the tens of thousands. A feature measured in large units needs only a tiny coefficient to have an effect, so the penalty barely touches it. A feature in small units needs a large coefficient, so the penalty hits it hard. The result depends on the units you happened to choose.
StandardScaler fixes this by subtracting each feature's mean and dividing by its standard deviation, so every feature has mean 0 and variance 1. Because the scaler is inside the pipeline, it learns those means and standard deviations from the training data only. This is the leakage protection from the previous chapter.
Fitting the model
This code is self-contained. It reloads the data, repeats the split from the earlier chapter, and fits the pipeline on the training set.
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error
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))
ridge.fit(X_train, y_train)
train_mae = mean_absolute_error(y_train, ridge.predict(X_train))
print("Ridge MAE on the training set:", train_mae)The training MAE should land around 0.53, compared with about 0.9 for the mean baseline. Remember the unit: the target is in $100,000, so 0.53 means an average miss of roughly $53,000.
A training-set score is optimistic, because the model has already seen those rows. It is enough to confirm the model learned something. Do not use it to choose between models. The next chapter covers cross-validation, which gives a fairer comparison. Do not score on X_test yet either. The test set is reserved for the final evaluation.
Reading the coefficients
A fitted pipeline lets you index into its steps. ridge[-1] is the last step, the Ridge object, which holds coef_ and intercept_.
coefs = pd.Series(ridge[-1].coef_, index=X.columns).sort_values()
print(coefs.round(3))
print("Intercept:", round(ridge[-1].intercept_, 3))Because the features were standardized, each coefficient is the change in predicted price (in $100,000) for a one-standard-deviation increase in that feature. That makes coefficients comparable across features. You should see these patterns:
MedInchas a large positive coefficient. Higher neighborhood income goes with higher prices.LatitudeandLongitudehave large negative coefficients. Prices fall as you move north and east, away from the southern coast.- The intercept is close to the mean of the training target, because the scaled features average zero.
Read these as associations in this model, not as causes. Latitude and longitude also interact (the expensive areas are coastal clusters, not a straight gradient), and a linear model can only draw one flat tilt across the map. This is the main reason the gradient boosting chapter improves on Ridge.
Watching alpha change the fit
You can see regularization work by fitting the same pipeline at several alpha values and tracking the size of the coefficients. This sketch uses cross_val_score to get a validation error for each setting, and the next chapter explains how it works. Here, treat it as a function that returns an honest score without touching the test set.
import numpy as np
from sklearn.model_selection import cross_val_score
for alpha in [0.01, 1, 100, 1_000, 10_000]:
model = make_pipeline(StandardScaler(), Ridge(alpha=alpha))
cv_mae = -cross_val_score(
model, X_train, y_train, cv=5, scoring="neg_mean_absolute_error"
).mean()
model.fit(X_train, y_train)
size = np.linalg.norm(model[-1].coef_)
print(f"alpha={alpha:>8} CV MAE={cv_mae:.3f} coefficient norm={size:.3f}")Expect two trends. The coefficient norm shrinks steadily as alpha grows. The CV MAE is nearly flat for small alpha, then gets worse once the penalty is strong enough to squash useful coefficients such as MedInc.
On this dataset the curve is flat for a wide range, because there are 16,000 training rows and only eight features. Regularization helps most when you have many features, few rows, or strongly correlated columns. Here Ridge with alpha=1 performs about the same as ordinary linear regression. That is a normal result, not a bug.
Common errors and limits
- Skipping the scaler. Ridge still runs without it, but the penalty then depends on feature units, and your coefficients cannot be compared. Always scale before a penalized linear model.
- Scaling outside the pipeline. Calling
scaler.fit_transform(X)on the full data before splitting leaks test-set statistics into training. Keep the scaler inside the pipeline. - Reading coefficients from an unscaled model. Coefficients on raw features reflect units. A tiny coefficient on
Populationsays nothing about its importance. - Choosing alpha by looking at the test set. This turns the test set into a second validation set, and your final score becomes optimistic. Use cross-validation, or
RidgeCV, on the training data. - Expecting non-linear patterns. Ridge fits one plane through the data. It cannot learn that prices jump near the coast or flatten at high incomes. It can also predict negative prices, and the target in this dataset is capped at 5.0 ($500,000), which the model does not know.
- Outliers in the features.
AveRooms,AveBedrmsandAveOccuphave extreme values for a few districts. Standardizing does not remove them, and squared error lets them pull the fit toward themselves.
Where Ridge fits in the project
Ridge gives you a second reference point. The baseline sets the floor at an MAE of about 0.9, and Ridge shows that the features carry real linear signal at about 0.53. Any later model must beat 0.53 to justify its extra complexity. The next chapter formalizes how to compare the two fairly with cross-validation.
Exercise
You fit Ridge(alpha=1.0) on raw, unscaled features, and the coefficient for Population is tiny while the coefficient for AveBedrms is large. A colleague concludes that AveBedrms matters far more than Population. Why is that conclusion unreliable, and what two changes would make coefficients comparable?
Show answer
Population is measured in thousands while AveBedrms is close to 1, so a small coefficient on Population can have as much effect on the prediction as a large coefficient on AveBedrms. The coefficient size reflects units, and Ridge's penalty also treats the features unequally because of those units. Put a StandardScaler in front of Ridge in a pipeline, so all features have mean 0 and standard deviation 1. Fit the pipeline on the training set only. Coefficients are then per standard deviation and can be compared.
Exercise
As alpha grows very large, for example 10 million, what happens to the coefficients and to the predictions of a Ridge pipeline?
Show answer
The coefficients shrink toward zero, but the intercept is not penalized. The model's predictions therefore approach a constant equal to the mean of the training target, which is the same as the DummyRegressor baseline. Ridge interpolates between ordinary least squares at alpha near 0 and the baseline at very large alpha.