Lesson 18
Polynomial Regression: Fit Curves with Python
Follow a Hyderabad house-price story to learn polynomial regression: degrees, the maths, a runnable Python notebook, overfitting and metrics.
Your progress: 0 of 13 steps
0 of 21 code cells run · saved in this browser only
Step 1 of 13
Imagine
What real-world problem are we solving?
A house buyer in Hyderabad
Ananya has saved for years and wants to buy a flat in Hyderabad. She has seen a 1500 sq ft flat that looks perfect. The agent, Rajesh, quotes a price. Ananya is not sure it is fair, so she asks Rajesh for the prices of twelve flats that sold recently. She wants to predict a fair price for any size, not just this flat.
Look at the three houses above. The biggest house is five times wider than the smallest, yet it costs almost six times as much. If price grew in a perfectly straight line with size, that would not happen.
What would you do? Ananya could ask ten more agents, guess, or look for a pattern in the twelve prices. Before we pick a tool, let us think like a problem solver.
Step 2 of 13
Brainstorm
What would you try first?
Think like a problem solver
The smallest house is 600 sq ft for 27 lakh. The largest is 3000 sq ft for 157 lakh. Price goes up with size, but not at a constant rate: each extra square foot costs more in a big house than in a small one. The price curve bends upward, and a model that can only draw straight lines will miss it. Next we discover how to let a model bend without inventing something new.
Step 3 of 13
Discover
Why do we need this algorithm?
Discover polynomial regression
The problem it solves
A straight-line model (linear regression) learns two numbers, a starting price and a price per extra 1000 sq ft. When the real prices curve, a line is too stiff. It guesses too low for the smallest and the largest houses and too high for the middle ones. We say it underfits.
The central idea
Do not change the learning method. Change the input. Instead of giving the model only the size , give it columns made from the size: , then , then if needed. Ordinary linear regression then learns one weight per column. The weighted sum of those columns is a curve.
What does the model actually learn?
It learns the weights . It does not learn the shape of the curve directly. The shape comes from the columns you chose, and the degree you chose controls how many columns there are.
Why not just use a straight line, or a super-bendy curve?
| Approach | What goes wrong |
|---|---|
| Straight line | Cannot bend. Misses the upward curve at both ends. |
| Very high degree | Bends to touch every training house, including random noise. It then fails on new houses. |
| Polynomial of a small degree | Usually the best first try: just enough bend, still easy to explain. |
Step 4 of 13
Visualize
What does it look like?
See it before we use maths
Here are four models fitted to the same eight training houses. Circles are training houses and squares are test houses that the model never sees. Only the degree changes.
Now the errors. A residual is the real price minus the model's prediction. The red bars are residuals. Watch the pattern: the straight line is too low at both ends and too high in the middle. Degree 2 leaves small errors of mixed sign.
Slide the degree yourself. Notice that the training error keeps falling as the curve gets more flexible, but the test error does not.
Step 5 of 13
Mathematics
What equation describes it?
The mathematics, one idea at a time
We build the equation in three small steps. For every step we decode each symbol, plug in real numbers from our house data, and say what the answer means.
Step 1: the straight line
| Symbol | Say it as | Meaning here |
|---|---|---|
| "y hat" | The predicted price in lakh. The hat means "estimated". | |
| "x" | House size in thousands of square feet (1.5 means 1500 sq ft). | |
| "b zero", the intercept | The price the line gives when . A starting level. | |
| "b one", the slope | Extra lakh for each extra 1000 sq ft. |
Fitted on our eight training houses, the line has and . For a 1500 sq ft house, :
Meaning: the line predicts 63.28 lakh. But the next steps show it is a poor shape for this data.
Step 2: add a squared term so the line can bend
means . A new weight controls how strongly the curve bends. If is positive the curve bends upward like a smile. Fitted on the same houses, , , . For we have :
Meaning: the curved model predicts 57.55 lakh. The real 1500 sq ft house in our table sold for 56 lakh, so the curve is much closer than the line's 63.28.
Step 3: any degree
| Symbol | Meaning |
|---|---|
| The degree: the highest power of the model may use. You choose it. | |
| The weight on . The model learns it. There are weights. | |
| "Add up the terms for ." | |
| Equals 1, which is why is a plain constant. |
What the degree means:
| Degree | Shape | Bends allowed | Weights |
|---|---|---|---|
| 1 | Straight line | 0 | 2 |
| 2 | Parabola | 1 | 3 |
| 3 | S-shaped cubic | 2 | 4 |
| Higher | Wigglier curve | up to |
With only eight training houses, a degree-7 model would have eight weights, one per house. It has enough freedom to pass through every point exactly. That is memorising, not learning.
Why is it still called linear regression?
The word "linear" describes the weights, not the curve. Rename the columns:
This is an ordinary weighted sum. If you double every weight, the prediction doubles. The data points are just numbers computed in advance. The curve appears only when you plot the result against the original .
Two consequences that matter in practice:
- The best weights come from a closed-form calculation, with no repeated guessing. That is next.
- A model like is not linear in its weights. It needs iterative optimisation such as gradient descent.
How the weights are chosen
We want the weights that make the squared residuals as small as possible:
is the real price of house , is the prediction, is how many training houses there are. Squaring makes every miss positive and punishes big misses more. For a model that is linear in its weights, the minimum is found by the normal equation:
Here is the table of columns for every training house, is that table flipped so rows become columns, and is the list of real prices. We now do this by hand.
Step 6 of 13
Dataset
What data are we using?
Meet the dataset
We use one table for the whole lesson. Every chart, calculation, notebook cell and quiz question uses these same twelve houses.
Illustrative teaching data made up for this lesson, not real listings. Prices follow a gentle curve with small random-looking differences, like real markets do.
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.
- Input feature :
size_k, the size in thousands of square feet. - Target :
price_lakh, the price in lakh rupees. This is what we want to predict. - Test set: houses 3, 6, 9 and 12. The model never sees them while learning. That is how we measure how well it will do on new houses.
This is a deliberately small table so you can check calculations by hand. A real project would use hundreds or thousands of rows.
Run these cells to load the data, explore it and split it. Change a price in the second cell, run it again, and everything after it uses your numbers.
Step 7 of 13
Manual calculation
Can we compute it by hand?
Calculate it by hand first
No library yet. We solve the degree-2 normal equation using only arithmetic, on the eight training houses.
Build the table . Each row is . The first three training houses:
| House | |||
|---|---|---|---|
| 1 | 1 | 0.6 | 0.36 |
| 2 | 1 | 0.8 | 0.64 |
| 4 | 1 | 1.2 | 1.44 |
Compute and . Each entry is a sum over all eight training houses. For example, the top-left entry is , and the entry .
The entries are and . The notebook below prints the same matrices from NumPy.
Solve the three equations:
Check it. Put back into the first equation: , which matches .
Predict. For a 1500 sq ft house this gives 57.55 lakh, exactly the number from Step 2 above.
Measure residuals. On training house 1 (0.6, real price 27) the curve predicts 25.13, so the residual is lakh. The straight line predicts 17.65 there, a residual of 9.35 lakh.
Analytical vs iterative. The normal equation is an analytical solution: one calculation gives the best weights. Iterative methods such as gradient descent reach the answer by many small improving steps. Polynomial regression can use either, but the closed form is exact for this problem. In practice scikit-learn uses a numerically safer least-squares solver than inverting directly.
Now do the same with NumPy:
Step 8 of 13
Python notebook
How do we run it in code?
Python notebook with scikit-learn
The same model, built with two scikit-learn tools. Run the cells top to bottom, or press Run all in the toolbar of the dataset step.
| Line of code | What it does |
|---|---|
PolynomialFeatures(degree=2, include_bias=False) |
Creates the feature expander. degree=2 means add . include_bias=False skips the column of ones because LinearRegression already learns . |
poly2.fit_transform(X_train) |
Learns the setup from the training data and returns the expanded table with columns . |
poly2.transform(X_test) |
Applies the same expansion without learning anything new. |
LinearRegression().fit(X_train_poly, y_train) |
Training. Solves for . |
.intercept_ and .coef_ |
The learned and . |
quadratic.predict(poly2.transform(new_house)) |
Prediction. New input must be expanded with the same poly2 first. |
Common mistake: calling quadratic.predict([[1.5]]) without expanding. The model expects two columns and receives one, so it raises an error.
Look at the output of the evaluation cell. The straight line has a test RMSE of 10.04 lakh and the degree-2 model has 2.94 lakh. The curve is clearly the better shape for this data.
Step 9 of 13
Experiment
What changes when we change things?
Experiment: change things and watch
Two kinds of numbers appear in every machine learning model. Keep them apart.
Model parameters
Learned by the algorithm from the data
- b0 (intercept)
- Price when x = 0. Learned from the data.
- b1
- Weight on x. Learned from the data.
- b2 … bd
- Weights on x², x³ … x^d. Learned from the data.
Hyperparameters
Chosen by you before training
- degree (d)
- Highest power of x. You choose it before training; the model cannot learn it by itself.
- include_bias
- Whether PolynomialFeatures adds a column of ones. Also chosen by you.
- train/test split
- Which houses are held back for honest testing. A choice about the experiment, not the model.
Change the prices, move the degree slider, and predict any house size.
Now repeat the experiment in code. Change degree, my_size_k or the data cell:
Things to try:
- Set
degree = 1, then 2, then 6, and compare the 1800 sq ft prediction. - Predict a 5000 sq ft house (
my_size_k = 5.0) with degree 6. The training houses stop at 3000 sq ft, and the model predicts about 22,454 lakh (over ₹2,000 crore) for a 5000 sq ft house. Degree 2 says about 360 lakh for the same house. This is extrapolation: far outside the data the prediction is not trustworthy, and high degrees are the worst offenders. - Change one price by 30 lakh in the dataset cell. Which degree reacts the most?
Step 10 of 13
Evaluation
How good is the model?
Evaluation and interpretation
For regression we measure how far predictions are from the real values. Compute every metric on the test houses.
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. |
Worked example for the degree-2 model on the four test houses. The errors are 2.75, -1.55, -2.57 and 4.24.
For we compare with always guessing the average test price (86.5 lakh): , , so . The notebook below prints the same numbers from NumPy and from scikit-learn.
Reading the degree sweep honestly
| Degree | Train RMSE | Test RMSE |
|---|---|---|
| 1 | 5.83 | 10.04 |
| 2 | 2.31 | 2.94 |
| 3 | 1.98 | 5.40 |
| 4 | 1.93 | 6.65 |
| 5 | 1.63 | 11.51 |
| 6 | 1.51 | 3.44 |
- Training error never rises as the degree grows, because each higher-degree model contains the lower ones as a special case. It tells you nothing about overfitting by itself.
- Test error is lowest at degree 2. Degrees 3 to 5 are worse on unseen houses, which is the sign of overfitting.
- Degree 6 looks better than 3 to 5 on test. Do not read that as "high degree is fine". With only four test houses, one lucky house moves the number a lot. A tiny test set gives a noisy score, so use more data or cross-validation before trusting small differences.
- Limits of each metric: was 0.996 for degree 2, but a high on training data says little about new data. RMSE and MAE are in lakh, so they are easy to explain to a buyer, but they do not show whether errors have a pattern. Always look at the residual plot as well.
Step 11 of 13
Applications
Where is it used, and when is it wrong?
When to use polynomial regression
Use it when a plot of one input against the target bends in a smooth curve, and a straight line leaves a pattern in the misses. On these houses the line is too low at both ends and too high in the middle. Degree 2 cuts the test RMSE from 10.04 lakh to 2.94 lakh, and the curve stays inside the sizes we actually saw (600 to 3000 sq ft).
| Check | Use polynomial regression when | Do not use it when |
|---|---|---|
| Shape | The points bend smoothly, like price rising faster for bigger houses | The points already sit on a straight line, or they jump and then flatten |
| Inputs | One main input, or a few, and you can build powers of them (, , …) | Many unrelated inputs. Each extra input multiplies the number of columns |
| Range | You will predict inside the training range | You must price something far outside it. Degree 6 on a 5000 sq ft house, when training stopped at 3000, predicts about 22,454 lakh |
| Noise | The bend is bigger than the random wobble from house to house | A high degree is only chasing that wobble. Training error falls, test error does not |
| Explanation | You can say "price is a weighted sum of size and size squared" | The real rule is a threshold, a category, or a sudden change. A tree fits that better |
Pick the smallest degree whose test error is close to the best. Here that is degree 2. If the check column says "do not use it", go back to a line, or on to ridge regression when the curve overfits.
Where polynomial regression is used
- Pricing and demand curves: how price changes with size, age or quantity when the trend bends.
- Science and engineering: calibrating sensors, fitting growth curves and dose-response curves over a limited range.
- Trend lines: short-range trends in business data where a straight line is clearly too simple.
- A building block: the same "expand the features, then use a linear model" trick is used far beyond polynomials.
Benefits: easy to explain, fast to train, closed-form solution, works well for smooth, low-noise relationships.
Limitations:
- Predictions outside the training range can explode.
- High degrees overfit and are sensitive to outliers.
- Powers of are highly correlated, and large values make enormous, so scale your inputs.
- With many input features the number of columns grows quickly.
Common mistakes: choosing the degree by looking at training error; forgetting to expand new inputs before predicting; fitting the expander on test data; trusting a curve outside the data range.
When to choose something else:
| Situation | Try instead |
|---|---|
| The relationship is a straight line | Linear Regression |
| Many features or high degree overfits | Ridge Regression or Lasso, which shrink the weights |
| Sudden jumps, thresholds or many interacting features | Trees and ensembles such as Random Forest Regressor |
| You are unsure why test error is higher than training error | Bias and Variance |
Step 12 of 13
Assessment
Did you understand?
Check your understanding
Start with the coding challenges, then take the quiz. Each quiz answer comes with an explanation.
Step 13 of 13
Recap
What did we learn?
Recap
- Problem solved: predict house prices when price grows faster than size, so a straight line is too stiff.
- Intuition: give a linear model extra columns made from (). The weighted sum of those columns is a curve.
- Mathematics: . It is linear in the weights, so the best weights come from the normal equation . On our data, degree 2 gives , , .
- Internal working: expand the features, then least-squares fit. Degree is a hyperparameter you choose. The weights are parameters the model learns.
- Python:
PolynomialFeaturesplusLinearRegression. Always transform new input the same way before predicting. - Evaluation: judge on held-out houses. Degree 2 had a test RMSE of 2.94 lakh against 10.04 lakh for the line. Training error always falls with degree, test error does not.
- When to use it: one input, a smooth bend, and predictions inside the training range. Degree 2 was enough here. Skip it for straight lines, sharp jumps, many features, or sizes far outside the data.
- Applications and limits: great for smooth curved trends over a known range. Avoid high degrees, extrapolation and unscaled inputs.
Next: keep the same curve but stop it from overfitting with Regularization and Ridge Regression. Prefer the live notebook? Open the full ML Lab.





