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

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.

Intermediate90 min

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.

Three Hyderabad houses of different sizes with their pricesA 600 square foot house costs 27 lakh rupees, a 1500 square foot house costs 56 lakh, and a 3000 square foot house costs 157 lakh. The biggest house is five times wider than the smallest but costs almost six times as much.600 sq ft₹27 lakh1500 sq ft₹56 lakh3000 sq ft₹157 lakhWidth of each house is proportional to its size. Sample data, not real listings.
The largest house is 5× wider than the smallest, but its price is about 5.8× higher. Size alone does not scale price in a straight line.

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 xx, give it columns made from the size: xx, then x2x^2, then x3x^3 if needed. Ordinary linear regression then learns one weight per column. The weighted sum of those columns is a curve.

Feature expansion turns one input into several columns that a linear model weighsA house of 1.5 thousand square feet becomes three columns: 1, 1.5 and 2.25. Linear regression multiplies them by the weights 13.8159, 11.9945 and 11.4398 to get 13.82, 17.99 and 25.74. Their sum, 57.55 lakh rupees, is the prediction. The weights only multiply and add, so the model is linear in its coefficients even though the result curves with size.Input x1.5PolynomialFeatures(degree=2)[ 1 , 1.5 , 2.25 ]LinearRegressionweights × columnsEach column is multiplied by its own weight, then everything is addedb0 × 113.82b1 × x17.99b2 × x²25.74++prediction ŷ57.55 lakh (1500 sq ft)Weights only multiply and add → linear in b, curved in x

What does the model actually learn?

It learns the weights b0,b1,b2,…b_0, b_1, b_2, \dots. 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.

Chart loads as you scroll…

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.

Chart loads as you scroll…

Slide the degree yourself. Notice that the training error keeps falling as the curve gets more flexible, but the test error does not.

Explorer loads as you scroll…

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

y^=b0+b1x\hat{y} = b_0 + b_1 x
Symbol Say it as Meaning here
y^\hat{y} "y hat" The predicted price in lakh. The hat means "estimated".
xx "x" House size in thousands of square feet (1.5 means 1500 sq ft).
b0b_0 "b zero", the intercept The price the line gives when x=0x = 0. A starting level.
b1b_1 "b one", the slope Extra lakh for each extra 1000 sq ft.

Fitted on our eight training houses, the line has b0=−12.7683b_0 = -12.7683 and b1=50.6982b_1 = 50.6982. For a 1500 sq ft house, x=1.5x = 1.5:

y^=−12.7683+50.6982×1.5\hat{y} = -12.7683 + 50.6982 \times 1.5 y^=−12.7683+76.0473=63.28\hat{y} = -12.7683 + 76.0473 = 63.28

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

y^=b0+b1x+b2x2\hat{y} = b_0 + b_1 x + b_2 x^2

x2x^2 means x×xx \times x. A new weight b2b_2 controls how strongly the curve bends. If b2b_2 is positive the curve bends upward like a smile. Fitted on the same houses, b0=13.8159b_0 = 13.8159, b1=11.9945b_1 = 11.9945, b2=11.4398b_2 = 11.4398. For x=1.5x = 1.5 we have x2=2.25x^2 = 2.25:

y^=13.8159+11.9945×1.5+11.4398×2.25=13.8159+17.9918+25.7396=57.55\begin{aligned} \hat{y} &= 13.8159 + 11.9945 \times 1.5 \\ &\quad + 11.4398 \times 2.25 \\ &= 13.8159 + 17.9918 + 25.7396 \\ &= 57.55 \end{aligned}

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.

Chart loads as you scroll…

Step 3: any degree

y^=b0+b1x+b2x2+⋯+bdxd\hat{y} = b_0 + b_1 x + b_2 x^2 + \dots + b_d x^d y^=∑j=0dbj xj\hat{y} = \sum_{j=0}^{d} b_j \, x^{j}
Symbol Meaning
dd The degree: the highest power of xx the model may use. You choose it.
bjb_j The weight on xjx^j. The model learns it. There are d+1d + 1 weights.
∑j=0d\sum_{j=0}^{d} "Add up the terms for j=0,1,…,dj = 0, 1, \dots, d."
x0x^0 Equals 1, which is why b0b_0 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 dd Wigglier curve up to d−1d - 1 d+1d + 1

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:

x1=x,x2=x2x_1 = x, \qquad x_2 = x^2 y^=b0+b1x1+b2x2\hat{y} = b_0 + b_1 x_1 + b_2 x_2

This is an ordinary weighted sum. If you double every weight, the prediction doubles. The data points (x,x2)(x, x^2) are just numbers computed in advance. The curve appears only when you plot the result against the original xx.

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 y^=b0 eb1x\hat{y} = b_0 \, e^{b_1 x} 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:

SSE(b)=∑i=1n(yi−y^i)2\text{SSE}(b) = \sum_{i=1}^{n} \left( y_i - \hat{y}_i \right)^2

yiy_i is the real price of house ii, y^i\hat{y}_i is the prediction, nn 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:

b=(X⊤X)−1X⊤y\mathbf{b} = \left( X^{\top} X \right)^{-1} X^{\top} \mathbf{y}

Here XX is the table of columns [1, x, x2][1,\ x,\ x^2] for every training house, X⊤X^{\top} is that table flipped so rows become columns, and y\mathbf{y} 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.
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.

  • Input feature xx: size_k, the size in thousands of square feet.
  • Target yy: 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.

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?

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 XX. Each row is [1, x, x2][1,\ x,\ x^2]. The first three training houses:

House 11 xx x2x^2
1 1 0.6 0.36
2 1 0.8 0.64
4 1 1.2 1.44

Compute X⊤XX^{\top}X and X⊤yX^{\top}\mathbf{y}. Each entry is a sum over all eight training houses. For example, the top-left entry is n=8n = 8, and the entry ∑x=0.6+0.8+1.2+1.4+1.8+2.0+2.5+2.8=13.1\sum x = 0.6 + 0.8 + 1.2 + 1.4 + 1.8 + 2.0 + 2.5 + 2.8 = 13.1.

X⊤X=[813.125.7313.125.7356.60925.7356.609133.4801]X^{\top}X = \begin{bmatrix} 8 & 13.1 & 25.73 \\ 13.1 & 25.73 & 56.609 \\ 25.73 & 56.609 & 133.4801 \end{bmatrix} X⊤y=[5621137.22561.46]X^{\top}\mathbf{y} = \begin{bmatrix} 562 \\ 1137.2 \\ 2561.46 \end{bmatrix}

The entries are ∑1, ∑x, ∑x2, ∑x3, ∑x4\sum 1,\ \sum x,\ \sum x^2,\ \sum x^3,\ \sum x^4 and ∑y, ∑xy, ∑x2y\sum y,\ \sum xy,\ \sum x^2 y. The notebook below prints the same matrices from NumPy.

Solve the three equations:

b=(X⊤X)−1X⊤y=[13.815911.994511.4398]\mathbf{b} = \left(X^{\top}X\right)^{-1} X^{\top}\mathbf{y} = \begin{bmatrix} 13.8159 \\ 11.9945 \\ 11.4398 \end{bmatrix}

Check it. Put b\mathbf{b} back into the first equation: 8×13.8159+13.1×11.9945+25.73×11.4398=562.08 \times 13.8159 + 13.1 \times 11.9945 + 25.73 \times 11.4398 = 562.0, which matches ∑y=562\sum y = 562.

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 27−25.13=1.8727 - 25.13 = 1.87 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 X⊤XX^{\top}X directly.

Now do the same with NumPy:

Notebook loads as you scroll…

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 x2x^2. include_bias=False skips the column of ones because LinearRegression already learns b0b_0.
poly2.fit_transform(X_train) Learns the setup from the training data and returns the expanded table with columns x,x2x, x^2.
poly2.transform(X_test) Applies the same expansion without learning anything new.
LinearRegression().fit(X_train_poly, y_train) Training. Solves for b0,b1,b2b_0, b_1, b_2.
.intercept_ and .coef_ The learned b0b_0 and [b1,b2][b_1, b_2].
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.

Notebook loads as you scroll…

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.

Explorer loads as you scroll…

Now repeat the experiment in code. Change degree, my_size_k or the data cell:

Notebook loads as you scroll…

Things to try:

  1. Set degree = 1, then 2, then 6, and compare the 1800 sq ft prediction.
  2. 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.
  3. 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.

Worked example for the degree-2 model on the four test houses. The errors y−y^y - \hat{y} are 2.75, -1.55, -2.57 and 4.24.

MAE=2.75+1.55+2.57+4.244=2.78\begin{aligned} \text{MAE} &= \frac{2.75 + 1.55 + 2.57 + 4.24}{4} \\ &= 2.78 \end{aligned} MSE=2.752+1.552+2.572+4.2424=8.64\begin{aligned} \text{MSE} &= \frac{2.75^2 + 1.55^2 + 2.57^2 + 4.24^2}{4} \\ &= 8.64 \end{aligned} RMSE=8.64=2.94\text{RMSE} = \sqrt{8.64} = 2.94

For R2R^2 we compare with always guessing the average test price (86.5 lakh): SST=8105.0\text{SST} = 8105.0, SSE=34.57\text{SSE} = 34.57, so R2=1−34.57/8105.0=0.996R^2 = 1 - 34.57 / 8105.0 = 0.996. The notebook below prints the same numbers from NumPy and from scikit-learn.

Notebook loads as you scroll…

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: R2R^2 was 0.996 for degree 2, but a high R2R^2 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 (xx, x2x^2, …) 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 xx are highly correlated, and large xx values make x6x^6 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.

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

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 xx (x2,x3,…x^2, x^3, \dots). The weighted sum of those columns is a curve.
  • Mathematics: y^=b0+b1x+⋯+bdxd\hat{y} = b_0 + b_1 x + \dots + b_d x^d. It is linear in the weights, so the best weights come from the normal equation b=(X⊤X)−1X⊤y\mathbf{b} = (X^{\top}X)^{-1}X^{\top}\mathbf{y}. On our data, degree 2 gives b0=13.8159b_0 = 13.8159, b1=11.9945b_1 = 11.9945, b2=11.4398b_2 = 11.4398.
  • Internal working: expand the features, then least-squares fit. Degree is a hyperparameter you choose. The weights are parameters the model learns.
  • Python: PolynomialFeatures plus LinearRegression. 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.