Asiman Data School

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.

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. 1.Why a model with large weights is a warning sign, and what regularization does about it
  2. 2.The three penalties: Ridge (L2), Lasso (L1) and elastic net, their formulas and their logic
  3. 3.Why Ridge makes weights small and Lasso makes some of them exactly zero
  4. 4.What the strength alpha does, and how to choose it with cross-validation
  5. 5.Why the features must be scaled before regularization
  6. 6.The whole workflow of a project: look, clean, encode, split, scale, train, tune, compare
  7. 7.When regularization helps a lot, and when it changes almost nothing
The words of this lesson
WordMeaning
regularizationtraining with a penalty for large weights, to keep the model simple
penaltythe extra term that is added to the loss
Ridge regressionlinear regression with the L2 penalty: the sum of the squared weights
Lasso regressionlinear regression with the L1 penalty: the sum of the absolute weights
elastic netlinear regression with a mix of both penalties
alphathe strength of the penalty: 0 is no regularization, a large value is a strong one
l1_ratioin an elastic net: the share of the L1 penalty in the mix
shrinkingweights moving towards 0 under a penalty
sparse modela model in which many weights are exactly 0
hyperparametera 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:

loss=error on the training data+penalty for large weights\begin{aligned} \text{loss} = {} & \text{error on the training data} \\ & + \text{penalty for large weights} \end{aligned}

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

(a) Towards which value does a penalty pull every weight? (b) Compared with plain linear regression, how does a regularized model usually fit the training data? (c) Which problem is regularization meant to cure?

Show a hint
The penalty makes large weights cost something. The model gives up a little of one score to gain steadiness.
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: y^=w0+w1x1+⋯+wpxp\hat{y} = w_0 + w_1 x_1 + \dots + w_p x_p, with pp features. The intercept w0w_0 is never penalised. In the formulas the strength of the penalty is written α\alpha, the Greek letter alpha; in code it is alpha.

2.1Plain linear regression

loss=MSE\text{loss} = \text{MSE}

The mean squared error of Topic 22, and nothing else.

2.2Ridge regression: the L2 penalty

loss=MSE+α(w12+w22+⋯+wp2)\text{loss} = \text{MSE} + \alpha \left( w_1^2 + w_2^2 + \dots + w_p^2 \right)

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

loss=MSE+α(∣w1∣+∣w2∣+⋯+∣wp∣)\text{loss} = \text{MSE} + \alpha \left( \lvert w_1 \rvert + \lvert w_2 \rvert + \dots + \lvert w_p \rvert \right)

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

loss=MSE+α[ r(∣w1∣+⋯+∣wp∣)+(1−r)(w12+⋯+wp2)]\begin{aligned} \text{loss} = \text{MSE} + \alpha \Big[ \, & r \left( \lvert w_1 \rvert + \dots + \lvert w_p \rvert \right) \\ & + (1 - r) \left( w_1^2 + \dots + w_p^2 \right) \Big] \end{aligned}

A mix of the two penalties. The number rr, called l1_ratio in scikit-learn, says how much of the mix is L1:

  • r=1r = 1: only the L1 penalty. The model is a Lasso.
  • r=0r = 0: only the L2 penalty. The model is a Ridge.
  • r=0.5r = 0.5: 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:

The penalties by hand
WeightsMSE on the training data
Model A6 and −8-84.0
Model B3 and −2-24.6

Without a penalty, Model A wins: its error is smaller. Now the two penalties:

Model AL2: 62+(−8)2=36+64=100L1: ∣6∣+∣−8∣=14Model BL2: 32+(−2)2=9+4=13L1: ∣3∣+∣−2∣=5\begin{aligned} \textbf{Model A}\quad & \text{L2: } 6^2 + (-8)^2 = 36 + 64 = 100 \\[2pt] & \text{L1: } \lvert 6 \rvert + \lvert -8 \rvert = 14 \\[10pt] \textbf{Model B}\quad & \text{L2: } 3^2 + (-2)^2 = 9 + 4 = 13 \\[2pt] & \text{L1: } \lvert 3 \rvert + \lvert -2 \rvert = 5 \end{aligned}

The Ridge loss with α=0.1\alpha = 0.1:

Model A:4.0+0.1×100=4.0+10=14.0Model B:4.6+0.1×13=4.6+1.3=5.9\begin{aligned} \text{Model A:}\quad & 4.0 + 0.1 \times 100 = 4.0 + 10 = 14.0 \\[4pt] \text{Model B:}\quad & 4.6 + 0.1 \times 13 = 4.6 + 1.3 = 5.9 \end{aligned}

Model B wins clearly. Its error is a little larger, but its weights are much smaller. The Lasso loss with α=0.1\alpha = 0.1:

Model A:4.0+0.1×14=4.0+1.4=5.4Model B:4.6+0.1×5=4.6+0.5=5.1\begin{aligned} \text{Model A:}\quad & 4.0 + 0.1 \times 14 = 4.0 + 1.4 = 5.4 \\[4pt] \text{Model B:}\quad & 4.6 + 0.1 \times 5 = 4.6 + 0.5 = 5.1 \end{aligned}

Model B wins here too, by less. The elastic net loss with α=0.1\alpha = 0.1 and r=0.5r = 0.5 takes half of each penalty:

Model A:4.0+0.1×(0.5×14+0.5×100)=4.0+5.7=9.7Model B:4.6+0.1×(0.5×5+0.5×13)=4.6+0.9=5.5\begin{aligned} \text{Model A:}\quad & 4.0 + 0.1 \times (0.5 \times 14 + 0.5 \times 100) \\ & = 4.0 + 5.7 = 9.7 \\[6pt] \text{Model B:}\quad & 4.6 + 0.1 \times (0.5 \times 5 + 0.5 \times 13) \\ & = 4.6 + 0.9 = 5.5 \end{aligned}

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, α=0.001\alpha = 0.001, in the Ridge loss:

Model A:4.0+0.001×100=4.1Model B:4.6+0.001×13=4.613\begin{aligned} \text{Model A:}\quad & 4.0 + 0.001 \times 100 = 4.1 \\[4pt] \text{Model B:}\quad & 4.6 + 0.001 \times 13 = 4.613 \end{aligned}

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 ww be the weight that plain linear regression would choose.

Ridge:wnew=w1+αLasso:wnew=w−αwhen w is larger than αwnew=0when w is smaller than α\begin{aligned} \text{Ridge:}\quad & w_{\text{new}} = \frac{w}{1 + \alpha} \\[10pt] \text{Lasso:}\quad & w_{\text{new}} = w - \alpha \quad \text{when } w \text{ is larger than } \alpha \\[4pt] & w_{\text{new}} = 0 \quad \text{when } w \text{ is smaller than } \alpha \end{aligned}

Ridge divides. Lasso subtracts. Take two weights, 4 and 0.5, and α=1\alpha = 1:

Ridge:41+1=20.51+1=0.25Lasso:4−1=30.5−1 is below 0, so the weight is 0\begin{aligned} \text{Ridge:}\quad & \frac{4}{1 + 1} = 2 \qquad \frac{0.5}{1 + 1} = 0.25 \\[10pt] \text{Lasso:}\quad & 4 - 1 = 3 \\[4pt] & 0.5 - 1 \text{ is below } 0 \text{, so the weight is } 0 \end{aligned}

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.

−4−4−2−22244

Ridge: every weight is divided

smaller, but never 0

−4−4−2−22244

Lasso: every weight loses the same amount

weights between −1 and 1 become 0

The weight with the penalty (upwards) against the weight without it (to the right), for alpha = 1. The dashed line is a model without a penalty. Ridge turns the line flatter: every weight is divided by the same number, and only a weight of 0 stays 0. Lasso moves the line: every weight loses the same amount, and all weights between −1 and 1 become exactly 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 (w12+w22w_1^2 + w_2^2 below a limit) is a circle, and the budget of Lasso (∣w1∣+∣w2∣\lvert w_1 \rvert + \lvert w_2 \rvert 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.

no penalty

Ridge: the budget is a circle

both weights small, neither is 0

no penalty

Lasso: the budget is a diamond

a corner: weight 2 is exactly 0

Two weights: weight 1 runs to the right, weight 2 upwards. The dark dot is where a model without a penalty would put them; every oval further out is a larger error. The coloured shape is the budget of the penalty, and the coloured dot is the point of the budget with the smallest error. The circle is touched at an ordinary point: both weights are small, neither is 0. The diamond is touched at 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

Side by side
Linear regressionRidgeLassoElastic net
Penaltynonesquared weights (L2)absolute weights (L1)a mix of both
What happens to the weightsfreeall become smallersome become exactly 0smaller, and some 0
Selects featuresnonoyesyes
Correlated featuresunstable weightsshares the weight among themkeeps one, drops the otherskeeps groups together
Numbers to choosenonealphaalphaalpha and l1_ratio
In scikit-learnLinearRegression()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.

−4−4−2−22244−4−4−2−22244

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

A model has the weights 3 and −4-4 and a training MSE of 2.0. (a) What is its L2 penalty? (b) Its L1 penalty? (c) Its Ridge loss with α=0.1\alpha = 0.1? (d) Its Lasso loss with α=0.1\alpha = 0.1? (e) In the simplest case, what does Lasso with α=2\alpha = 2 make of a weight of 1.5?

Show a hint
Squares for L2, absolute values for L1. The loss is the MSE plus alpha times the penalty. Lasso subtracts alpha, and a weight that is smaller than alpha becomes 0.
Show the solution

Answer: (a) 25; (b) 7; (c) 4.5; (d) 2.7; (e) 0.

(a)32+(−4)2=9+16=25(b)∣3∣+∣−4∣=7(c)2.0+0.1×25=4.5(d)2.0+0.1×7=2.7(e)1.5 is smaller than 2, so the weight is 0\begin{aligned} \text{(a)}\quad & 3^2 + (-4)^2 = 9 + 16 = 25 \\[4pt] \text{(b)}\quad & \lvert 3 \rvert + \lvert -4 \rvert = 7 \\[4pt] \text{(c)}\quad & 2.0 + 0.1 \times 25 = 4.5 \\[4pt] \text{(d)}\quad & 2.0 + 0.1 \times 7 = 2.7 \\[4pt] \text{(e)}\quad & 1.5 \text{ is smaller than } 2 \text{, so the weight is } 0 \end{aligned}

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.

Python
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
Step 1: read the file and look at it
ColumnMeaning
pricethe price of the house: the target
areathe area of the house
bedroomsthe number of bedrooms
bathroomsthe number of bathrooms
storiesthe number of floors
mainroadis the house on a main road? yes or no
guestroomdoes it have a guest room?
basementdoes it have a basement?
hotwaterheatingdoes it have hot water heating?
airconditioningdoes it have air conditioning?
parkingthe number of parking places
prefareais it in a preferred area of the town?
furnishingstatusfurnished, 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.

Download

Loading the table ...

3.2Step 2: check the columns

Are there missing values or repeated rows (Topic 11)? Which columns are text?

Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

Python, continues from the cells above
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

(a) The IQR rule marks 15 prices. Why do they stay in the data? (b) Why does furnishingstatus get the numbers 0, 1 and 2? (c) Why is scaling required for the models of this lesson?

Show a hint
Topic 25 for (a) and (b). The penalty of Part 2 for (c).
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.

Python, continues from the cells above
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:

Python, continues from the cells above
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

The first model has a training score of 0.685 and a test score of 0.649. (a) How large is the gap between the two scores? (b) Does the model overfit much? (c) The weight of area is 0.519. For which change of the area does the price rise by about 0.52 million?

Show a hint
Subtract. A few hundredths are a normal gap (Topic 23). The features are standardised and the price is in millions.
Show the solution

Answer: (a) 0.036; (b) no; (c) one standard deviation more area.

0.685−0.649=0.0360.685 - 0.649 = 0.036

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.

Python, continues from the cells above
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:

Python, continues from the cells above
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 α=100\alpha = 100 both scores begin to fall.
  • With α=1000\alpha = 1000 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:

Python, continues from the cells above
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

Python, continues from the cells above
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.

Python, continues from the cells above
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 α=0.1\alpha = 0.1 all twelve features stay. With α=0.3\alpha = 0.3 only seven are left. Which ones?

Python, continues from the cells above
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 α=0.3\alpha = 0.3 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.

Python, continues from the cells above
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, α=0.3\alpha = 0.3, the mix shows its two sides. Every line shows l1_ratio, the test score and the number of weights that are not 0:

Python, continues from the cells above
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.

area0.509
bedrooms0.067
bathrooms0.513
stories0.341
mainroad0.131
guestroom0.093
basement0.183
hotwaterheating0.147
airconditioning0.359
parking0.194
prefarea0.262
furnishingstatus0.158
00.20.40.11101001,00010,000alpha (each step is ten times larger)

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

This task continues from the cells above. Train a 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
Python, continues from the cells above
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

This task continues from the cells above. Train a 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
Python, continues from the cells above
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

This task continues from the cells above. Train an 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
Python, continues from the cells above
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.

Python, continues from the cells above
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 α=10\alpha = 10, by a hair. The same for Lasso:

Python, continues from the cells above
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; α=0.01\alpha = 0.01 is taken. And for the elastic net, with l1_ratio=0.5:

Python, continues from the cells above
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 α=0.05\alpha = 0.05 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.

Python, continues from the cells above
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).

The four models side by side
ModelTraining scoreTest score
linear regression0.6850.649
Ridge, α=10\alpha = 100.6850.648
Lasso, α=0.01\alpha = 0.010.6850.646
elastic net, α=0.05\alpha = 0.050.6840.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

This task continues from the cells above: 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
Python, continues from the cells above
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

A cross-validation on the training data gives these mean scores for four alphas: 0.01 gives 0.61, 0.1 gives 0.66, 1 gives 0.64, 10 gives 0.40. (a) Which alpha is chosen? (b) On which data was this choice made? (c) How often is the test data used?

Show a hint
The best mean score wins. The test data must not take part in building the model.
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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.

Python, continues from the cells above
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
The three regularized models on ninety features
Model on 90 featuresTraining scoreTest scoreFeatures kept
linear regression0.7900.65090
Ridge, α=100\alpha = 1000.7420.66890
Lasso, α=0.05\alpha = 0.050.7280.65824
elastic net, α=0.1\alpha = 0.10.7260.65937

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:

Python, continues from the cells above
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.

Python, continues from the cells above
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 −1.9-1.9. 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:

Python, continues from the cells above
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:

Python, continues from the cells above
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.

00.20.40.11101001,00010,000alpha (each step is ten times larger)

Ridge

the weights shrink together

00.20.40.0010.010.11alpha (each step is ten times larger)

Lasso

one weight after another becomes 0

00.20.40.0010.010.11alpha (each step is ten times larger)

Elastic net

first together, then to 0

The twelve weights of the housing model for a whole row of alphas, calculated with scikit-learn. 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. The elastic net (with l1_ratio 0.5) does both: the lines sink together at first, like a Ridge, and then reach 0 one after another, like a Lasso.

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

What the project showed
12 features90 features454 features
linear regression: training / test0.685 / 0.6490.790 / 0.6500.948 / below 0
Ridge: test0.6480.6680.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)
The same houses with twelve, ninety and 454 features. The training score of the plain model climbs with every feature, and its test score does not follow: at 454 features it is below 0. The test scores of Ridge, Lasso and the elastic net stay where they were.
  • 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

This task continues from the cells above: 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
Python, continues from the cells above
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.

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, kinds of columns545 houses, 13 columns, 7 of them text
2. Checkmissing values, repeated rows, columns without informationnothing to repair, nothing to drop
3. Outliersfind them, decide: mistake or realreal houses: kept
4. Encodetext to numberssix yes/no columns as 1 and 0, one ordinal column
5. Splittraining and test data436 and 109 houses
6. Scalefit on the training data, transform bothStandardScaler: required for regularization
7. First modela simple starting pointLinearRegression: 0.649
8. Improveother models, more features, regularizationRidge, Lasso, elastic net
9. Tunechoose hyperparameters with cross-validationalpha
10. Judgethe test score of the finished models, oncethe 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

(a) Which step comes directly before scaling? (b) Which of these is done on the whole table, before the split? (c) What is fitted on the training data only?

Show a hint
Whatever learns from the rows comes after the split and learns from the training rows.
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

Common mistakes
MistakeWhy it is wrongRight
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 α=0\alpha = 0 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, −3-3 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).

L2:22+(−3)2+0.52=4+9+0.25=13.25L1:∣2∣+∣−3∣+∣0.5∣=2+3+0.5=5.5\begin{aligned} \text{L2:}\quad & 2^2 + (-3)^2 + 0.5^2 \\ & = 4 + 9 + 0.25 = 13.25 \\[10pt] \text{L1:}\quad & \lvert 2 \rvert + \lvert -3 \rvert + \lvert 0.5 \rvert \\ & = 2 + 3 + 0.5 = 5.5 \end{aligned}

Why: the sign of a weight does not matter for either penalty: only its size. In L2 the weight −3-3 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 α=0.1\alpha = 0.1? And with α=0.01\alpha = 0.01?

Idea. Ridge loss=MSE+α×(sum of the squared weights)\text{Ridge loss} = \text{MSE} + \alpha \times (\text{sum of the squared weights}) (Part 2).

L2 of A: 52+52=50L2 of B: 22+12=5α=0.1:A: 2.0+0.1×50=7.0B: 2.5+0.1×5=3.0α=0.01:A: 2.0+0.01×50=2.5B: 2.5+0.01×5=2.55\begin{aligned} & \text{L2 of A: } 5^2 + 5^2 = 50 \\[2pt] & \text{L2 of B: } 2^2 + 1^2 = 5 \\[12pt] \alpha = 0.1:\quad & \text{A: } 2.0 + 0.1 \times 50 = 7.0 \\[2pt] & \text{B: } 2.5 + 0.1 \times 5 = 3.0 \\[10pt] \alpha = 0.01:\quad & \text{A: } 2.0 + 0.01 \times 50 = 2.5 \\[2pt] & \text{B: } 2.5 + 0.01 \times 5 = 2.55 \end{aligned}

Why: with α=0.1\alpha = 0.1 Model B wins clearly: its small weights outweigh its larger error. With α=0.01\alpha = 0.01 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 α=1\alpha = 1 under Ridge and under Lasso?

Idea. Ridge: w1+α\frac{w}{1 + \alpha}. Lasso: w−αw - \alpha, and 0 when ww is smaller than α\alpha (Part 2).

Ridge:62=322=10.42=0.2Lasso:6−1=52−1=10.4−1 is below 0, so the weight is 0\begin{aligned} \text{Ridge:}\quad & \frac{6}{2} = 3 \qquad \frac{2}{2} = 1 \qquad \frac{0.4}{2} = 0.2 \\[10pt] \text{Lasso:}\quad & 6 - 1 = 5 \qquad 2 - 1 = 1 \\[4pt] & 0.4 - 1 \text{ is below } 0 \text{, so the weight is } 0 \end{aligned}

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).

Python
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).

Python, continues from the cells above
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.

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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 α=0.01\alpha = 0.01 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).

Python, continues from the cells above
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).

Python, continues from the cells above
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. 1.A model has the weights 4, −1-1 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.

    (a)42+(−1)2+22=16+1+4=21(b)∣4∣+∣−1∣+∣2∣=4+1+2=7\begin{aligned} \text{(a)}\quad & 4^2 + (-1)^2 + 2^2 = 16 + 1 + 4 = 21 \\[6pt] \text{(b)}\quad & \lvert 4 \rvert + \lvert -1 \rvert + \lvert 2 \rvert = 4 + 1 + 2 = 7 \end{aligned}
  2. 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 α=0.1\alpha = 0.1? (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.

    (a)3.0+0.1×10=4.0(b)3.4+0.1×4=3.8\begin{aligned} \text{(a)}\quad & 3.0 + 0.1 \times 10 = 4.0 \\[6pt] \text{(b)}\quad & 3.4 + 0.1 \times 4 = 3.8 \end{aligned}

    (c) Model B has the smaller loss: its error is a little larger, but its weights are much smaller.

  3. 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.

  1. 4.Read Housing.csv into df. Print the shape, then the number of missing values.
    Show a hint
    df = pd.read_csv("Housing.csv"), then print(df.shape) and print(df.isna().sum().sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("Housing.csv")
    
    print(df.shape)
    print(df.isna().sum().sum())

    Output

    (545, 13)
    0
  2. 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 with 0.75 for q3, then upper = 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 above
    q1 = 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
  3. 6.Turn price into 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, then print(df["price"].min(), df["price"].max()).
    Show one possible solution
    Python, continues from the cells above
    df["price"] = df["price"] / 1000000
    
    print(df["price"].min(), df["price"].max())

    Output

    1.75 13.3
  4. 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 it df[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 above
    yes_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
  5. 8.Encode furnishingstatus in 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}), then print(round(df["furnishingstatus"].mean(), 2)).
    Show one possible solution
    Python, continues from the cells above
    df["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.

  1. 9.Make X (all columns without price) and y (price). Split them with test_size=0.3 and random_state=1. Print the shapes of X_train and X_test on 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"], then X_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 above
    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.3, random_state=1)
    
    print(X_train.shape, X_test.shape)

    Output

    (381, 12) (164, 12)
  2. 10.Scale the features with a StandardScaler called scaler into X_train_scaled and X_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 and scaler.transform(X_test) for the test data, then print(round(X_test_scaled.max(), 2)). If your number differs, check test_size=0.3 and random_state=1 in Step 9.
    Show one possible solution
    Python, continues from the cells above
    from 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
  3. 11.Train a LinearRegression called linear on 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), then linear.score(X_train_scaled, y_train) and linear.score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    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.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.

  1. 12.Train a Ridge called ridge with alpha=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, then ridge = Ridge(alpha=100). It is used exactly like LinearRegression.
    Show one possible solution
    Python, continues from the cells above
    from 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
  2. 13.Train a Lasso called lasso with alpha=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 are X.columns[lasso.coef_ == 0].tolist().
    Show one possible solution
    Python, continues from the cells above
    from 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']
  3. 14.Train an ElasticNet called elastic with alpha=0.05 and l1_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, then elastic = 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 above
    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))
    print((elastic.coef_ != 0).sum())

    Output

    0.678
    0.658
    12
  4. 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]: with scores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5) and print(alpha, round(scores.mean(), 3)).
    Show one possible solution
    Python, continues from the cells above
    from 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
  5. 16.Print the test scores of linear, ridge, lasso and elastic on 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 above
    print(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.

Question 1

1.What does regularization add to the training of a linear model?

Question 2

2.Which problem is regularization meant to cure?

Question 3

3.What is the penalty of Ridge regression?

Question 4

4.Which model can set weights to exactly 0?

Question 5

5.A model has the weights 3 and −4-4. What is its L1 penalty?

Question 6

6.What happens when alpha is made very large?

Question 7

7.Why must the features be scaled before Ridge or Lasso?

Question 8

8.How is alpha chosen?

Question 9

9.In an elastic net, what does l1_ratio=1 give?

Question 10

10.A plain linear regression has a training score of 0.69 and a test score of 0.65. What can regularization be expected to do?

Question 11

11.A model has 454 features and 436 training rows. Its training score is 0.95 and its test score is negative. Which statement is right?

Question 12

12.When is Lasso a better choice than Ridge?

0 of 12 answered.

13Summary

Summary
RidgeLassoElastic net
PenaltyL2: the sum of the squared weightsL1: the sum of the absolute weightsa mix of L1 and L2
Effect on the weightsall smaller, none exactly 0some exactly 0smaller, and some 0
Feature selectionnoyesyes
Use it whenmost features carry something; correlated featuresfew of many features matter; a short model is wantedmany features and groups of correlated ones
In scikit-learnRidge(alpha=10)Lasso(alpha=0.01)ElasticNet(alpha=0.05, l1_ratio=0.5)
Summary
CodeWhat 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

  1. Regularization is a penalty for large weights. It trades a little fit on the training data for steadier predictions.
  2. Ridge shrinks all weights. Lasso sets some to exactly 0. The elastic net does both.
  3. Scale the features before any regularized model.
  4. Alpha is chosen with cross-validation on the training data, never with the test data.
  5. Too small an alpha leaves overfitting; too large an alpha makes underfitting.
  6. Compare the training and the test score first. Without overfitting there is nothing to cure.
  7. 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.