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.
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 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:
| Symbol | Say it as | Meaning here |
|---|---|---|
| (alpha) | the penalty strength | A hyperparameter you choose. 0 is ordinary least squares. Bigger pulls the weights harder toward 0 |
| the weight on column | Learned. The intercept is not in the penalty, so the model can still sit at the right price level | |
| 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 is so large that alpha mostly fights that one column and barely touches . 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.
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):
The design matrix has a column of ones, a column of , and a column of . The normal equation with the penalty on the two slopes only is
Add 1 to the and diagonal entries and solve. The weights are
A 2000 sq ft house ():
Training RMSE is 2.59 lakh. Test RMSE is 2.28 lakh. The unpenalised degree-2 model from the previous lesson was , , , 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.
| Row | size_k | price_lakh | Used for |
|---|---|---|---|
| 1 | 0.6 | 27 | ● train |
| 2 | 0.8 | 29 | ● train |
| 3 | 1 | 40 | ▢ test |
| 4 | 1.2 | 43 | ● train |
| 5 | 1.4 | 55 | ● train |
| 6 | 1.5 | 56 | ▢ test |
| 7 | 1.8 | 69 | ● train |
| 8 | 2 | 86 | ● train |
| 9 | 2.2 | 93 | ▢ test |
| 10 | 2.5 | 118 | ● train |
| 11 | 2.8 | 135 | ● train |
| 12 | 3 | 157 | ▢ test |
Every third house (houses 3, 6, 9 and 12) is held back as the test set. The model never sees them while learning.
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.
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 , 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.
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.
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.
| Metric | Formula | Good for | Limitation |
|---|---|---|---|
| MAE | mean(|y - ŷ|) | Typical miss in the target's own units. | Treats a small and a huge miss almost alike. |
| MSE | mean((y - ŷ)²) | Training objective; punishes big misses. | Units are squared, so hard to read. |
| RMSE | √MSE | Typical miss, with big misses weighted more. | Sensitive to outliers. |
| R² | 1 - SSE/SST | Share of variation the model explains. | 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 |
| 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.
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.
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 to the squared error. The intercept is not penalised.
- Scale first. Fit
StandardScaleron the training powers so alpha treats and fairly. - By hand: degree 2, alpha 1, no scaler gives , , , 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.





