Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 19

Ridge Regression: Calm a Curve with Python

Calm Ananya's degree-6 Hyderabad house curve with ridge: scale the powers, pick alpha, and see when a penalty helps or underfits.

Intermediate40 min

Your progress: 0 of 13 steps

0 of 9 code cells run · saved in this browser only

Step 1 of 13

Imagine

What real-world problem are we solving?

The curve that ran away

Ananya already has a fair model for her Hyderabad flats. In polynomial regression a degree-2 curve priced a 2000 sq ft house at about 83.6 lakh, with a test RMSE of 2.94 lakh. Degree 6 looked even tighter on the training houses, then a 5000 sq ft villa came out at about 22,454 lakh. The weights on the raw powers ran into the thousands. The curve had memorised the wiggles.

She does not want to throw the bend away. She wants the same powers, with the wild weights pulled back.

Step 2 of 13

Brainstorm

What would you try first?

What could calm the weights

A straight line is too stiff. Degree 2 already works. Degree 6 is flexible enough to follow noise, and x6x^6 is a huge number, so ordinary least squares is free to use a huge weight. One fix is to keep the columns and add a cost for large weights. That cost is the ridge penalty. We still have to choose how strong it is, and we still must not trust a price far outside 600 to 3000 sq ft.

Step 3 of 13

Discover

Why do we need this algorithm?

Discover ridge regression

Ordinary least squares picks the weights that make the squared misses as small as possible. Ridge adds a second term:

cost=∑(y−y^)2+α∑j=1dwj2\text{cost} = \sum (y - \hat{y})^2 + \alpha \sum_{j=1}^{d} w_j^2
Symbol Say it as Meaning here
α\alpha (alpha) the penalty strength A hyperparameter you choose. 0 is ordinary least squares. Bigger pulls the weights harder toward 0
wjw_j the weight on column jj Learned. The intercept is not in the penalty, so the model can still sit at the right price level
dd the degree How many powers of size we build first. We freeze it at 6 so alpha is the only knob

Before the penalty, scale each power on the training houses only. Otherwise x6x^6 is so large that alpha mostly fights that one column and barely touches xx. After scaling, a weight of 10 means the same kind of push on every power.

Step 4 of 13

Visualize

What does it look like?

See the penalty before the algebra

The dashed curve is degree 6 with no penalty. The solid curve is the same degree with the alpha you choose. Both are drawn only across the houses we have.

Explorer loads as you scroll…

Move alpha from 0.1 to 100. Watch the largest weight, the test error, and the 5000 sq ft callout. A calmer curve inside the plot is not the same as a safe price for a villa we have never seen.

Step 5 of 13

Mathematics

What equation describes it?

The mathematics, on eight houses

The practical model uses six scaled powers. That matrix is too big to check by hand, so this section uses degree 2, no scaler, alpha 1. The notebook later fits the degree-6 model and the numbers will not match these. That is expected.

Training sizes and prices (houses 3, 6, 9 and 12 are held out):

x=0.6,0.8,1.2,1.4,1.8,2.0,2.5,2.8y=27,29,43,55,69,86,118,135x = 0.6, 0.8, 1.2, 1.4, 1.8, 2.0, 2.5, 2.8 \qquad y = 27, 29, 43, 55, 69, 86, 118, 135

The design matrix has a column of ones, a column of xx, and a column of x2x^2. The normal equation with the penalty on the two slopes only is

(X⊤X+αIslopes) b=X⊤y(X^{\top}X + \alpha I_{\text{slopes}})\, b = X^{\top} y X⊤X=[813.125.7313.125.7356.60925.7356.609133.4801]X⊤y=[5621137.22561.46]X^{\top}X = \begin{bmatrix} 8 & 13.1 & 25.73 \\ 13.1 & 25.73 & 56.609 \\ 25.73 & 56.609 & 133.4801 \end{bmatrix} \qquad X^{\top} y = \begin{bmatrix} 562 \\ 1137.2 \\ 2561.46 \end{bmatrix}

Add 1 to the xx and x2x^2 diagonal entries and solve. The weights are

b0=19.8096,b1=4.8308,b2=13.2234b_0 = 19.8096, \quad b_1 = 4.8308, \quad b_2 = 13.2234

A 2000 sq ft house (x=2x = 2):

19.8096+4.8308×2+13.2234×4=82.37 lakh19.8096 + 4.8308 \times 2 + 13.2234 \times 4 = 82.37 \text{ lakh}

Training RMSE is 2.59 lakh. Test RMSE is 2.28 lakh. The unpenalised degree-2 model from the previous lesson was b0=13.82b_0 = 13.82, b1=11.99b_1 = 11.99, b2=11.44b_2 = 11.44, with a lower training error (2.31) and a slightly higher test error (2.94). Ridge traded a little training fit for smaller slopes. On eight houses that trade is small. The point of the penalty shows up when the degree is high.

Step 6 of 13

Dataset

What data are we using?

The same twelve houses

Edit a price in the notebook and the table follows. New rows you do not list in test_rows stay in the training set.

The same twelve houses as the polynomial regression lesson. Illustrative teaching data, not real listings.

size_kinput feature (X)1000 sq ft
Built-up area. 1.5 means 1500 sq ft. This is the input x.
price_lakhtarget (y)₹ lakh
Sale price. 100 lakh = ₹1 crore. This is what we predict, y.
12 sample houses in Hyderabad
Rowsize_kprice_lakhUsed for
10.627● train
20.829● train
3140▢ test
41.243● train
51.455● train
61.556▢ test
71.869● train
8286● train
92.293▢ test
102.5118● train
112.8135● train
123157▢ test

Every third house (houses 3, 6, 9 and 12) is held back as the test set. The model never sees them while learning.

Kernel not startedSession 1

Saves automatically in this browser

Notebook loads as you scroll…

Step 7 of 13

Manual calculation

Can we compute it by hand?

Check the hand result in Python

This cell solves the degree-2 system above. It should print 19.8096, 4.8308, 13.2234 and 82.37.

Notebook loads as you scroll…

Step 8 of 13

Python notebook

How do we run it in code?

The model you would actually train

Build the six powers, scale them with StandardScaler fit on the training houses, then Ridge(alpha=1). Beside it, fit ordinary least squares on the unscaled powers so you can see the explosion the penalty is reacting to.

At alpha 1 the scaled weights are about 12.87,10.01,7.02,4.37,2.16,0.3412.87, 10.01, 7.02, 4.37, 2.16, 0.34, and the intercept is the training mean, 70.25 lakh. The largest ordinary weight is about 2,464. Those two numbers are not the same weight in different units: scaling changed the columns. Compare predictions, not the raw digits.

Model Train RMSE Test RMSE 2000 sq ft 5000 sq ft
Degree 6, no penalty 1.51 3.44 84.56 22,453.9
Degree 6, scaled ridge, alpha 1 3.78 1.04 80.06 603.4

603 lakh is less absurd than 22,454. It is still a guess for a house bigger than anything in the table.

Notebook loads as you scroll…

Step 9 of 13

Experiment

What changes when we change things?

Change only alpha

Model parameters

Learned by the algorithm from the data

intercept
Predicted price when every scaled column is 0. With standard scaling this is the average training price, 70.25 lakh.
weights w1 … w6
Learned weights on the scaled powers x, x², … x⁶. Ridge pulls these toward zero.

Hyperparameters

Chosen by you before training

alpha
How hard large weights are punished. You choose it. 0 is ordinary least squares. Larger means a smoother, simpler curve.
degree
How many powers of size to build before the penalty. Fixed at 6 in this lesson so alpha is the only knob.
Alpha Train RMSE Test RMSE 5000 sq ft
0.1 2.23 3.73 86.7
1 3.78 1.04 603.4
10 9.68 5.36 960.5
100 26.35 30.29 457.8

Read this table slowly.

  • Alpha 0.1 keeps the 5000 sq ft guess near the data (86.7 lakh) and the training fit is still close. Its test RMSE is worse than alpha 1.
  • Alpha 1 has the lowest test RMSE on these four houses. The outside guess is 603 lakh, so the best test score did not make extrapolation safe.
  • Alpha 10 is worse on both sets, and the outside guess is even larger. A stronger penalty is not automatically a safer villa price.
  • Alpha 100 underfits. Training and test errors are both huge because the curve can no longer follow the bend.

Four test houses make 1.04 look more decisive than it is. The useful band on this sample is about 0.1 to 1. Do not ship degree 6 just because one alpha won a four-row contest. Degree 2 from the previous lesson is still the simpler model for these houses. Ridge earns its place when you already have many correlated columns and ordinary weights swing.

Notebook loads as you scroll…

Step 10 of 13

Evaluation

How good is the model?

Score the model you can explain

  • MAE

    mean(|y - ŷ|)

    Good for. Typical miss in the target's own units.

    Limit. Treats a small and a huge miss almost alike.

  • MSE

    mean((y - ŷ)²)

    Good for. Training objective; punishes big misses.

    Limit. Units are squared, so hard to read.

  • RMSE

    √MSE

    Good for. Typical miss, with big misses weighted more.

    Limit. Sensitive to outliers.

  • R²

    1 - SSE/SST

    Good for. Share of variation the model explains.

    Limit. Can look great on training data while the model overfits.

For scaled ridge at alpha 1, on the four held-out houses:

Metric Value How to say it
MAE 0.96 lakh The typical miss is under 1 lakh on these four flats
RMSE 1.04 lakh The squared misses, back in lakh
R2R^2 0.999 Almost all of the test variation is captured. With four points this can be luck

The no-penalty degree-6 model has a better training RMSE (1.51 against 3.78) and a worse test RMSE (3.44 against 1.04). Training error is the wrong judge. Also compare alpha 1 with degree 2's test RMSE of 2.94 before you decide the flexible model won.

Notebook loads as you scroll…

Step 11 of 13

Applications

Where is it used, and when is it wrong?

When to use ridge regression

Use it when a flexible linear model, often one with many columns or high powers, fits the training rows and then wobbles. The columns are usually correlated, so ordinary least squares is free to make one weight huge and another huge with the opposite sign. Ridge keeps every column and shrinks those weights.

Check Use ridge when Do not use it when
Weights Ordinary weights are huge or flip sign when you drop one row The ordinary fit is already stable and the line is straight
Columns Many inputs, or powers of one input, that move together You need some weights to be exactly zero so you can drop inputs. That is lasso
Scale You can standardise the columns on the training rows before the penalty You skip scaling, so alpha secretly punishes only the largest column
Alpha A moderate alpha lowers test error without flattening the bend Alpha is so large that train and test error both jump (here, alpha 100)
Range You predict inside the sizes you trained on You treat a calmer curve as permission to price a 5000 sq ft villa

Where ridge regression is used

  • Many measurements of the same thing: nearby pixels, correlated lab readings, or size and size-squared in one model.
  • Polynomials that overfit: keep a high degree, then shrink it, and still check a simpler degree.
  • A default linear model when you have more columns than you want to inspect one by one.

Benefits: closed form, every column stays available, predictions move less when two inputs carry the same signal.

Limitations: weights rarely hit zero, so the model does not select features. Alpha is a choice, and a tiny test set will flatter one of them. Scaling must be fit on training rows only. Extrapolation can still be nonsense, as 603 lakh shows.

Common mistakes: comparing a scaled weight with an unscaled one; picking alpha by training error; fitting the scaler on the test houses; reading a lower test RMSE on four rows as proof.

Situation Try instead
The points already sit on a line Linear regression
One input, a smooth bend, and you want the smallest degree Polynomial regression, degree 2 on these houses
You must drop useless inputs Lasso
You want both shrinking and zeros Elastic net

Step 12 of 13

Assessment

Did you understand?

Check your understanding

Replace the ... in the challenge, then take the quiz. The challenge should print about 960.5.

Notebook loads as you scroll…
Quiz loads as you scroll…

Step 13 of 13

Recap

What did we learn?

Recap

  • Problem: degree 6 followed the houses and then predicted about 22,454 lakh for a 5000 sq ft villa.
  • Idea: add α∑wj2\alpha \sum w_j^2 to the squared error. The intercept is not penalised.
  • Scale first. Fit StandardScaler on the training powers so alpha treats xx and x6x^6 fairly.
  • By hand: degree 2, alpha 1, no scaler gives b0=19.81b_0 = 19.81, b1=4.83b_1 = 4.83, b2=13.22b_2 = 13.22, and 82.37 lakh at 2000 sq ft.
  • In practice: degree 6, scaled, alpha 1. Weights stay modest, intercept is 70.25, test RMSE is 1.04 lakh on four houses, and 5000 sq ft is still 603 lakh.
  • Alpha is not "bigger is safer". Alpha 100 underfits. Alpha 10 makes the outside guess worse. Four test houses make the winner noisy.
  • When to use it: correlated columns or a flexible linear model whose weights explode, and predictions inside the training range. Use lasso when you need exact zeros. Keep degree 2 when a simple curve already fits.

Next: the same penalty idea, written out, is on Regularization. To drop columns instead of shrinking them, go to Lasso. The full notebook is in the ML Lab.