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
| x | y | Increase in y |
|---|---|---|
| 1 | 2 | — |
| 2 | 5 | +3 |
| 3 | 10 | +5 |
| 4 | 17 | +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 + cIt expands into a polynomial of degree `n`:
y = b₀ + b₁x + b₂x² + b₃x³ + ... + bₙxⁿWhere Polynomial Regression Fits
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.
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)
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
Difference Between Linear and Polynomial Regression
| Feature | Linear Regression | Polynomial Regression |
|---|---|---|
| Relationship | Straight line | Curved |
| Complexity | Simple | More complex |
| Curved pattern | May underfit | Can capture curvature |
| Risk of overfitting | Usually lower complexity | Can rise with degree |
| Feature engineering | Original features | Adds 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 |
|---|---|---|
| 5 | 4 | (5 - 4)² = 1 |
| 8 | 10 | (8 - 10)² = 4 |
| 12 | 11 | (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
● ●
Cannot capture the true pattern.
Good Fit
Smooth curve follows trend.
Overfitting
May bend around noise instead of learning the general trend.
Advantages
| Advantage | Explanation |
|---|---|
| Captures nonlinear data | Can represent smooth curvature |
| Flexible | Degree controls model flexibility |
| Better accuracy | Can outperform a straight line on suitable data |
| Extension of LR | Familiar mathematical foundation |
Disadvantages
| Disadvantage | Explanation |
|---|---|
| Overfitting risk | Higher degrees can fit noise |
| Feature count can grow | More polynomial and interaction terms may be created |
| Sensitive to outliers | Squared-error fitting can be influenced by extreme observations |
| Harder interpretation | Complex 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
- Stock Trend Analysis
- Revenue Forecasting
- Risk Modeling
- Disease Progression
- Drug Response Analysis
- Medical Forecasting
- Production Optimization
- Quality Prediction
- Equipment Failure
- Sales Forecasting
- Seasonal Demand
- Customer Trend Modeling
- 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.
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| Library | Purpose |
|---|---|
| NumPy | Used for numerical operations |
| Pandas | Helps load and manage datasets |
| Matplotlib | Used for plotting graphs |
| LinearRegression | Creates the regression model |
| PolynomialFeatures | Converts 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)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'].valuesHere, 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=3createsx,x², andx³. We useinclude_bias=FalsebecauseLinearRegressionalready 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)Polynomial Prediction
poly_prediction = poly_model.predict(
poly_features.transform(new_value)
)
print(poly_prediction)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)
Average of absolute error magnitudes.
2. Root Mean Squared Error (RMSE)
Gives larger errors more influence because errors are squared before taking the square root.
3. R² Score
1.0 is perfect. Around 0 means performance similar to predicting the target mean; R² can also be negative.
Polynomial vs Other Algorithms
| Algorithm | Relationship Type | Complexity | Interpretability |
|---|---|---|---|
| Linear Regression | Linear | Low | High |
| Polynomial Regression | Nonlinear | Medium | Medium |
| Decision Tree | Nonlinear | Medium | Medium |
| Random Forest | Nonlinear | High | Low |
| Neural Networks | Highly nonlinear | Very High | Low |
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."