Module 3, topic 26, week 13, Thursday
Regularization: Ridge and Lasso regression
Why a model is trained with a penalty for large weights, what Ridge, Lasso and the elastic net do to the weights, how the strength alpha is chosen, and a complete project on a real data file of houses: from reading the file to comparing the models.
Lesson notebook
The lesson as a Jupyter notebook: the explanations, the whole project on Housing.csv cell by cell, and the fourteen solved problems.
topic-26-regularization-ridge-and-lasso.ipynb, 67 KB
Practice notebook
The same project on Housing.csv in thirteen steps, from reading the file to comparing the four models, with a hint and a hidden solution for each step.
topic-26-practice.ipynb, 20 KB
Data file: the houses
545 houses with 13 columns: the data of the lesson, the solved problems and the practice. A public data set (Housing Prices Dataset, Kaggle, public domain).
Housing.csv, 29 KB
Introduction: keeping the weights small
The sixth lesson of Module 3. In Topic 23 you met overfitting: a model that follows its training rows so closely that it does worse on new rows. The cures named there were more rows, fewer features or a simpler model. This lesson adds a fourth cure, and the most widely used one: regularization. The model keeps all its features, but it is trained with a rule that keeps its weights small.
The lesson has two halves. The first explains the idea and the three kinds of regularization for linear models: Ridge, Lasso and elastic net, with their formulas and the logic behind them. The second half is a complete machine learning project on a real data file, Housing.csv: every step from reading the file to comparing the models, in the order in which it is done in practice. It uses everything of Topics 22 to 25.
You need: linear regression, its weights and its loss (Topic 22), the train/test split, overfitting and cross-validation (Topic 23), scaling (Topic 24), outliers and encoding (Topic 25).
What you will learn
- 1.Why a model with large weights is a warning sign, and what regularization does about it
- 2.The three penalties: Ridge (L2), Lasso (L1) and elastic net, their formulas and their logic
- 3.Why Ridge makes weights small and Lasso makes some of them exactly zero
- 4.What the strength
alphadoes, and how to choose it with cross-validation - 5.Why the features must be scaled before regularization
- 6.The whole workflow of a project: look, clean, encode, split, scale, train, tune, compare
- 7.When regularization helps a lot, and when it changes almost nothing
| Word | Meaning |
|---|---|
| regularization | training with a penalty for large weights, to keep the model simple |
| penalty | the extra term that is added to the loss |
| Ridge regression | linear regression with the L2 penalty: the sum of the squared weights |
| Lasso regression | linear regression with the L1 penalty: the sum of the absolute weights |
| elastic net | linear regression with a mix of both penalties |
alpha | the strength of the penalty: 0 is no regularization, a large value is a strong one |
l1_ratio | in an elastic net: the share of the L1 penalty in the mix |
| shrinking | weights moving towards 0 under a penalty |
| sparse model | a model in which many weights are exactly 0 |
| hyperparameter | a number that you choose before training, such as alpha (Topic 21) |
1Why regularization?
1.1Overfitting, seen in the weights
A linear regression chooses the weights that make the error on the training data as small as possible. Nothing else counts. When the model has many features and not many rows, it uses its freedom to follow the accidents of the training rows, and it often does so with very large weights: one feature gets a huge positive weight, another a huge negative one, and the two almost cancel each other. On the training rows the result fits beautifully. On new rows a small change in a feature is multiplied by a huge weight, and the prediction jumps.
Large weights are therefore a sign of a model that trusts its training data too much. Part 7 will show a model on the housing data whose largest weight is many times as large as it should be, and whose test score is negative.
1.2The idea: make large weights cost something
Regularization changes what the training is asked to do. The loss gets a second term:
Now the model must balance two wishes. A large weight is still allowed, but only if it reduces the error by more than it costs. A weight that only follows noise is not worth its price and stays small.
- The error pulls the weights towards the values that fit the training data best.
- The penalty pulls every weight towards 0.
- A number called alpha says how strong the penalty is.
The model that comes out fits the training data a little worse than plain linear regression. That is intended. It gives up a little of the training score to become steadier on new data: less variance for a little more bias, the tradeoff of Topic 23.
1.3What regularization is not
- It does not add data and it does not remove columns from the table.
- It does not make a weak model strong. If the features carry little information, no penalty will find more.
- It is not always needed. A model with few features and many rows hardly overfits, and then there is little to gain. The project of this lesson will show that honestly.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0; (b) a little worse; (c) overfitting.
The penalty grows with the size of the weights, so it pulls each of them towards 0. A model that may not use large weights cannot follow every accident of its training rows, so it fits them a little worse. In return it is steadier on new rows: less overfitting.
2Three penalties: Ridge, Lasso, elastic net
The three methods differ only in how they measure "large weights". The model itself is the same in all of them: , with features. The intercept is never penalised. In the formulas the strength of the penalty is written , the Greek letter alpha; in code it is alpha.
2.1Plain linear regression
The mean squared error of Topic 22, and nothing else.
2.2Ridge regression: the L2 penalty
The penalty is the sum of the squared weights. It is called the L2 penalty, after the L2 norm of Topic 15.
The logic: squaring makes a large weight very expensive and a small weight almost free. A weight of 10 costs 100; a weight of 1 costs 1; a weight of 0.1 costs 0.01. So Ridge attacks the large weights first and pushes all weights to be small and of similar size. But the cost of a small weight is so tiny that pushing it all the way to 0 is never worth it: Ridge makes weights small, never exactly zero. All features stay in the model.
2.3Lasso regression: the L1 penalty
The penalty is the sum of the absolute values of the weights: the L1 penalty, after the L1 norm of Topic 15. "Lasso" is short for "least absolute shrinkage and selection operator".
The logic: without the square, every step towards 0 saves the same amount, whether the weight is large or small. A weight of 10 costs 10, a weight of 0.1 costs 0.1, and reducing either of them by 0.1 saves exactly 0.1. So for a feature that helps only a little, the saving is larger than the loss all the way down, and the weight ends at exactly 0. The feature has left the model. Lasso selects features: it does feature selection (Topic 24) by itself, during training.
2.4Elastic net: both together
A mix of the two penalties. The number , called l1_ratio in scikit-learn, says how much of the mix is L1:
- : only the L1 penalty. The model is a Lasso.
- : only the L2 penalty. The model is a Ridge.
- : half and half.
The logic: Lasso has a weakness. When several features are strongly correlated with each other (the multicollinearity of Topic 24), it keeps one of them almost at random and drops the others. Ridge handles such groups well: it gives the correlated features similar weights. The elastic net takes feature selection from Lasso and the steady handling of correlated features from Ridge.
(scikit-learn writes these losses with a few fixed factors, for example one half in front of the L2 part of the elastic net, and Ridge uses the sum of the squared errors in the place of their mean. The logic is the same. One consequence matters in practice: the alpha of Ridge and the alpha of Lasso are on different scales and cannot be compared. A usual alpha for Ridge is 1, 10 or 100; a usual alpha for Lasso is 0.01 or 0.1.)
2.5The penalties by hand
Two models for the same data, each with two weights:
| Weights | MSE on the training data | |
|---|---|---|
| Model A | 6 and | 4.0 |
| Model B | 3 and | 4.6 |
Without a penalty, Model A wins: its error is smaller. Now the two penalties:
The Ridge loss with :
Model B wins clearly. Its error is a little larger, but its weights are much smaller. The Lasso loss with :
Model B wins here too, by less. The elastic net loss with and takes half of each penalty:
Model B wins again, and the two losses lie between those of Lasso and Ridge, as the penalty itself does. And with a very weak penalty, , in the Ridge loss:
Model A wins again: the penalty is too weak to matter. Alpha decides how much the size of the weights counts against the error.
2.6Why Ridge shrinks and Lasso cuts
In the simplest case, one feature that is scaled and stands alone, the effect of each penalty on a weight can be written in one line. Let be the weight that plain linear regression would choose.
Ridge divides. Lasso subtracts. Take two weights, 4 and 0.5, and :
Dividing makes every weight smaller by the same share, and a number that is divided never becomes 0. Subtracting takes the same amount from every weight, and a weight that is smaller than this amount is gone. That is the whole difference between the two methods.
Ridge: every weight is divided
smaller, but never 0
Lasso: every weight loses the same amount
weights between −1 and 1 become 0
2.7The picture with the circle and the diamond
There is a second way to see it. A penalty is the same as a budget: the weights may be anything, as long as their penalty stays below a limit. For two weights, the budget of Ridge ( below a limit) is a circle, and the budget of Lasso ( below a limit) is a diamond with its corners on the axes.
The ovals in the picture are the error: the dot in their middle is where plain linear regression would put the weights, and every oval further out is a larger error. The model takes the point of its budget that touches the smallest oval.
Ridge: the budget is a circle
both weights small, neither is 0
Lasso: the budget is a diamond
a corner: weight 2 is exactly 0
A circle is round everywhere, so the oval touches it at some ordinary point where both weights are small and neither is 0. A diamond has corners, and the corners stick out: the oval very often touches a corner first. At a corner one of the weights is exactly 0. With many features the diamond has many corners and edges, and many weights become 0.
2.8Side by side
| Linear regression | Ridge | Lasso | Elastic net | |
|---|---|---|---|---|
| Penalty | none | squared weights (L2) | absolute weights (L1) | a mix of both |
| What happens to the weights | free | all become smaller | some become exactly 0 | smaller, and some 0 |
| Selects features | no | no | yes | yes |
| Correlated features | unstable weights | shares the weight among them | keeps one, drops the others | keeps groups together |
| Numbers to choose | none | alpha | alpha | alpha and l1_ratio |
| In scikit-learn | LinearRegression() | Ridge(alpha=1.0) | Lasso(alpha=1.0) | ElasticNet(alpha=1.0, l1_ratio=0.5) |
2.9When to use which
- Ridge: the usual first choice. Use it when you believe that most features carry some information, and when features are correlated with each other.
- Lasso: when you believe that only some of many features matter, or when you want a short model that is easy to explain: the features with a weight of 0 can be left out.
- Elastic net: when there are many features and groups of correlated ones, or when Lasso behaves unsteadily. It costs a second number to tune.
- Plain linear regression: when there are few features and many rows, and the training and the test score are close together. Then there is nothing to cure.
2.10Two rules before any code
1. Scale the features first. The penalty looks at the size of the weights, and the size of a weight depends on the unit of its feature (Topic 24). A feature in square feet has a tiny weight and would hardly be penalised; the same feature in thousands of square feet has a large weight and would be punished hard. Only after scaling does the penalty treat all features alike. For plain linear regression scaling was optional; for regularization it is required.
2. Alpha is chosen, not learned. The weights are learned from the data. Alpha is a hyperparameter (Topic 21): you set it before training. The right value is found by trying several values and comparing them with cross-validation on the training data (Topic 23). The test data is not used for this choice.
One weight in the simplest case. Choose the weight a model without a penalty would have, and the strength of the penalty.
Ridge: 1.5 / (1 + 1) = 0.75
Lasso: 0.5 (1 taken away)
Ridge makes the weight smaller by a share, so it never reaches 0. Lasso takes a fixed amount, and a weight that is not larger than that amount is gone.
Plain linear regression, Ridge, Lasso or elastic net?
1 of 8
12 features and 5,000 rows. The training score is 0.71, the test score 0.70.
Try it yourself
Show a hint
Show the solution
Answer: (a) 25; (b) 7; (c) 4.5; (d) 2.7; (e) 0.
3The project: the data and its preparation
From here on the lesson is one project, in the order of real work: look at the data, clean it, encode it, split it, scale it, train a first model, then improve it. Every code block is a cell that continues from the cells above it, like a notebook.
The task: predict the price of a house.
3.1Step 1: read the file and look at it
Housing.csv is a public data set of 545 houses.
import pandas as pd
df = pd.read_csv("Housing.csv")
print(df.shape)
print(df.head(3).T)Output
(545, 13)
0 1 2
price 13300000 12250000 12250000
area 7420 8960 9960
bedrooms 4 4 3
bathrooms 2 4 2
stories 3 4 2
mainroad yes yes yes
guestroom no no no
basement no no yes
hotwaterheating no no no
airconditioning yes yes no
parking 2 3 2
prefarea yes no yes
furnishingstatus furnished furnished semi-furnished| Column | Meaning |
|---|---|
price | the price of the house: the target |
area | the area of the house |
bedrooms | the number of bedrooms |
bathrooms | the number of bathrooms |
stories | the number of floors |
mainroad | is the house on a main road? yes or no |
guestroom | does it have a guest room? |
basement | does it have a basement? |
hotwaterheating | does it have hot water heating? |
airconditioning | does it have air conditioning? |
parking | the number of parking places |
prefarea | is it in a preferred area of the town? |
furnishingstatus | furnished, semi-furnished or unfurnished |
The data file: Housing.csv
545 houses, 13 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
3.2Step 2: check the columns
Are there missing values or repeated rows (Topic 11)? Which columns are text?
print(df.isna().sum().sum())
print(df.duplicated().sum())
print(df.select_dtypes(exclude="number").columns.tolist())Output
0 0 ['mainroad', 'guestroom', 'basement', 'hotwaterheating', 'airconditioning', 'prefarea', 'furnishingstatus']
No missing value and no repeated row. Seven columns are text and must be encoded.
Are there columns without information (Topic 24)? There is no identification number, no name and no constant column here: every column describes the house. Nothing is dropped.
3.3Step 3: look for outliers
print(df[["price", "area"]].describe().round(0))Output
price area count 545.0 545.0 mean 4766729.0 5151.0 std 1870440.0 2170.0 min 1750000.0 1650.0 25% 3430000.0 3600.0 50% 4340000.0 4600.0 75% 5740000.0 6360.0 max 13300000.0 16200.0
The two columns with continuous measurements are the price and the area (Topic 25). The IQR rule on both:
for name in ["price", "area"]:
q1 = df[name].quantile(0.25)
q3 = df[name].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)
print(name, upper, (df[name] > upper).sum())Output
price 9205000.0 15 area 10500.0 12
The rule marks 15 prices and 12 areas. Now the question of Topic 25: mistakes, or real extreme values? The largest house has 16,200 units of area, about three times the typical house, and the most expensive one costs 13.3 million, about three times the median. Nothing is impossible here, and nothing looks like a typing mistake. These are simply the largest and most expensive houses of the town: real values, so they stay.
3.4Step 4: a target in handy numbers
The prices are numbers in the millions. That is no problem for the score, but it makes every weight and every error a number with seven digits, and it matters for Lasso, whose alpha is compared with the size of the target. So the price is turned into millions:
df["price"] = df["price"] / 1000000
print(df["price"].describe().round(2))Output
count 545.00 mean 4.77 std 1.87 min 1.75 25% 3.43 50% 4.34 75% 5.74 max 13.30 Name: price, dtype: float64
A house now costs between 1.75 and 13.3 (million). This is only a change of unit: it uses no information from other rows, so it is done before the split.
3.5Step 5: encode the text columns
Six columns have the values yes and no. Each becomes 1 and 0 (Topic 25), in one loop:
yes_no = ["mainroad", "guestroom", "basement", "hotwaterheating", "airconditioning", "prefarea"]
for name in yes_no:
df[name] = df[name].map({"no": 0, "yes": 1})
print(df[yes_no].head(3))Output
mainroad guestroom basement hotwaterheating airconditioning prefarea 0 1 0 0 0 1 1 1 1 0 0 0 1 0 2 1 0 1 0 0 1
The seventh text column has three values:
print(df["furnishingstatus"].value_counts())Output
furnishingstatus semi-furnished 227 unfurnished 178 furnished 140 Name: count, dtype: int64
Unfurnished, semi-furnished, furnished: these have an order, so the column gets ordinal encoding with numbers in that order:
df["furnishingstatus"] = df["furnishingstatus"].map({"unfurnished": 0, "semi-furnished": 1, "furnished": 2})
print(df["furnishingstatus"].value_counts().sort_index())Output
furnishingstatus 0 178 1 227 2 140 Name: count, dtype: int64
Every column is a number now.
3.6Step 6: a look at the correlations
print(df.corr()["price"].round(2).sort_values())Output
hotwaterheating 0.09 basement 0.19 guestroom 0.26 mainroad 0.30 furnishingstatus 0.30 prefarea 0.33 bedrooms 0.37 parking 0.38 stories 0.42 airconditioning 0.45 bathrooms 0.52 area 0.54 price 1.00 Name: price, dtype: float64
Every feature moves with the price in the expected direction. The area and the number of bathrooms are the strongest; hotwaterheating is the weakest. In Topic 24 the weakest feature would now be a candidate for dropping. Here all twelve stay, on purpose: Part 5 will let Lasso decide which features are worth keeping.
3.7Step 7: split
from sklearn.model_selection import train_test_split
X = df.drop(columns=["price"])
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)Output
(436, 12) (109, 12)
Change it and run: change test_size to 0.3 and run: 164 houses become test data.
df.drop(columns=["price"]) is the table without the target: all twelve features.
3.8Step 8: scale
The scaler is fitted on the training data and applied to both parts (Topic 24). For the models of this lesson this step is not optional.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(X_train_scaled[:2].round(2))Output
[[ 0.38 0.06 1.54 2.59 0.41 -0.47 -0.75 -0.23 1.5 0.37 -0.55 1.41] [ 0.93 0.06 1.54 -0.91 0.41 -0.47 1.34 -0.23 1.5 2.71 -0.55 0.08]]
The data is ready: 436 houses for training, 109 for the test, twelve features on the same scale.
Try it yourself
furnishingstatus get the numbers 0, 1 and 2? (c) Why is scaling required for the models of this lesson?Show a hint
Show the solution
Answer: (a) they are real values; (b) its values have an order; (c) the penalty measures the weights.
The most expensive houses are simply expensive houses, and the model must know them. Unfurnished, semi-furnished and furnished stand in an order, so numbers in that order say something true. And a penalty for large weights is only fair when the size of a weight means the same for every feature, which is the case after scaling.
4A first model, without regularization
Every project needs a starting point. Here it is plain linear regression.
from sklearn.linear_model import LinearRegression
linear = LinearRegression()
linear.fit(X_train_scaled, y_train)
print(round(linear.score(X_train_scaled, y_train), 3))
print(round(linear.score(X_test_scaled, y_test), 3))Output
0.685 0.649
A training score of 0.685 and a test score of 0.649. Read them as in Topic 23: the gap is small (less than 0.04), so this model does not overfit much. The scores are moderate because the twelve columns do not tell everything about a house, not because the model memorised its rows. Keep that in mind: regularization cures overfitting, and there is little of it here.
The weights:
for name, weight in zip(X.columns, linear.coef_):
print(name, round(weight, 3))Output
area 0.519 bedrooms 0.059 bathrooms 0.523 stories 0.348 mainroad 0.128 guestroom 0.089 basement 0.188 hotwaterheating 0.151 airconditioning 0.362 parking 0.193 prefarea 0.267 furnishingstatus 0.158
The features are standardised, so the weights can be compared (Topic 24): one standard deviation more area adds about 0.52 million to the price, and the area, the bathrooms, the air conditioning and the number of floors matter most. All weights are of a reasonable size. No weight is huge.
Try it yourself
area is 0.519. For which change of the area does the price rise by about 0.52 million?Show a hint
Show the solution
Answer: (a) 0.036; (b) no; (c) one standard deviation more area.
A gap of less than 0.04 is small: the model does almost as well on new houses as on its training houses. After standard scaling one unit of a feature is one standard deviation, so a weight says how much the price (in millions) changes for one standard deviation of the feature.
5Ridge, Lasso and elastic net on the housing data
5.1Ridge
Ridge is used exactly like LinearRegression. The strength of the penalty is alpha.
from sklearn.linear_model import Ridge
ridge = Ridge(alpha=10)
ridge.fit(X_train_scaled, y_train)
print(round(ridge.score(X_train_scaled, y_train), 3))
print(round(ridge.score(X_test_scaled, y_test), 3))Output
0.685 0.648
Change it and run: change 10 to 500 and run: both scores fall, because the penalty is now too strong.
Almost the same scores as the plain model. Now several strengths, to see what alpha does. Every line shows alpha, the training score and the test score:
for alpha in [0.1, 1, 10, 100, 1000]:
model = Ridge(alpha=alpha)
model.fit(X_train_scaled, y_train)
print(alpha, round(model.score(X_train_scaled, y_train), 3), round(model.score(X_test_scaled, y_test), 3))Output
0.1 0.685 0.649 1 0.685 0.649 10 0.685 0.648 100 0.678 0.631 1000 0.511 0.434
- With a small alpha (0.1, 1, 10) the model is practically the plain linear regression.
- With both scores begin to fall.
- With the penalty is so strong that the model can no longer follow the data: both scores are low. This is underfitting (Topic 23), made by too much regularization.
Alpha is a dial between two mistakes: too small and the model is free to overfit, too large and it is not allowed to learn.
What the strong penalty did to the weights, next to the plain model:
strong = Ridge(alpha=1000)
strong.fit(X_train_scaled, y_train)
for name, a, b in zip(X.columns, linear.coef_, strong.coef_):
print(name, round(a, 3), round(b, 3))Output
area 0.519 0.212 bedrooms 0.059 0.117 bathrooms 0.523 0.212 stories 0.348 0.152 mainroad 0.128 0.103 guestroom 0.089 0.087 basement 0.188 0.076 hotwaterheating 0.151 0.042 airconditioning 0.362 0.176 parking 0.193 0.132 prefarea 0.267 0.116 furnishingstatus 0.158 0.104
The first number of every line is the weight of the plain model, the second the weight under the strong penalty. The large weights shrank most: the area from 0.519 to 0.212, the bathrooms from 0.523 to 0.212. One weight even grew, bedrooms: the number of bedrooms moves together with the area and the bathrooms, and Ridge shares the weight among features that belong together (Part 2). And no weight is 0. That is Ridge: it makes the weights small and similar, and it keeps every feature.
5.2Lasso
from sklearn.linear_model import Lasso
lasso = Lasso(alpha=0.05)
lasso.fit(X_train_scaled, y_train)
print(round(lasso.score(X_train_scaled, y_train), 3))
print(round(lasso.score(X_test_scaled, y_test), 3))Output
0.681 0.629
The alpha of Lasso is on another scale than the alpha of Ridge (Part 2): here 0.05 is already a noticeable penalty. Several strengths, this time with a fourth number: how many weights are not 0.
for alpha in [0.001, 0.01, 0.05, 0.1, 0.3]:
model = Lasso(alpha=alpha)
model.fit(X_train_scaled, y_train)
kept = (model.coef_ != 0).sum()
print(alpha, round(model.score(X_train_scaled, y_train), 3), round(model.score(X_test_scaled, y_test), 3), kept)Output
0.001 0.685 0.649 12 0.01 0.685 0.646 12 0.05 0.681 0.629 12 0.1 0.667 0.603 12 0.3 0.549 0.47 7
model.coef_ != 0 is True for every weight that is not 0, and sum() counts them. Up to all twelve features stay. With only seven are left. Which ones?
strong = Lasso(alpha=0.3)
strong.fit(X_train_scaled, y_train)
for name, weight in zip(X.columns, strong.coef_):
print(name, round(weight, 3))Output
area 0.439 bedrooms 0.0 bathrooms 0.426 stories 0.151 mainroad 0.0 guestroom 0.0 basement 0.0 hotwaterheating 0.0 airconditioning 0.266 parking 0.059 prefarea 0.099 furnishingstatus 0.037
Change it and run: change 0.3 to 0.5 and run: more weights are 0.
Five weights are exactly 0: bedrooms, mainroad, guestroom, basement and hotwaterheating. Lasso has thrown them out of the model, and it kept the seven it found most useful. That is feature selection done by the training itself.
Look at the price, though: with the test score fell to 0.47. On this data the five features were not useless. Each carried a little information, and removing them costs. Lasso can select features; whether the shorter model is good enough is still judged by the score.
5.3Elastic net
ElasticNet has two numbers: alpha, the strength, and l1_ratio, the share of the L1 penalty.
from sklearn.linear_model import ElasticNet
elastic = ElasticNet(alpha=0.05, l1_ratio=0.5)
elastic.fit(X_train_scaled, y_train)
print(round(elastic.score(X_train_scaled, y_train), 3))
print(round(elastic.score(X_test_scaled, y_test), 3))Output
0.684 0.638
Change it and run: set l1_ratio=1 and run: the scores are those of Lasso(alpha=0.05).
With a strong penalty, , the mix shows its two sides. Every line shows l1_ratio, the test score and the number of weights that are not 0:
for ratio in [0.1, 0.5, 0.9]:
model = ElasticNet(alpha=0.3, l1_ratio=ratio)
model.fit(X_train_scaled, y_train)
print(ratio, round(model.score(X_test_scaled, y_test), 3), (model.coef_ != 0).sum())Output
0.1 0.613 12 0.5 0.557 11 0.9 0.489 9
The closer l1_ratio is to 1, the more the model behaves like a Lasso: more weights become 0. Close to 0 it behaves like a Ridge and keeps them all.
The twelve weights of the housing model. Choose a model and move alpha.
Training score 0.685, test score 0.648, weights that are not 0: 12 of 12.
Under Ridge every weight gets smaller as alpha grows, and all twelve features stay. With a very large alpha both scores fall: underfitting.
Try it yourself
Ridge with alpha=500 on the scaled training data and print its training score, then its test score, each rounded to 3 decimals. Is that alpha too strong?Show a hint
model = Ridge(alpha=500), model.fit(X_train_scaled, y_train), then model.score for each part. Both scores are clearly lower than with alpha=10: the penalty is too strong.Show the solution
from sklearn.linear_model import Ridge
model = Ridge(alpha=500)
model.fit(X_train_scaled, y_train)
print(round(model.score(X_train_scaled, y_train), 3))
print(round(model.score(X_test_scaled, y_test), 3))Output
0.603 0.533
Try it yourself
Lasso with alpha=0.2 and print how many of its twelve weights are not 0.Show a hint
model = Lasso(alpha=0.2), model.fit(X_train_scaled, y_train), then print((model.coef_ != 0).sum()).Show the solution
from sklearn.linear_model import Lasso
model = Lasso(alpha=0.2)
model.fit(X_train_scaled, y_train)
print((model.coef_ != 0).sum())Output
11
Try it yourself
ElasticNet with alpha=0.3 and l1_ratio=0.9, a mix that is almost a Lasso. Print its test score, rounded to 3 decimals, then the number of weights that are not 0.Show a hint
model = ElasticNet(alpha=0.3, l1_ratio=0.9), model.fit(X_train_scaled, y_train), then print(round(model.score(X_test_scaled, y_test), 3)) and print((model.coef_ != 0).sum()).Show the solution
from sklearn.linear_model import ElasticNet
model = ElasticNet(alpha=0.3, l1_ratio=0.9)
model.fit(X_train_scaled, y_train)
print(round(model.score(X_test_scaled, y_test), 3))
print((model.coef_ != 0).sum())Output
0.489 9
6Choosing alpha with cross-validation
The loops above printed test scores to show what alpha does. For choosing alpha they must not be used: the test data would then take part in building the model (Topic 23). The choice is made with cross-validation on the training data.
For every alpha, cross_val_score trains the model five times on four fifths of the training data and judges it on the remaining fifth. The mean of the five scores is the judgement of that alpha.
from sklearn.model_selection import cross_val_score
for alpha in [0.1, 1, 10, 100, 1000]:
scores = cross_val_score(Ridge(alpha=alpha), X_train_scaled, y_train, cv=5)
print(alpha, round(scores.mean(), 3))Output
0.1 0.647 1 0.647 10 0.648 100 0.646 1000 0.458
The best mean belongs to , by a hair. The same for Lasso:
for alpha in [0.001, 0.01, 0.05, 0.1, 0.3]:
scores = cross_val_score(Lasso(alpha=alpha), X_train_scaled, y_train, cv=5)
print(alpha, round(scores.mean(), 3))Output
0.001 0.647 0.01 0.647 0.05 0.644 0.1 0.632 0.3 0.515
The two smallest values share the best score; is taken. And for the elastic net, with l1_ratio=0.5:
for alpha in [0.001, 0.01, 0.05, 0.1, 0.3]:
scores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5)
print(alpha, round(scores.mean(), 3))Output
0.001 0.647 0.01 0.647 0.05 0.648 0.1 0.644 0.3 0.601
Here is the best.
(scikit-learn has ready tools that run such a loop for you: RidgeCV, LassoCV and ElasticNetCV. They do what these cells do.)
6.1The four models side by side
Now, and only now, the test data is used: once for each finished model.
models = {
"linear": LinearRegression(),
"ridge": Ridge(alpha=10),
"lasso": Lasso(alpha=0.01),
"elastic net": ElasticNet(alpha=0.05, l1_ratio=0.5),
}
for name, model in models.items():
model.fit(X_train_scaled, y_train)
print(name, round(model.score(X_train_scaled, y_train), 3), round(model.score(X_test_scaled, y_test), 3))Output
linear 0.685 0.649 ridge 0.685 0.648 lasso 0.685 0.646 elastic net 0.684 0.638
A dictionary holds the four models under their names, and the loop trains and judges one after the other (Topic 5).
| Model | Training score | Test score |
|---|---|---|
| linear regression | 0.685 | 0.649 |
| Ridge, | 0.685 | 0.648 |
| Lasso, | 0.685 | 0.646 |
| elastic net, | 0.684 | 0.638 |
Four models, practically one score. This is an honest and important result. The plain model was not overfitting, so there was nothing for regularization to cure. Twelve features and 436 training rows leave a linear model little room to memorise. Regularization is a medicine for a particular illness, and a healthy model does not get better from it. A small loss, as with the elastic net here, is normal: the penalty takes away a little of the fit.
So when does it help? When the model has much more freedom than the data can support. Part 7 builds such a model from the same houses.
Try it yourself
Ridge and cross_val_score are imported. The loop of the lesson found alpha=10. Look closer: compare the Ridge alphas 20, 50 and 200 with a 5-fold cross-validation on the training data, and print every alpha with its mean score, rounded to 3 decimals.Show a hint
for alpha in [20, 50, 200]: with scores = cross_val_score(Ridge(alpha=alpha), X_train_scaled, y_train, cv=5) and print(alpha, round(scores.mean(), 3)). A value between 10 and 100 is a little better than both.Show the solution
for alpha in [20, 50, 200]:
scores = cross_val_score(Ridge(alpha=alpha), X_train_scaled, y_train, cv=5)
print(alpha, round(scores.mean(), 3))Output
20 0.649 50 0.65 200 0.631
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.1; (b) the training data; (c) once, at the end.
The mean score 0.66 is the best, so alpha is 0.1. Cross-validation splits the training data into folds and never touches the test data. The finished model is then judged on the test data a single time.
7When regularization really matters: many features
7.1Giving the model more freedom
A linear model cannot multiply two features (Topic 24). Perhaps a large area is worth more in a preferred part of the town, or air conditioning matters more in a house with many floors. Such products of two features can be created by hand, or all at once with PolynomialFeatures. With degree=2 it creates, from twelve features, every feature, every square of a feature and every product of two features:
from sklearn.preprocessing import PolynomialFeatures
maker = PolynomialFeatures(degree=2, include_bias=False)
X_train_many = maker.fit_transform(X_train)
X_test_many = maker.transform(X_test)
print(X_train_many.shape, X_test_many.shape)Output
(436, 90) (109, 90)
Ninety features in the place of twelve, for the same 436 houses. (include_bias=False leaves out a column of ones that the model does not need.) The new features are scaled like the old ones:
scaler_many = StandardScaler()
X_train_many = scaler_many.fit_transform(X_train_many)
X_test_many = scaler_many.transform(X_test_many)
linear_many = LinearRegression()
linear_many.fit(X_train_many, y_train)
print(round(linear_many.score(X_train_many, y_train), 3))
print(round(linear_many.score(X_test_many, y_test), 3))Output
0.79 0.65
The training score jumped from 0.685 to 0.790, and the test score did not move: 0.650. The gap is now 0.14. The model used its seventy-eight new features to follow the training rows, and nothing of that carried over to new houses. This is overfitting, and now there is something to cure.
7.2The three regularized models on ninety features
Every line: the name, the training score, the test score and the number of weights that are not 0.
models = {
"linear": LinearRegression(),
"ridge": Ridge(alpha=100),
"lasso": Lasso(alpha=0.05),
"elastic net": ElasticNet(alpha=0.1, l1_ratio=0.5),
}
for name, model in models.items():
model.fit(X_train_many, y_train)
kept = (model.coef_ != 0).sum()
print(name, round(model.score(X_train_many, y_train), 3), round(model.score(X_test_many, y_test), 3), kept)Output
linear 0.79 0.65 90 ridge 0.742 0.668 90 lasso 0.728 0.658 24 elastic net 0.726 0.659 37
| Model on 90 features | Training score | Test score | Features kept |
|---|---|---|---|
| linear regression | 0.790 | 0.650 | 90 |
| Ridge, | 0.742 | 0.668 | 90 |
| Lasso, | 0.728 | 0.658 | 24 |
| elastic net, | 0.726 | 0.659 | 37 |
Now the pattern of the theory is there:
- All three regularized models have a lower training score and a higher test score than the plain model. They gave up fit on the training rows and gained on new houses.
- Ridge kept all ninety features with small weights and has the best test score, 0.668, above every model of Part 6.
- Lasso reached almost the same with 24 of the 90 features: it set 66 weights to exactly 0.
- The elastic net lies between the two, as its penalty does.
7.3Even more freedom
With degree=3 the same twelve features become 454, more than the 436 training houses:
maker = PolynomialFeatures(degree=3, include_bias=False)
scaler_huge = StandardScaler()
X_train_huge = scaler_huge.fit_transform(maker.fit_transform(X_train))
X_test_huge = scaler_huge.transform(maker.transform(X_test))
print(X_train_huge.shape)Output
(436, 454)
The plain model first. Its test score is printed in another way this time: the cell only asks whether it is below 0.
linear_huge = LinearRegression()
linear_huge.fit(X_train_huge, y_train)
print(round(linear_huge.score(X_train_huge, y_train), 3))
print(linear_huge.score(X_test_huge, y_test) < 0)Output
0.948 True
A training score of 0.948, and a test score below 0: worse than always answering with the mean price. (On the computer on which this lesson was written the test score is about . With more features than rows the weights of such a model rest on tiny differences in the calculation, so the exact number can differ a little from one computer to the next. That is itself a sign of how unsteady the model is.) With more features than rows the model can fit its training data almost perfectly, and what it learned is noise.
The same 454 features with a penalty:
models = {
"ridge": Ridge(alpha=300),
"lasso": Lasso(alpha=0.05),
"elastic net": ElasticNet(alpha=0.1, l1_ratio=0.5),
}
for name, model in models.items():
model.fit(X_train_huge, y_train)
kept = (model.coef_ != 0).sum()
print(name, round(model.score(X_train_huge, y_train), 3), round(model.score(X_test_huge, y_test), 3), kept)Output
ridge 0.773 0.659 449 lasso 0.748 0.652 47 elastic net 0.746 0.653 69
Ordinary, usable models: Ridge reaches 0.659, Lasso reaches 0.652 with 47 features and 407 weights at 0, and the elastic net reaches 0.653 with 69 features. (Ridge shows 449 weights, not 454: five of the new columns are 0 in every training row, each a product of three yes/no features that never occur together in one house, and a column that never changes gets the weight 0.)
The size of the weights tells the story of Part 1. The cell prints the largest weight of the first model of the lesson, then whether the largest weight of the plain model on 454 features is above 10, then the largest weight of the Ridge model on the same features:
print(round(abs(linear.coef_).max(), 2))
print(abs(linear_huge.coef_).max() > 10)
print(round(abs(models["ridge"].coef_).max(), 2))Output
0.52 True 0.06
The largest weight of the first model was 0.52. The plain model on 454 features has weights above 10 (about 17 here), more than twenty times as large. The Ridge model on the same features has no weight above 0.06.
Ridge
the weights shrink together
Lasso
one weight after another becomes 0
Elastic net
first together, then to 0
The picture shows the twelve weights of the housing model for a whole range of alphas. Under Ridge all lines sink towards 0 together and never reach it. Under Lasso the lines hit 0 one after another and stay there: the weak features leave first, the area and the bathrooms last.
7.4What the project showed
| 12 features | 90 features | 454 features | |
|---|---|---|---|
| linear regression: training / test | 0.685 / 0.649 | 0.790 / 0.650 | 0.948 / below 0 |
| Ridge: test | 0.648 | 0.668 | 0.659 |
| Lasso: test (features kept) | 0.646 (12) | 0.658 (24) | 0.652 (47) |
| Elastic net: test (features kept) | 0.638 (12) | 0.659 (37) | 0.653 (69) |
12 features
90 features
454 features
- Few features, enough rows: the plain model is fine, and regularization changes nothing.
- Many features: the plain model overfits, and regularization brings a real gain.
- More features than rows: the plain model is useless, and regularization makes it work.
- The more freedom a model has, the more it needs a penalty. That is why regularization is part of nearly every large model in machine learning.
Try it yourself
X_train_many and X_test_many hold the ninety scaled features, and Ridge is imported. Train a Ridge with alpha=30 on them and print its training score, then its test score, each rounded to 3 decimals.Show a hint
model = Ridge(alpha=30), model.fit(X_train_many, y_train), then model.score(X_train_many, y_train) and model.score(X_test_many, y_test).Show the solution
model = Ridge(alpha=30)
model.fit(X_train_many, y_train)
print(round(model.score(X_train_many, y_train), 3))
print(round(model.score(X_test_many, y_test), 3))Output
0.764 0.668
8The workflow, step by step
The order of this project is the order of most projects with tables of data.
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, kinds of columns | 545 houses, 13 columns, 7 of them text |
| 2. Check | missing values, repeated rows, columns without information | nothing to repair, nothing to drop |
| 3. Outliers | find them, decide: mistake or real | real houses: kept |
| 4. Encode | text to numbers | six yes/no columns as 1 and 0, one ordinal column |
| 5. Split | training and test data | 436 and 109 houses |
| 6. Scale | fit on the training data, transform both | StandardScaler: required for regularization |
| 7. First model | a simple starting point | LinearRegression: 0.649 |
| 8. Improve | other models, more features, regularization | Ridge, Lasso, elastic net |
| 9. Tune | choose hyperparameters with cross-validation | alpha |
| 10. Judge | the test score of the finished models, once | the table of Part 6 |
Steps 1 to 4 need no learning from the rows and are done on the whole table. From step 6 on, everything that learns is fitted on the training data (Topics 24 and 25).
Try it yourself
Show a hint
Show the solution
Answer: (a) the split; (b) encoding yes and no as 1 and 0; (c) the scaler and the models.
Looking, checking and encoding by a fixed rule learn nothing from the rows, so they are done on the whole table. The scaler learns means and standard deviations and the models learn weights: both learn from the rows, so both see the training data only.
9Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Regularization on features that are not scaled. | The penalty punishes a feature for its unit, not for its importance. | Scale first, with a scaler fitted on the training data. |
| Choosing alpha by the test score. | The test data takes part in building the model, and its score is no longer honest. | Cross-validation on the training data. |
| "A larger alpha is always safer." | Too much penalty gives underfitting: both scores fall. | Try several values, from very small to very large. |
| Using the same alpha for Ridge and for Lasso. | The two are on different scales. | Tune each model by itself. |
| Expecting regularization to raise every score. | It cures overfitting. A model that does not overfit has nothing to gain. | Compare the training and the test score first. |
| Expecting Ridge to remove features. | Ridge makes weights small, never exactly 0. | Lasso or elastic net for selection. |
| Reading a weight of 0 in a Lasso as "this feature has no effect in reality". | Lasso may drop one of two correlated features, although both matter. | It only says: the model does well without it. |
| Judging overfitting by the training score alone. | A high training score is exactly what an overfitted model has. | Look at the gap to the test score. |
Fitting the scaler or PolynomialFeatures on all rows before the split. | Data leakage (Topic 24). | Split first; fit on the training data. |
| Forgetting that is plain linear regression. | Then the penalty is switched off. | Use LinearRegression when no penalty is wanted. |
10Solved problems
Fourteen problems. The first three are short and solved by hand. Problems 4 to 14 are one project on Housing.csv, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with a few choices made differently: another split, and one-hot encoding for the furnishing.
Problem 1: The two penalties by hand
A model has the weights 2, and 0.5. Calculate its L2 penalty and its L1 penalty (without alpha).
Idea. L2 is the sum of the squared weights, L1 the sum of their absolute values (Part 2).
Why: the sign of a weight does not matter for either penalty: only its size. In L2 the weight alone gives 9 of the 13.25: squaring makes the largest weight count most.
Problem 2: Which model wins?
Model A has a training MSE of 2.0 and the weights 5 and 5. Model B has a training MSE of 2.5 and the weights 2 and 1. Which model has the smaller Ridge loss with ? And with ?
Idea. (Part 2).
Why: with Model B wins clearly: its small weights outweigh its larger error. With Model A wins by a little: the penalty is too weak. The choice of alpha decides which model the training prefers.
Problem 3: Ridge divides, Lasso subtracts
In the simplest case of Part 2, three weights without a penalty are 6, 2 and 0.4. What do they become with under Ridge and under Lasso?
Idea. Ridge: . Lasso: , and 0 when is smaller than (Part 2).
Why: Ridge halves every weight and keeps all three. Lasso takes 1 from each: the large weight hardly notices, and the small one is gone. A feature with a weight of 0 has left the model.
Problem 4: Read and check
Read Housing.csv. Print its shape, the number of missing values and the number of repeated rows.
Idea. The first two steps of the workflow: look and check (Part 3).
import pandas as pd
df = pd.read_csv("Housing.csv")
print(df.shape)
print(df.isna().sum().sum(), df.duplicated().sum())Output
(545, 13) 0 0
Why: before any model, know what is in the table. Nothing is missing and nothing is repeated, so no cleaning is needed here.
Problem 5: The target and the yes/no columns
Turn the price into millions and encode the six yes/no columns as 1 and 0. Print the first three rows of price, mainroad and basement.
Idea. A change of unit, and map with a dictionary in a loop (Part 3).
df["price"] = df["price"] / 1000000
for name in ["mainroad", "guestroom", "basement", "hotwaterheating", "airconditioning", "prefarea"]:
df[name] = df[name].map({"no": 0, "yes": 1})
print(df[["price", "mainroad", "basement"]].head(3))Output
price mainroad basement 0 13.30 1 0 1 12.25 1 0 2 12.25 1 1
Why: both steps follow fixed rules and learn nothing from the rows, so they are done on the whole table before the split.
Problem 6: One-hot encoding for the furnishing
The lesson gave furnishingstatus numbers in order. Encode it this time with one-hot encoding, with drop_first=True. Print the names of the last three columns.
Idea. pd.get_dummies (Topic 25). With three categories and one dropped, two columns arrive.
df = pd.get_dummies(df, columns=["furnishingstatus"], drop_first=True, dtype=int)
print(df.columns.tolist()[-3:])Output
['prefarea', 'furnishingstatus_semi-furnished', 'furnishingstatus_unfurnished']
Why: both encodings are defensible for this column. One-hot encoding does not assume that the step from unfurnished to semi-furnished is as large as the next one. furnished, the first category in the alphabet, is the reference.
Problem 7: Split
Make X and y, and split them with test_size=0.25 and random_state=7. Print the shapes of X_train and X_test.
Idea. The split comes before everything that learns from the rows (Part 3).
from sklearn.model_selection import train_test_split
X = df.drop(columns=["price"])
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)
print(X_train.shape, X_test.shape)Output
(408, 13) (137, 13)
Why: thirteen features now, because the furnishing became two columns. A quarter of the houses is put aside for the test.
Problem 8: Scale
Scale the features with a StandardScaler that is fitted on the training data. Print the shapes of the two scaled arrays.
Idea. fit_transform on the training data, transform on the test data (Topic 24).
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(X_train_scaled.shape, X_test_scaled.shape)Output
(408, 13) (137, 13)
Why: the penalty of Ridge and Lasso looks at the size of the weights, and only on scaled features do the sizes mean the same for every feature.
Problem 9: The starting point
Train a LinearRegression and print its training score and its test score.
Idea. Every project starts with a simple model to compare with (Part 4).
from sklearn.linear_model import LinearRegression
linear = LinearRegression()
linear.fit(X_train_scaled, y_train)
print(round(linear.score(X_train_scaled, y_train), 3))
print(round(linear.score(X_test_scaled, y_test), 3))Output
0.695 0.639
Why: 0.695 and 0.639. The gap is about 0.06: a little overfitting, not much. These two numbers are what the next models are measured against.
Problem 10: Ridge
Train a Ridge with alpha=10 and print its two scores.
Idea. Used exactly like LinearRegression, with the strength of the penalty as alpha (Part 5).
from sklearn.linear_model import Ridge
ridge = Ridge(alpha=10)
ridge.fit(X_train_scaled, y_train)
print(round(ridge.score(X_train_scaled, y_train), 3))
print(round(ridge.score(X_test_scaled, y_test), 3))Output
0.695 0.637
Why: practically the scores of the plain model. With thirteen features and 408 training houses there is little overfitting for the penalty to remove.
Problem 11: Lasso and the weights that become 0
Train a Lasso with alpha=0.3. Print its test score, and the names of the features whose weight is 0.
Idea. coef_ == 0 marks the features that Lasso removed (Part 5).
from sklearn.linear_model import Lasso
lasso = Lasso(alpha=0.3)
lasso.fit(X_train_scaled, y_train)
print(round(lasso.score(X_test_scaled, y_test), 3))
print(X.columns[lasso.coef_ == 0].tolist())Output
0.436 ['guestroom', 'basement', 'hotwaterheating', 'furnishingstatus_semi-furnished', 'furnishingstatus_unfurnished']
Why: a strong Lasso removed five of the thirteen features, and the test score fell far below the 0.639 of the plain model. X.columns[...] with a list of True and False keeps the names where it is True (Topic 10). The alpha is too large for this data: the next problem looks for a better one.
Problem 12: Choosing alpha
Compare the Lasso alphas 0.001, 0.01, 0.05 and 0.1 with a 5-fold cross-validation on the training data. Print every alpha with its mean score.
Idea. Alpha is chosen with cross-validation, never with the test data (Part 6).
from sklearn.model_selection import cross_val_score
for alpha in [0.001, 0.01, 0.05, 0.1]:
scores = cross_val_score(Lasso(alpha=alpha), X_train_scaled, y_train, cv=5)
print(alpha, round(scores.mean(), 3))Output
0.001 0.668 0.01 0.669 0.05 0.666 0.1 0.653
Why: the mean score is best at and falls for the larger values. A small alpha is right here, which fits the picture: the model hardly overfits, so it needs hardly any penalty.
Problem 13: Elastic net
Train an ElasticNet with alpha=0.05 and l1_ratio=0.5. Print its test score and the number of weights that are not 0.
Idea. A mix of both penalties: l1_ratio is the share of L1 (Part 5).
from sklearn.linear_model import ElasticNet
elastic = ElasticNet(alpha=0.05, l1_ratio=0.5)
elastic.fit(X_train_scaled, y_train)
print(round(elastic.score(X_test_scaled, y_test), 3))
print((elastic.coef_ != 0).sum())Output
0.628 12
Why: twelve of the thirteen weights are left. The L1 half of the penalty removed one feature, and the L2 half kept the others small but alive.
Problem 14: All models side by side
Train the four models (linear, Ridge with alpha 10, Lasso with alpha 0.01, elastic net with alpha 0.05) and print the name and the test score of each.
Idea. A dictionary of models and one loop (Part 6).
models = {
"linear": LinearRegression(),
"ridge": Ridge(alpha=10),
"lasso": Lasso(alpha=0.01),
"elastic net": ElasticNet(alpha=0.05, l1_ratio=0.5),
}
for name, model in models.items():
model.fit(X_train_scaled, y_train)
print(name, round(model.score(X_test_scaled, y_test), 3))Output
linear 0.639 ridge 0.637 lasso 0.635 elastic net 0.628
Why: the four test scores lie within about 0.01 of each other. With another split and another encoding the project gives the same answer as the lesson: on these twelve or thirteen features the plain model is enough, and regularization is the tool to keep ready for models with more freedom.
11Practice
Sixteen problems. The first three are solved on paper. Problems 4 to 16 are one project in Python on Housing.csv, the file of the lesson (the whole table): from reading the file to comparing the models. Under every problem there is a hint and a solution.
11.1Group A: by hand
- 1.A model has the weights 4, and 2. (a) What is its L2 penalty? (b) What is its L1 penalty?
Show a hint
Squares for L2, absolute values for L1.Show one possible solution
Answer: (a) 21; (b) 7.
- 2.Model A has an MSE of 3.0 and an L1 penalty of 10. Model B has an MSE of 3.4 and an L1 penalty of 4. (a) What is the Lasso loss of A with ? (b) Of B? (c) Which model does the Lasso prefer?
Show a hint
Lasso loss = MSE + alpha times the L1 penalty.Show one possible solution
Answer: (a) 4.0; (b) 3.8; (c) Model B.
(c) Model B has the smaller loss: its error is a little larger, but its weights are much smaller.
- 3.(a) Which method can set weights to exactly 0: Ridge or Lasso? (b) A model has a training score of 0.95 and a test score of 0.55. Should alpha be made larger or smaller? (c) With a very large alpha both scores are low. What is this called?
Show a hint
L1 cuts, L2 shrinks. A large gap between the two scores is overfitting.Show one possible solution
Answer: (a) Lasso; (b) larger; (c) underfitting.
(a) The L1 penalty of Lasso removes features; Ridge only makes weights small. (b) The model overfits, so it needs a stronger penalty: a larger alpha. (c) Too much penalty keeps the model from learning: underfitting.
11.2Group B: one project in Python
The same workflow as in the lesson, on the same file, with one change: the split is test_size=0.3 with random_state=1. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created.
Steps 4 to 8: look and prepare
Read the file, look for outliers, change the unit of the price, encode the text columns.
- 4.Read
Housing.csvintodf. Print the shape, then the number of missing values.Show a hint
df = pd.read_csv("Housing.csv"), thenprint(df.shape)andprint(df.isna().sum().sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("Housing.csv") print(df.shape) print(df.isna().sum().sum())Output
(545, 13) 0
- 5.Calculate the upper limit of the IQR rule for
area. Print the limit, then the number of areas above it. (They are real houses and stay in the data.) This step continues from Step 4.Show a hint
q1 = df["area"].quantile(0.25), the same with0.75forq3, thenupper = q3 + 1.5 * (q3 - q1). The number of areas above it is(df["area"] > upper).sum().Show one possible solution
Python, continues from the cells aboveq1 = df["area"].quantile(0.25) q3 = df["area"].quantile(0.75) upper = q3 + 1.5 * (q3 - q1) print(upper) print((df["area"] > upper).sum())Output
10500.0 12
- 6.Turn
priceinto millions: divide it by 1,000,000. Print the smallest and the largest price on one line. This step continues from Step 4.Show a hint
df["price"] = df["price"] / 1000000, thenprint(df["price"].min(), df["price"].max()).Show one possible solution
Python, continues from the cells abovedf["price"] = df["price"] / 1000000 print(df["price"].min(), df["price"].max())Output
1.75 13.3
- 7.Encode the six yes/no columns as 1 (yes) and 0 (no). The list of their names is in the editor. Print how many houses have air conditioning. This step continues from Step 6.
Show a hint
A loop:for name in yes_no:and inside itdf[name] = df[name].map({"no": 0, "yes": 1}). The number of houses is the sum of the column:print(df["airconditioning"].sum()).Show one possible solution
Python, continues from the cells aboveyes_no = ["mainroad", "guestroom", "basement", "hotwaterheating", "airconditioning", "prefarea"] for name in yes_no: df[name] = df[name].map({"no": 0, "yes": 1}) print(df["airconditioning"].sum())Output
172
- 8.Encode
furnishingstatusin its order: unfurnished 0, semi-furnished 1, furnished 2. Print the mean of the column, rounded to 2 decimals. This step continues from Step 7.Show a hint
df["furnishingstatus"] = df["furnishingstatus"].map({"unfurnished": 0, "semi-furnished": 1, "furnished": 2}), thenprint(round(df["furnishingstatus"].mean(), 2)).Show one possible solution
Python, continues from the cells abovedf["furnishingstatus"] = df["furnishingstatus"].map({"unfurnished": 0, "semi-furnished": 1, "furnished": 2}) print(round(df["furnishingstatus"].mean(), 2))Output
0.93
Steps 9 to 11: split, scale, a first model
The split, the scaler fitted on the training data, and plain linear regression as the starting point.
- 9.Make
X(all columns withoutprice) andy(price). Split them withtest_size=0.3andrandom_state=1. Print the shapes ofX_trainandX_teston one line. This step continues from Step 8.Show a hint
from sklearn.model_selection import train_test_split,X = df.drop(columns=["price"]),y = df["price"], thenX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1).Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import train_test_split X = df.drop(columns=["price"]) y = df["price"] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) print(X_train.shape, X_test.shape)Output
(381, 12) (164, 12)
- 10.Scale the features with a
StandardScalercalledscalerintoX_train_scaledandX_test_scaled. Print the largest value of the scaled test data, rounded to 2 decimals. This step continues from Step 9.Show a hint
from sklearn.preprocessing import StandardScaler,scaler.fit_transform(X_train)for the training data andscaler.transform(X_test)for the test data, thenprint(round(X_test_scaled.max(), 2)). If your number differs, checktest_size=0.3andrandom_state=1in Step 9.Show one possible solution
Python, continues from the cells abovefrom sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) print(round(X_test_scaled.max(), 2))Output
4.49
- 11.Train a
LinearRegressioncalledlinearon the scaled training data. Print the training score, then the test score, each rounded to 3 decimals. This step continues from Step 10.Show a hint
from sklearn.linear_model import LinearRegression,linear.fit(X_train_scaled, y_train), thenlinear.score(X_train_scaled, y_train)andlinear.score(X_test_scaled, y_test).Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import LinearRegression linear = LinearRegression() linear.fit(X_train_scaled, y_train) print(round(linear.score(X_train_scaled, y_train), 3)) print(round(linear.score(X_test_scaled, y_test), 3))Output
0.68 0.662
Steps 12 to 16: regularize, tune, compare
Ridge, Lasso, the elastic net, the choice of alpha with cross-validation, and the four models side by side.
- 12.Train a
Ridgecalledridgewithalpha=100. Print its training score, then its test score, each rounded to 3 decimals. This step continues from Step 10.Show a hint
from sklearn.linear_model import Ridge, thenridge = Ridge(alpha=100). It is used exactly likeLinearRegression.Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import Ridge ridge = Ridge(alpha=100) ridge.fit(X_train_scaled, y_train) print(round(ridge.score(X_train_scaled, y_train), 3)) print(round(ridge.score(X_test_scaled, y_test), 3))Output
0.669 0.653
- 13.Train a
Lassocalledlassowithalpha=0.3. Print the number of weights that are not 0, then the names of the features whose weight is 0, as a list. This step continues from Step 10.Show a hint
from sklearn.linear_model import Lasso. The number is(lasso.coef_ != 0).sum(), the names areX.columns[lasso.coef_ == 0].tolist().Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import Lasso lasso = Lasso(alpha=0.3) lasso.fit(X_train_scaled, y_train) print((lasso.coef_ != 0).sum()) print(X.columns[lasso.coef_ == 0].tolist())Output
9 ['bedrooms', 'guestroom', 'hotwaterheating']
- 14.Train an
ElasticNetcalledelasticwithalpha=0.05andl1_ratio=0.5. Print its training score, then its test score, each rounded to 3 decimals, then the number of weights that are not 0. This step continues from Step 10.Show a hint
from sklearn.linear_model import ElasticNet, thenelastic = ElasticNet(alpha=0.05, l1_ratio=0.5). It is used like the other models; the number of weights is(elastic.coef_ != 0).sum().Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import ElasticNet elastic = ElasticNet(alpha=0.05, l1_ratio=0.5) elastic.fit(X_train_scaled, y_train) print(round(elastic.score(X_train_scaled, y_train), 3)) print(round(elastic.score(X_test_scaled, y_test), 3)) print((elastic.coef_ != 0).sum())Output
0.678 0.658 12
- 15.Compare the elastic net alphas 0.01, 0.05, 0.1 and 0.3 (with
l1_ratio=0.5) with a 5-fold cross-validation on the training data. Print every alpha with its mean score, rounded to 3 decimals, one alpha on a line. This step continues from Step 14.Show a hint
from sklearn.model_selection import cross_val_score, then a loop:for alpha in [0.01, 0.05, 0.1, 0.3]:withscores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5)andprint(alpha, round(scores.mean(), 3)).Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import cross_val_score for alpha in [0.01, 0.05, 0.1, 0.3]: scores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5) print(alpha, round(scores.mean(), 3))Output
0.01 0.643 0.05 0.641 0.1 0.635 0.3 0.586
- 16.Print the test scores of
linear,ridge,lassoandelasticon four lines, each rounded to 3 decimals. Which model would you use? This step continues from Steps 11 to 14.Show a hint
print(round(linear.score(X_test_scaled, y_test), 3)), and the same for the other three. The plain model, the Ridge and the elastic net are close together, so the simplest one, plain linear regression, is a sensible choice here. The strong Lasso of Step 13 paid for the features it removed.Show one possible solution
Python, continues from the cells aboveprint(round(linear.score(X_test_scaled, y_test), 3)) print(round(ridge.score(X_test_scaled, y_test), 3)) print(round(lasso.score(X_test_scaled, y_test), 3)) print(round(elastic.score(X_test_scaled, y_test), 3))Output
0.662 0.653 0.512 0.658
12Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
13Summary
| Ridge | Lasso | Elastic net | |
|---|---|---|---|
| Penalty | L2: the sum of the squared weights | L1: the sum of the absolute weights | a mix of L1 and L2 |
| Effect on the weights | all smaller, none exactly 0 | some exactly 0 | smaller, and some 0 |
| Feature selection | no | yes | yes |
| Use it when | most features carry something; correlated features | few of many features matter; a short model is wanted | many features and groups of correlated ones |
| In scikit-learn | Ridge(alpha=10) | Lasso(alpha=0.01) | ElasticNet(alpha=0.05, l1_ratio=0.5) |
| Code | What it does |
|---|---|
model = Ridge(alpha=10) | a linear regression with the L2 penalty |
model = Lasso(alpha=0.01) | a linear regression with the L1 penalty |
model = ElasticNet(alpha=0.05, l1_ratio=0.5) | a mix of both penalties |
model.coef_ | the weights after training |
(model.coef_ != 0).sum() | the number of features that are left |
cross_val_score(Ridge(alpha=a), X_train_scaled, y_train, cv=5).mean() | the judgement of one alpha |
PolynomialFeatures(degree=2, include_bias=False) | adds squares and products of the features |
Rules to keep
- Regularization is a penalty for large weights. It trades a little fit on the training data for steadier predictions.
- Ridge shrinks all weights. Lasso sets some to exactly 0. The elastic net does both.
- Scale the features before any regularized model.
- Alpha is chosen with cross-validation on the training data, never with the test data.
- Too small an alpha leaves overfitting; too large an alpha makes underfitting.
- Compare the training and the test score first. Without overfitting there is nothing to cure.
- The more features a model has for its rows, the more it needs a penalty.
What comes next
Until now every model predicted a number: a price. Topic 27, logistic regression, is the first model for the other large task of supervised learning: predicting a class, such as "yes" or "no". The regularization of this lesson will be part of it from the start.