Skip to main content
LearnMLAcademy
Intermediate10 min read

Polynomial Regression

Fit polynomial regression curves while preventing high-variance overfitting, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Polynomial Regression

Polynomial Regression is a form of Regression used when the relationship between variables is nonlinear. Instead of fitting a straight line, it bends the line to fit the curves of the dataset.

Polynomial Regression in Simple Words

Linear Regression tries to describe a pattern with a straight line. Polynomial Regression is useful when the pattern clearly bends or curves. It gives the model extra features such as x² and x³ so a linear model can follow that curve.

1. Look at the data

Do the points roughly follow a straight line or a curve?

2. Add polynomial terms

For degree 2, x becomes x and x².

3. Fit the model

Linear Regression learns coefficients for the new columns.

A tiny example: the rate of change is not constant

xyIncrease in y
12—
25+3
310+5
417+7

The increase changes from +3 → +5 → +7. That is a clue that a straight line may be too simple. In fact, these values follow the easy curve y = x² + 1.

What is Polynomial Regression?

Polynomial Regression is a supervised machine learning algorithm that models nonlinear relationships between the independent variable and dependent variable by using polynomial terms.

Although it is called "polynomial," it still belongs to the family of linear models because the coefficients are learned linearly.

Real-Life Intuition

Consider the relationships between:

  • Temperature and electricity usage
  • Age and income
  • Advertisement spending and sales
  • Speed and fuel efficiency

These relationships can be curved rather than perfectly straight. A straight line may underfit such a pattern, while polynomial terms can sometimes capture the curvature more effectively.

Visual Understanding of Polynomial Regression

Linear Relationship

Straight line follows a constant-rate trend

Polynomial Relationship

A curve can follow a changing-rate pattern

Why Polynomial Regression is Needed

Linear Regression Assumes:

  • A straight-line form between the created features and target
  • A constant slope when only the original x feature is used

But Real-World Data Contains:

  • Curved relationships
  • Changing rates of increase or decrease
  • Patterns a straight line may underfit

Polynomial Regression can model some smooth nonlinear patterns by adding powers of the original features. Whether it predicts better must be checked on validation or unseen data.

Core Idea of Polynomial Regression

Polynomial Regression transforms features into higher-degree polynomial terms.

Instead of a simple line equation:

y = m*x + c

It expands into a polynomial of degree `n`:

y = b₀ + b₁x + b₂x² + b₃x³ + ... + bₙxⁿ

Where Polynomial Regression Fits

Regression

Linear Regression

Uses the original features to fit a straight-line relationship.

Polynomial Regression

Adds powers such as x² and x³, then fits a linear model to those features.

Degree 2: QuadraticDegree 3: CubicHigher Degree

Understanding Polynomial Degrees

1. Quadratic Regression (Degree 2)

Produces a parabola-shaped curve.

Formula

y = b₀ + b₁x + b₂x²

Worked Example

Suppose:

  • b₀ = 2
  • b₁ = 3
  • b₂ = 1
  • x = 2

Step 1 — Substitute x = 2

y = 2 + 3(2) + 1(2²)

Put the given value of x into every x term.

Step 2 — Calculate powers and multiplication

y = 2 + 6 + 4

2² = 4, so the curved x² term contributes 4.

Step 3 — Add the terms

y = 12

Quadratic Curve Visualization

2. Cubic Regression (Degree 3)

Captures more complex nonlinear relationships.

Formula

y = b₀ + b₁x + b₂x² + b₃x³

Worked Example

Suppose:

  • b₀ = 1
  • b₁ = 2
  • b₂ = 1
  • b₃ = 1
  • x = 2

Step 1 — Substitute x = 2

y = 1 + 2(2) + 1(2²) + 1(2³)

Step 2 — Calculate each term

y = 1 + 4 + 4 + 8

Here 2² = 4 and 2³ = 8.

Step 3 — Add the terms

y = 17

Cubic Curve Visualization

Feature Transformation

Polynomial Regression converts original features into polynomial features. By doing this, it treats the higher powers as completely new variables and trains a linear model on them.

Example Transformation (Degree 4)

x
x, x², x³, x⁴

The dataset width grows. If a row had just [3] as its feature, the useful degree-4 terms are [3, 9, 27, 81]. Scikit-learn can also add a constant bias column unless include_bias=False.

Transformation Workflow

Original Input
Generate Polynomial Features
x, x², x³, x⁴
Train Linear Model
Curved Predictions

Difference Between Linear and Polynomial Regression

FeatureLinear RegressionPolynomial Regression
RelationshipStraight lineCurved
ComplexitySimpleMore complex
Curved patternMay underfitCan capture curvature
Risk of overfittingUsually lower complexityCan rise with degree
Feature engineeringOriginal featuresAdds polynomial terms

Cost Function in Polynomial Regression

Polynomial Regression for a continuous target can use the same regression losses as Linear Regression. A common choice is Mean Squared Error (MSE), which measures the average squared prediction error.

MSE Formula

MSE = 1/n * Σ (y_i - ŷ_i)²

Where y_i is actual, and ŷ_i is predicted.

Worked numerical Example

Actual (y)Predicted (ŷ)Squared Error
54(5 - 4)² = 1
810(8 - 10)² = 4
1211(12 - 11)² = 1

Step 2 — Add the squared errors

1 + 4 + 1 = 6

Step 3 — Divide by the 3 observations

MSE = 6 / 3

MSE = 2

Overfitting & Choosing the Degree

The polynomial degree controls how flexible the curve can become. Too low a degree may miss the pattern, while an unnecessarily high degree can start fitting noise and perform poorly on unseen data. Choose the degree using validation data or cross-validation rather than a fixed rule.

Underfitting

Degree 1 (Straight)
●       ●
  ●   ●

Cannot capture the true pattern.

Good Fit

Example: Degree 2 or 3
●     ●       ●

Smooth curve follows trend.

Overfitting

Very High Degree
● ● ● ● ●

May bend around noise instead of learning the general trend.

Important: degree 2 or 3 is not automatically the best choice. Try reasonable degrees and compare validation or cross-validation performance. See Cross-Validation for the idea of checking performance on unseen folds.

Advantages

AdvantageExplanation
Captures nonlinear dataCan represent smooth curvature
FlexibleDegree controls model flexibility
Better accuracyCan outperform a straight line on suitable data
Extension of LRFamiliar mathematical foundation

Disadvantages

DisadvantageExplanation
Overfitting riskHigher degrees can fit noise
Feature count can growMore polynomial and interaction terms may be created
Sensitive to outliersSquared-error fitting can be influenced by extreme observations
Harder interpretationComplex coefficients

Assumptions & Practical Checks

Polynomial Regression is linear in its learned coefficients, so many Linear Regression assumptions still matter. Some checks are especially important when you want statistical inference, while others are practical modeling choices.

Independent Observations

Data points must be independent; one sample should not influence another.

Correlated Polynomial Terms

Polynomial terms such as x, x² and x³ can be strongly correlated. This can make individual coefficients unstable or harder to interpret, especially at high degrees.

Continuous Target

Polynomial regression is normally used to predict a numeric continuous target, such as price, temperature or score.

Choose Degree with Validation

Degree is a model-choice decision, not a statistical assumption. Compare candidate degrees on validation data or with cross-validation.

Random Errors

Residuals should not show a strong systematic pattern. Roughly constant error variance matters for classical inference, and residual normality is mainly relevant when constructing traditional significance tests or confidence intervals.

Industry Applications Tree

Polynomial Regression Applications
Finance
  • Stock Trend Analysis
  • Revenue Forecasting
  • Risk Modeling
Healthcare
  • Disease Progression
  • Drug Response Analysis
  • Medical Forecasting
Manufacturing
  • Production Optimization
  • Quality Prediction
  • Equipment Failure
Retail
  • Sales Forecasting
  • Seasonal Demand
  • Customer Trend Modeling
Scientific Research
  • Physics Experiments
  • Climate Modeling
  • Biological Growth

Implementation of Polynomial Regression in Python

Polynomial Regression is used when the relationship between the input variable and output variable is not perfectly linear. Instead of fitting a straight line, polynomial regression fits a curved line to better capture complex patterns in the data. In this example, we will build a polynomial regression model using Python and compare it with a simple linear regression model.

Teaching note: this tiny example fits all 10 rows so you can see the mechanics clearly. In a real project, compare candidate degrees using a validation set or cross-validation before judging which model generalizes better.

Step 1: Import the Required Libraries

First, import the necessary Python libraries for data handling, visualization, and machine learning.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
LibraryPurpose
NumPyUsed for numerical operations
PandasHelps load and manage datasets
MatplotlibUsed for plotting graphs
LinearRegressionCreates the regression model
PolynomialFeaturesConverts normal features into polynomial features

Step 2: Create and Load the Dataset

Instead of using an external dataset, let us create a custom dataset related to study hours and exam scores.

data = {
    'Study_Hours': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'Exam_Score': [45, 50, 54, 60, 68, 78, 85, 91, 96, 98]
}

df = pd.DataFrame(data)

print(df)
Sample Output Study_Hours Exam_Score 0 1 45 1 2 50 2 3 54 3 4 60 4 5 68 ...

Study_Hours → Independent variable (X)
Exam_Score → Dependent variable (Y)

Step 3: Separate Features and Target Variables

Now split the dataset into input and output variables.

X = df[['Study_Hours']].values
y = df['Exam_Score'].values

Here, X stores the feature values and y stores the target values.

Step 4: Train the Linear Regression Model

Before applying polynomial regression, first fit a simple linear regression model.

linear_model = LinearRegression()
linear_model.fit(X, y)

The model learns the relationship between study hours and exam scores using a straight line.

Step 5: Create and Train the Polynomial Regression Model

Now transform the input data into polynomial features and train another regression model.

poly_features = PolynomialFeatures(degree=3, include_bias=False)

X_poly = poly_features.fit_transform(X)

poly_model = LinearRegression()

poly_model.fit(X_poly, y)

Why Polynomial Features?

  • Polynomial regression creates additional feature columns such as X², X³, and higher-order terms.
  • These extra features help the model capture curved relationships in the data.
  • In this example, degree=3 creates x, x², and x³. We use include_bias=False because LinearRegression already learns an intercept by default.

Step 6: Visualize Linear Model

plt.scatter(X, y, color='blue')
plt.plot(X, linear_model.predict(X), color='red')
plt.title('Linear Regression Model')
plt.xlabel('Study Hours')
plt.ylabel('Exam Score')
plt.show()

Linear Regression Model

Explanation:

Blue dots represent the actual data points. The red line represents predictions from linear regression. Since linear regression uses a straight line, it may not perfectly fit all points if the data follows a curve.

Step 7: Visualize Polynomial Model

plt.scatter(X, y, color='blue')
plt.plot(X,
    poly_model.predict(poly_features.transform(X)),
    color='red')
plt.title('Polynomial Regression Model')
plt.xlabel('Study Hours')
plt.ylabel('Exam Score')
plt.show()

Polynomial Regression Model

Explanation:

The polynomial curve bends according to the data pattern. This often produces more accurate predictions for non-linear datasets compared to the rigid straight line.

Step 8: Predict New Values

Let us predict the exam score for a student who studies for 7.5 hours.

Linear Prediction

new_value = np.array([[7.5]])
linear_prediction = linear_model.predict(new_value)
print(linear_prediction)
[85.46]

Polynomial Prediction

poly_prediction = poly_model.predict(
    poly_features.transform(new_value)
)
print(poly_prediction)
[88.20]

The polynomial regression model may provide a more realistic prediction (88.20) than the straight-line prediction (85.46) for this input. Which model is actually better should be decided using validation or test data, not by preferring the curved answer automatically.

Complete Python Code

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# 1. Create Dataset
data = {
    'Study_Hours': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'Exam_Score': [45, 50, 54, 60, 68, 78, 85, 91, 96, 98]
}

df = pd.DataFrame(data)

# 2. Features and Target
X = df[['Study_Hours']].values
y = df['Exam_Score'].values

# 3. Linear Regression Model Training
linear_model = LinearRegression()
linear_model.fit(X, y)

# 4. Polynomial Feature Expansion & Model Training
poly_features = PolynomialFeatures(degree=3, include_bias=False)
X_poly = poly_features.fit_transform(X)

poly_model = LinearRegression()
poly_model.fit(X_poly, y)

# 5. Linear Regression Plot
plt.scatter(X, y, color='blue')
plt.plot(X, linear_model.predict(X), color='red')
plt.title('Linear Regression Model')
plt.xlabel('Study Hours')
plt.ylabel('Exam Score')
plt.show()

# 6. Polynomial Regression Plot
plt.scatter(X, y, color='blue')
plt.plot(X, poly_model.predict(poly_features.transform(X)), color='red')
plt.title('Polynomial Regression Model')
plt.xlabel('Study Hours')
plt.ylabel('Exam Score')
plt.show()

# 7. Make Predictions
new_value = np.array([[7.5]])
linear_prediction = linear_model.predict(new_value)
poly_prediction = poly_model.predict(poly_features.transform(new_value))

print("Linear Regression Prediction:", linear_prediction)
print("Polynomial Regression Prediction:", poly_prediction)

Evaluation Metrics

Polynomial Regression uses standard regression metrics to tell how well our curve fits the data:

1. Mean Absolute Error (MAE)

MAE = 1/n * Σ |y_i - ŷ_i|

Average of absolute error magnitudes.

2. Root Mean Squared Error (RMSE)

RMSE = √[1/n * Σ (y_i - ŷ_i)²]

Gives larger errors more influence because errors are squared before taking the square root.

3. R² Score

R² = 1 - (SS_res / SS_tot)

1.0 is perfect. Around 0 means performance similar to predicting the target mean; R² can also be negative.

Polynomial vs Other Algorithms

AlgorithmRelationship TypeComplexityInterpretability
Linear RegressionLinearLowHigh
Polynomial RegressionNonlinearMediumMedium
Decision TreeNonlinearMediumMedium
Random ForestNonlinearHighLow
Neural NetworksHighly nonlinearVery HighLow

Common Questions About Polynomial Regression

Is Polynomial Regression really nonlinear?

Its prediction can curve with x, but the model is still linear in the coefficients it learns after polynomial features are created.

How do I choose degree 2, 3, 4, or higher?

Start with small degrees and compare validation or cross-validation performance. Do not choose a high degree only because it fits training data more closely.

Does Polynomial Regression always beat Linear Regression?

No. If the real relationship is approximately straight, the simpler linear model may generalize just as well or better.

What should I learn next?

See Ridge Regression and Lasso Regression to learn how regularization can control overly flexible models. You can also review Linear Regression first.

Final Summary

Polynomial Regression is a powerful extension of Linear Regression designed to model nonlinear relationships. It expands features and fits a curve rather than a straight line.

Increasing the polynomial degree makes the model more flexible, but too much flexibility can fit noise and hurt generalization. A good workflow is to try modest degrees, monitor validation error, use cross-validation, and consider scaling or regularization when polynomial features become large or highly correlated.

Most Important Insight to Remember:

"Polynomial Regression keeps a linear model in the coefficients, but changes the input representation with terms such as x² and x³ so the prediction can follow a smooth curve."

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Polynomial Regression"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Polynomial regression adds powers and interactions but stays linear in its coefficients.
  • Higher degree captures more curved relationships.
  • Transformations and scaling belong inside the pipeline.
  • Very high degree can oscillate, overfit, and extrapolate badly.
  • Choose degree with cross-validation, not training error.
  • Regularization and residual plots help control added complexity.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
A scatter plot of engine_temperature vs efficiency shows an inverted-U shape. What does this suggest?
Question 2 of 4
You fit polynomial regression with degrees 1, 2, 3, 5, 10, 20 and plot training vs validation MSE. Describe what you expect.
Question 3 of 4
With degree-2 polynomial and 30 original features, how many total features does PolynomialFeatures produce?
Question 4 of 4
Ridge regression is applied to a degree-15 polynomial that wildly oscillates between training points. What does Ridge do?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1A scatter plot of engine_temperature vs efficiency shows an inverted-U shape. What does this suggest?▼

Correct Answer: This is a degree-2 polynomial relationship. Adding temperature² as a feature lets a linear model capture this curvature — without it, linear regression would fit a flat line through the peak

The inverted-U is a quadratic relationship. A linear model cannot produce this shape. Adding the squared term gives the mathematical flexibility to capture the optimum.

2You fit polynomial regression with degrees 1, 2, 3, 5, 10, 20 and plot training vs validation MSE. Describe what you expect.▼

Correct Answer: Training MSE decreases consistently. Validation MSE decreases initially (capturing real curvature), then increases at high degrees (fitting noise). The optimal degree is where validation MSE is minimised

This is the bias-variance tradeoff made concrete. Degree 1 has high bias. Degree 20 has high variance. The validation curve reveals the best tradeoff.

3With degree-2 polynomial and 30 original features, how many total features does PolynomialFeatures produce?▼

Correct Answer: 496 features: 30 originals + 30 squared terms + 435 pairwise interactions + 1 bias

Degree-2: 1 bias + 30 original + 30 squared + (30×29/2)=435 interactions = 496 total. This dimensionality explosion requires feature selection or regularisation.

4Ridge regression is applied to a degree-15 polynomial that wildly oscillates between training points. What does Ridge do?▼

Correct Answer: Ridge penalises large coefficient magnitudes — the wild oscillations come from very large positive and negative coefficients. Ridge shrinks them toward zero, creating a smoother curve without removing polynomial terms

High-degree polynomial oscillation (Runge's phenomenon) is caused by extremely large coefficients of alternating sign. Ridge's L2 penalty prevents them from growing large, damping oscillation while retaining flexibility.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next