Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathPredict a Number: Regression from Scratch to Regularisation
  1. 1
    Linear Regression and the Cost Function: Draw a Line, Score It
  2. 2
    Gradient Descent Explained: Feel the Slope, Step Downhill
  3. 3
    Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
  4. 4
    Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
  5. 5
    Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
  6. 6
    Regularisation with Ridge and Lasso: Put a Price on Big Weights
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Predict a Number: Regression from Scratch to Regularisation · Step 5 of 6

Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score

Give a linear model extra columns with PolynomialFeatures and it can bend. Then watch train and test scores split apart: degrees 1, 2 and 16 on Canada's income per person, and degrees 1 to 5 on the insurance model.

Chaand Sheikh

·27 November 2026Regression

What you will learn

  • Use PolynomialFeatures to let a linear model draw a curve
  • Compare train and test R-squared as the degree grows
  • Recognise underfitting (high bias) and overfitting (high variance) from the two scores
  • Add a polynomial step to a preprocessing pipeline

Before you start

  • Linear Regression in scikit-learn
  • Regression Metrics: MAE, RMSE, R-squared

Three students prepare for the same exam.

  • The first one skipped the classes. 40% on the practice papers, 38% in the real exam. Bad everywhere. That's underfitting.
  • The second one memorised the past papers. 100% at home, but the real exam has new questions and the score falls to 45%. That's overfitting.
  • The third one understood the topic. 85% at home, 82% in the exam. Good on both. Just right.

The practice papers are your training data and the real exam is your test data. Only the exam tells the truth. In this lesson you'll let a straight line bend, and watch what happens to both scores.

One number becomes four columns

A straight line can't bend. The trick is to give the model extra columns: x squared, x cubed, and so on. PolynomialFeatures does exactly that:

from sklearn.preprocessing import PolynomialFeatures

print(PolynomialFeatures(degree=3).fit_transform([[2]]))
[[1. 2. 4. 8.]]

The number 2 with degree 3 becomes four columns: 1, x, x2 and x3, so 1, 2, 4 and 8. The model then gives each column its own weight:

y_hat = w0 + w1·x + w2·x2 + w3·x3

That's still a straight line in the weights, so the model is still plain LinearRegression. But drawn against x, it's a curve. A higher degree means more bends.

Canada: income per person by year

Start with a small dataset with one input, so you can draw it: income per person in Canada, by year.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

canada = pd.read_csv("canada_per_capita_income.csv")
canada.columns = ["year", "income"]
print(canada.shape)
(47, 2)
X = canada[["year"]]
y = canada["income"]
# a small train set makes overfitting easy to see
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.6, random_state=42)
print(len(X_train), len(X_test))
18 29

47 years. With test_size=0.6, only 18 years are used for learning and 29 for testing. That small training set is on purpose: it makes overfitting easy to see.

Three degrees, train vs test

The same pipeline at three degrees: scale, then PolynomialFeatures, then LinearRegression. Only the degree changes, and the scaler learns from the training years only.

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression

models = {}
for degree in [1, 2, 16]:
    model = Pipeline([
        ("scale", StandardScaler()),
        ("poly", PolynomialFeatures(degree=degree)),
        ("reg", LinearRegression()),
    ])
    model.fit(X_train, y_train)
    models[degree] = model
    train = round(model.score(X_train, y_train), 3)
    test = round(model.score(X_test, y_test), 3)
    print(degree, train, test)
1 0.905 0.858
2 0.923 0.909
16 0.999 0.404

score returns R-squared (see Regression Metrics). Degree 2 beats degree 1 on both train and test. Degree 16 is almost perfect on train, 0.999, but only 0.404 on test. That's the student who memorised the past papers.

The three curves, drawn

plt.figure(figsize=(6.4, 3.0))
plt.scatter(X_train, y_train, color="black", label="train")
plt.scatter(X_test, y_test, color="red", label="test")
for degree, model in models.items():
    plt.plot(X, model.predict(X), label=f"degree {degree}")
plt.ylim(0, 50000)
plt.legend()
plt.show()
Canada income per person from 1970 to 2016, with black training dots and red test dots rising from about 4,000 to over 40,000 dollars. The blue degree 1 line is straight and misses both ends. The orange degree 2 curve bends gently and follows the trend. The green degree 16 curve hugs the black dots, drops below the axis near 1972 and swings sharply near 2014 to 2016.
Degree 1 (blue) is too stiff and misses both ends. Degree 2 (orange) bends once and follows the trend. Degree 16 (green) hugs the training dots and swings wildly at the edges.

The insurance model, now bendable

Now the same idea on the insurance data from Linear Regression in scikit-learn. A small function builds the pipeline for any degree. The preprocessing is the usual one, with one change: the number columns are now scaled. Then there's one new step between preprocessing and the model.

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder

df = pd.read_csv("insurance.csv")
X = df.drop(columns="charges")
y = df["charges"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)
num_cols = X.select_dtypes(include="number").columns
cat_cols = X.select_dtypes(exclude="number").columns

def poly_model(degree):
    num = Pipeline([
        ("impute", SimpleImputer(strategy="median")),
        ("scale", StandardScaler())])
    cat = Pipeline([
        ("impute", SimpleImputer(strategy="most_frequent")),
        ("onehot", OneHotEncoder(
            drop="first", handle_unknown="ignore"))])
    preprocess = ColumnTransformer([
        ("num", num, num_cols),
        ("cat", cat, cat_cols)])
    return Pipeline([
        ("preprocess", preprocess),
        ("poly", PolynomialFeatures(degree=degree)),
        ("reg", LinearRegression()),
    ])

The scaler comes before PolynomialFeatures, so the squares and cubes stay small.

Degree 1 to 5, train vs test

for degree in range(1, 6):
    model = poly_model(degree).fit(X_train, y_train)
    n_cols = model.named_steps["poly"].n_output_features_
    train = round(model.score(X_train, y_train), 3)
    test = round(model.score(X_test, y_test), 3)
    print(degree, n_cols, train, test)
1 9 0.742 0.784
2 45 0.842 0.867
3 165 0.855 0.849
4 495 0.876 0.754
5 1287 0.906 -0.264

The columns are degree, number of columns, train R-squared and test R-squared. Look at the columns first: 9, 45, 165, 495, 1,287. They explode, because PolynomialFeatures also multiplies columns together.

  • Degree 2 has the best test score, 0.867.
  • At degree 4, train still climbs to 0.876, but test drops to 0.754.
  • At degree 5, test is -0.264: worse than just guessing the mean.
Train vs test R squared by degree -0.4 0 0.5 1 R squared degree 1 9 cols degree 2 45 cols degree 3 165 cols degree 4 495 cols degree 5 1,287 cols 0.742 0.784 0.842 0.867 0.855 0.849 0.876 0.754 0.906 -0.264 train test degree 1:underfit degree 2:sweet spot degree 4-5:overfit
Train R-squared (blue) keeps climbing as the columns explode. Test R-squared (red) peaks at degree 2, then falls below zero at degree 5.

Bias and variance

Read the two scores together:

What you seeNameWhat to try
Train low, test lowUnderfitting, high bias: too simple to see the patternMore bends (a higher degree), better columns
Both high and close togetherThe sweet spotKeep it (degree 2 here)
Train high, test much lowerOverfitting, high variance: it learned the noiseFewer bends, or more data

A train score on its own can't tell these apart. Degree 5 has the best train score of all and the worst test score.

Common mistakes

  • Choosing the degree by the train score. Train always goes up with more bends. Choose by the test score.
  • Forgetting how fast the columns grow. Six raw columns became 1,287 at degree 5.
  • Skipping the scaler. Without it, squares and cubes of large numbers get huge.

Quick recap

DatasetDegreeTrain R2Test R2Verdict
Canada10.9050.858Too stiff
Canada20.9230.909Best
Canada160.9990.404Overfit
Insurance20.8420.867Best
Insurance50.906-0.264Overfit

The degree-4 model overfits, but it can be tamed without lowering the degree. That's Regularisation with Ridge and Lasso.

Try it yourself

Run the Canada degree loop with test_size=0.2 instead of 0.6. Does degree 16 still overfit as badly? Why does more training data help?

The notebook and the datasets are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Next →
Regularisation with Ridge and Lasso: Put a Price on Big Weights
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

On this page
  • One number becomes four columns
  • Canada: income per person by year
  • Three degrees, train vs test
  • The three curves, drawn
  • The insurance model, now bendable
  • Degree 1 to 5, train vs test
  • Bias and variance
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.