Learning path: Predict a Number: Regression from Scratch to Regularisation · Step 6 of 6
Regularisation with Ridge and Lasso: Put a Price on Big Weights
The degree-4 insurance model overfits (train 0.876, test 0.754). Ridge shrinks every weight and lifts the test score to 0.843; Lasso switches off all but 40 of 495 columns and reaches 0.862.
What you will learn
- Explain regularisation as MSE plus alpha times the size of the weights
- Use Ridge (L2) to shrink every weight and fix an overfitting model
- Use Lasso (L1) to switch useless columns off and read which ones survive
- Choose alpha by the score on unseen data, not the train score
Before you start
- Polynomial Regression, Overfitting and Underfitting
- Regression Metrics: MAE, RMSE, R-squared
Imagine a shopping spree with no limit. You grab the biggest, most expensive things: the jacket, the shoes, the phone, the watch. Now add a budget. You can still buy everything you need, but every big item costs you more, so you pick smaller versions.
That's regularisation. The items are the model's weights, and the budget is a price on big weights. Same data, same pipeline; only the model at the end changes.
The model that overfits
In Polynomial Regression, Overfitting and Underfitting, the degree-4 insurance model overfit: 495 columns, train 0.876, test 0.754. Here's the same pipeline, with the model at the end as a parameter so you can swap it:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, PolynomialFeatures
from sklearn.linear_model import LinearRegression, Ridge, Lasso
df = pd.read_csv("insurance.csv")
X = df.drop(columns="charges")
y = df["charges"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
num_cols = X.select_dtypes(include="number").columns
cat_cols = X.select_dtypes(exclude="number").columns
def poly_model(reg, degree=4):
num = Pipeline([("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())])
cat = Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(drop="first",
handle_unknown="ignore"))])
preprocess = ColumnTransformer([("num", num, num_cols),
("cat", cat, cat_cols)])
return Pipeline([("preprocess", preprocess),
("poly", PolynomialFeatures(degree=degree)),
("reg", reg)])
A small helper prints the train score, the test score and the total size of the weights (the sum of their absolute values). With kept=True it also counts the columns whose weight is not zero.
def report(model, kept=False):
w = model.named_steps["reg"].coef_
tr = model.score(X_train, y_train)
te = model.score(X_test, y_test)
out = f"train {tr:.3f} test {te:.3f}"
out += f" weight {abs(w).sum():.0f}"
if kept:
out += f" kept {(w != 0).sum()}/{len(w)}"
print(out)
plain = poly_model(LinearRegression())
plain.fit(X_train, y_train)
report(plain)
train 0.876 test 0.754 weight 278054
The weights add up to 278,054. Big weights, big swings, poor test score.
A new score to push down
A model always pushes a score down. So far that was the MSE. Regularisation adds a price on the weights:
cost = MSE + alpha × (size of the weights)
- The MSE is how wrong the guesses are.
alphais how strict the price is.alpha = 0means no price at all: plain linear regression.- A bigger
alphameans smaller weights and a simpler model. Too big, and the model underfits.
The two classic choices differ only in how they measure "size":
| Model | Size of the weights | Effect |
|---|---|---|
| Ridge (L2) | sum of w2 | Big weights cost a lot, so every weight shrinks |
| Lasso (L1) | sum of |w| | Useless weights go all the way to 0, switched off |
Ridge shrinks every weight
Four values of alpha. Only the model at the end changes:
for alpha in [1, 10, 100, 1000]:
model = poly_model(Ridge(alpha=alpha))
model.fit(X_train, y_train)
print(f"{alpha:>4}", end=" ")
report(model)
1 train 0.875 test 0.767 weight 239820
10 train 0.871 test 0.807 weight 160807
100 train 0.841 test 0.843 weight 90610
1000 train 0.721 test 0.714 weight 46439
As alpha grows, the total weight falls: 239,820, 160,807, 90,610, 46,439. At alpha=100 the test score is 0.843, up from 0.754, and train and test are now close together. At alpha=1000 the price is too strict: both scores drop to about 0.72 and the model underfits.
Lasso switches columns off
Same loop with Lasso. max_iter=50000 gives it enough steps to finish its search on 495 columns.
for alpha in [10, 50, 100, 300]:
lasso = Lasso(alpha=alpha, max_iter=50000)
model = poly_model(lasso)
model.fit(X_train, y_train)
print(f"{alpha:>4}", end=" ")
report(model, kept=True)
10 train 0.868 test 0.812 weight 100024 kept 235/495
50 train 0.853 test 0.852 weight 46878 kept 69/495
100 train 0.847 test 0.862 weight 40486 kept 40/495
300 train 0.828 test 0.857 weight 32894 kept 17/495
More alpha, fewer columns: 235, 69, 40, 17. At alpha=100, Lasso uses only 40 of the 495 columns and gives the best test score so far, 0.862.
Which columns survive?
Fit Lasso with alpha=100, rebuild the column names from the pipeline, and list the four biggest weights that aren't zero:
lasso = Lasso(alpha=100, max_iter=50000)
model = poly_model(lasso).fit(X_train, y_train)
cols = model["preprocess"].get_feature_names_out()
names = model["poly"].get_feature_names_out(cols)
w = pd.Series(model["reg"].coef_, index=names)
big = w[w != 0].abs().sort_values(ascending=False)
print(big.head(4).round().astype(int).to_string())
cat__smoker_yes 22926
num__bmi cat__smoker_yes 8267
num__age 3231
num__bmi cat__smoker_yes^3 2232
Smoker, bmi for smokers, and age. That's the same story as the price tags in Linear Regression in scikit-learn, and Lasso found it by itself out of 495 columns. (These weights are not dollars per unit: the number columns were scaled first.)
The same five columns under three models
models = {"LinearRegression": poly_model(LinearRegression()),
"Ridge(100)": poly_model(Ridge(alpha=100)),
"Lasso(100)": model}
pick = ["num__age", "num__bmi", "num__bmi cat__smoker_yes",
"num__age^2", "num__bmi^2 num__children"]
rows = {}
for label, m in models.items():
m.fit(X_train, y_train)
s = pd.Series(m["reg"].coef_, index=names)
rows[label] = s[pick].round(0)
print(pd.DataFrame(rows))
LinearRegression Ridge(100) Lasso(100)
num__age 2393.0 1345.0 3231.0
num__bmi 1143.0 703.0 113.0
num__bmi cat__smoker_yes 4714.0 1877.0 8267.0
num__age^2 2692.0 615.0 405.0
num__bmi^2 num__children -852.0 -50.0 0.0
Ridge shrinks all five: bmi × smoker_yes goes from 4,714 to 1,877. Lasso works differently. It sets bmi² × children to exactly 0, and it lets the strong columns, bmi × smoker_yes and age, stay big.
Same model, three penalties
| Model | Penalty | Test R2 | Weights |
|---|---|---|---|
| LinearRegression | none | 0.754 | total 278,054 |
| Ridge(alpha=100) | L2, sum of w2 | 0.843 | total 90,610, all shrunk |
| Lasso(alpha=100) | L1, sum of |w| | 0.862 | 40 of 495 columns kept |
One more name to know: ElasticNet(alpha=..., l1_ratio=0.5) mixes both penalties, some shrinking and some switching off.
Common mistakes
- Picking alpha by the train score. Train always prefers a small alpha. Pick alpha by the score on data the model hasn't seen. This lesson uses the test score; once you've met cross-validation, pick alpha on validation folds and keep the test set for the final check.
- Dropping the scaler when you swap the model. This pipeline already scales the number columns before
PolynomialFeatures, as in the last lesson. Swap only theregstep and keep everything else. - Making alpha too big. Ridge at 1000 drops to test 0.714: underfitting.
- Reading Lasso's weights as dollar price tags. They're on scaled inputs.
Quick recap
| Idea | Code | Insurance, degree 4 |
|---|---|---|
| Price on big weights | MSE + alpha × size of weights | alpha = 0 is plain regression |
| Ridge shrinks every weight | Ridge(alpha=100) | test 0.754 to 0.843 |
| Lasso switches columns off | Lasso(alpha=100, max_iter=50000) | 40/495 kept, test 0.862 |
| Too strict underfits | Ridge(alpha=1000) | train 0.721, test 0.714 |
| One line to swap | poly_model(Ridge(...)) | same pipeline, new model |
Try it yourself
Fit Ridge and Lasso on this degree-4 insurance model and report the test RMSE of each, next to a DummyRegressor baseline (see Regression Metrics). Which alpha gives the lowest RMSE?
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.