Polynomial Linear Regression with Scikit-Learn
Polynomial Linear Regression is a supervised machine learning algorithm used to predict a continuous numerical value when the relationship between the input and output is non-linear.
In this tutorial, we'll build the intuition behind polynomial regression, understand its mathematical foundation, and implement it step by step using Python and scikit-learn.
We'll use the classic Position Salaries dataset to predict an employee's salary based on their position level. Along the way, we'll explore a small "Truth or Bluff" scenario to understand why polynomial regression can sometimes perform better than simple linear regression.
1. Where This Fits: Regression Models
Before learning polynomial regression, let's quickly review the regression models we've already studied.
Simple Linear Regression
Simple Linear Regression models the relationship between one independent variable and one dependent variable using a straight line.
Its mathematical equation is:
For example, predicting salary based on position level:
Here, the model assumes that salary changes at a constant rate as the position level increases.
Multiple Linear Regression
Multiple Linear Regression uses two or more independent variables to predict a dependent variable.
Its mathematical equation is:
For example: predicting salary from position level, years of experience, and education. Each independent variable contributes to the predicted salary.
Polynomial Linear Regression
Polynomial Linear Regression uses different powers of the same independent variable to model a non-linear relationship.
Its mathematical equation is:
Instead of using different independent variables like , we use the same variable , but with different powers.
For example:
This allows the model to learn curved relationships rather than being restricted to a straight line.
2. Why Do We Need Polynomial Regression?
Imagine a dataset showing the relationship between position level and salary, where salaries increase slowly at lower levels, rise rapidly in the middle, and then keep climbing steeply at the top. This is a non-linear relationship because salary doesn't increase at a constant rate.
A straight line, , cannot capture this accelerating pattern. It will sit too high in the middle and too low at the extremes.
To capture a curved relationship, we add polynomial terms:
The squared term lets the model produce a parabola (curve). Adding higher powers (, , …) gives the model more flexibility to fit complex patterns.
Key idea: Polynomial Regression extends Linear Regression by transforming the input features into polynomial features.
Instead of changing the regression algorithm, we change the features we give to it.
3. Understanding the Mathematics
Let's understand polynomial regression through a simple example.
Suppose we have one input, , and one output, .
Depending on the polynomial degree, the model uses different powers of the input variable.
Degree 1 (simple linear):
Here:
- : Intercept
- : Coefficient of the input variable
- : Position level
The model uses only the original input variable. It can produce a straight line.
Degree 2:
The model uses the original input and its square. It can produce a parabolic curve.
Degree 3:
The model includes the third power of the input, allowing more flexible curves.
Degree 4:
The model includes the fourth power, giving it even more flexibility.
What does the degree mean?
The degree determines the highest power of the input variable included in the model.
| Degree | Polynomial features | Model shape |
|---|---|---|
| 1 | Straight line | |
| 2 | Parabola | |
| 3 | More flexible curve | |
| 4 | Even more flexible curve |
Important: A higher degree does not automatically mean a better model.
Higher degrees allow the model to fit more complex patterns, but they also increase the risk of overfitting. We'll explore this limitation later.
4. Why Is It Still Called Linear Regression?
Polynomial regression produces a non-linear curve, so why do we still call it Polynomial Linear Regression?
The answer: linearity refers to the model’s coefficients, not the input variable.
Consider:
The relationship between and is clearly non-linear because of the term. But the coefficients appear in a linear combination. We can rename the polynomial terms as separate features:
Then the equation becomes:
This is exactly a multiple linear regression equation with transformed features.
Therefore:
Polynomial Linear Regression is a special case of Multiple Linear Regression. The model is linear in its coefficients, even though the relationship between the original input and output is non-linear.
This is why we can still use the familiar LinearRegression algorithm from scikit-learn.
5. The Problem: Predicting Position Salaries
Let's understand polynomial regression through a practical scenario.
Imagine you work in an HR department. You want to hire a candidate who previously worked at another company. The candidate claims they earned $160,000 per year and expects the same salary at your company.
Is that reasonable, or a bluff?
You've collected salary information for every position level (1–10) at the candidate's previous company (from sites like Glassdoor). According to their employment information, the candidate worked as a Regional Manager, which is position level 6. But they held that role for two years, so their salary was probably somewhere between level 6 ($150K) and level 7 ($200K). We'll use level 6.5 as the input.
Our plan:
- Train a regression model on the salary data.
- Predict the salary for position level
6.5. - Compare the prediction to the candidate's $160,000 claim.
- Decide whether the claim is reasonable.
We'll compare two models: Simple Linear Regression and Polynomial Linear Regression.
💡 Why no train/test split here? Normally you split data to evaluate generalization. This dataset is tiny (10 rows) and the goal is a single precise prediction, so we train on all the data. In real projects, you'd still use a train/test split or cross-validation.
6. Importing Libraries
First, let's import the libraries we'll need.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd| Library | Purpose |
|---|---|
| NumPy | Working with numerical arrays |
| Matplotlib | Visualizing data and regression curves |
| Pandas | Loading and manipulating datasets |
We'll also import the necessary scikit-learn classes when we start building our models.
7. Creating the Dataset
Our dataset contains position levels and their corresponding salaries.
Since the dataset is small and contains only 10 rows, we can create it directly using a Pandas DataFrame instead of importing a CSV file.
import pandas as pd
data = {
"Position": [
"Business Analyst",
"Junior Consultant",
"Senior Consultant",
"Manager",
"Country Manager",
"Region Manager",
"Partner",
"Senior Partner",
"C-level",
"CEO"
],
"Level": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Salary": [
45000,
50000,
60000,
80000,
110000,
150000,
200000,
300000,
500000,
1000000
]
}
dataset = pd.DataFrame(data)
datasetThe dataset looks like this:
| Position | Level | Salary |
|---|---|---|
| Business Analyst | 1 | 45000 |
| Junior Consultant | 2 | 50000 |
| Senior Consultant | 3 | 60000 |
| Manager | 4 | 80000 |
| Country Manager | 5 | 110000 |
| Region Manager | 6 | 150000 |
| Partner | 7 | 200000 |
| Senior Partner | 8 | 300000 |
| C-level | 9 | 500000 |
| CEO | 10 | 1000000 |
Creating the Independent and Dependent Variables
Before training our models, we need to separate the independent variable (input) from the dependent variable (output).
- Independent variable (X): The position level used to predict salary.
- Dependent variable (y): The salary we want to predict.
Let's prepare them.
target_column = "Salary"
X = dataset.drop(columns=[target_column, "Position"]).values
y = dataset[target_column].values
X[:5], y[:5]Xcontains the position levels (our single feature).ycontains the corresponding salaries.Position(text job titles) is dropped because the numericLevelcolumn already encodes the job hierarchy.
Now we have one independent variable and one dependent variable .
Why
.values? It converts the Pandas DataFrame/Series into a NumPy array, which scikit-learn models expect.
8. Training the Simple Linear Regression Model
Before building our polynomial model, let's train a Simple Linear Regression model.
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)LinearRegression()creates the model object; it hasn't learned anything yet.lin_reg.fit(X, y)learns the coefficients and that best fit the relationship between position level and salary.
The learned equation is:
We can now use this model to make predictions.
9. Training the Polynomial Linear Regression Model
Now the important part. Our polynomial model needs additional features:
We could compute them by hand, but scikit-learn provides a convenient transformer called PolynomialFeatures.
Let's understand how it works.
Step 1: Import the transformer
from sklearn.preprocessing import PolynomialFeaturesPolynomialFeatures is a feature transformation tool. It takes existing input features and generates additional polynomial features based on the specified degree.
Step 2: Create the polynomial feature transformer
poly_reg = PolynomialFeatures(degree=4)degree=4 creates polynomial features up to the fourth power. For a single input variable, this produces:
The first column (constant 1) lets the regression model learn the intercept .
Step 3: Transform the features
X_poly = poly_reg.fit_transform(X)The fit_transform() method learns the feature transformation configuration and applies it to our input data.
Let's understand the transformation with a small example.
Suppose our original input is:
X = [[1],
[2],
[3]]After the degree-4 transformation:
X_poly = [
[1, 1, 1, 1, 1],
[1, 2, 4, 8, 16],
[1, 3, 9, 27, 81]
]
The original single feature has become five columns:
| Original | Constant | ||||
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 4 | 8 | 16 |
| 3 | 1 | 3 | 9 | 27 | 81 |
Notice how each original value generates additional columns containing its powers. This feature transformation is what makes polynomial regression possible.
Step 4: Train a Linear Regression on the polynomial features
Now we can train a Linear Regression model using the transformed dataset.
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)Notice: we're still using
LinearRegression! Polynomial regression is implemented by transforming the features first, then training a linear regression model on those transformed features.
Our final model learns an equation like this:
The model has now learned the coefficients for each polynomial feature. That's it! Our Polynomial Linear Regression model is trained.
10. Visualizing the Simple Linear Regression Results
Let's visualize how well our Simple Linear Regression model fits the dataset.
plt.scatter(X, y, color="red")
plt.plot(X, lin_reg.predict(X), color="blue")
plt.title("Truth or Bluff (Simple Linear Regression)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()Understanding the Visualization
- Red dots: actual salary observations.
- Blue line: the model's predictions.
You'll see a straight blue line that badly misses the middle points (predicting far too high) and the top points (predicting far too low). A straight line simply cannot capture the accelerating pattern. This is why we need polynomial regression.
11. Visualizing the Polynomial Linear Regression Results
Now let's visualize our polynomial model.
plt.scatter(X, y, color="red")
plt.plot(X, lin_reg_2.predict(X_poly), color="blue")
plt.title("Truth or Bluff (Polynomial Linear Regression)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()Critical change: pass
X_polytopredict, notX. The model was trained on the powered-feature matrix, so it must be fed that same matrix at prediction time.
This time, the model produces a curved line instead of a straight line. The curve can capture the non-linear relationship between position levels and salaries much better. The fourth-degree polynomial fits the available observations closely.
This demonstrates why polynomial regression can perform better than simple linear regression when the underlying relationship is non-linear.
12. Predicting a New Result with Simple Linear Regression
Now let's predict the salary for position level 6.5.
lin_reg.predict([[6.5]])Why the double brackets? predict expects a 2D array-like: one dimension for rows (observations), one for columns (features).
[6.5]is 1D — this will error.[[6.5]]is 2D: 1 row × 1 column. ✅
(If you had two features: [[6.5, 5]]. If you had two observations: [[6.5, 5], [2, 3]]. The first bracket pair = rows, the second = columns.)
Result: ~$330,000. That's wildly above the candidate's claim and even above most of the highest salaries in the dataset. The straight-line model is clearly unsuitable here.
13. Predicting a New Result with Polynomial Linear Regression
Finally, let's make the same prediction using our polynomial model.
lin_reg_2.predict(poly_reg.transform([[6.5]]))Two changes from the simple model, broken into three steps:
Step 1: Provide the new input
[[6.5]]Step 2: Transform the input
poly_reg.transform([[6.5]])This produces the polynomial features for level 6.5:
Step 3: Predict
lin_reg_2.predict(poly_reg.transform([[6.5]]))The transformed features are passed to the trained polynomial model, which uses its learned coefficients to predict the salary.
🔑
fit_transformvstransform: During training, usefit_transform(learn the transformation and apply it). At prediction time, usetransformonly (apply the already-learned transformation). Never re-fiton new data.
Result: approximately $159,000.
The predicted salary is close to the candidate's claim, suggesting that the claim is reasonable according to this model.
14. The Verdict
Let's compare the predictions from both models.
| Model | Predicted Salary (level 6.5) | Verdict |
|---|---|---|
| Simple Linear Regression | ~$330,000 | ❌ Absurdly high — unreliable |
| Polynomial Linear Regression | ~$159,000 | ✅ Very close to $160,000 |
The candidate claimed to earn $160,000. The polynomial model predicts approximately $159,000, essentially matching the claim.
Conclusion: The candidate's claim is credible. They're both a good fit for the job and a honest person. You can confidently proceed with the hire.
15. Complete Implementation
Here's everything in one place.
# ---------------------------------------------------------
# Importing Libraries
# ---------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# ---------------------------------------------------------
# Creating the Dataset
# ---------------------------------------------------------
data = {
"Position": [
"Business Analyst",
"Junior Consultant",
"Senior Consultant",
"Manager",
"Country Manager",
"Region Manager",
"Partner",
"Senior Partner",
"C-level",
"CEO"
],
"Level": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Salary": [
45000,
50000,
60000,
80000,
110000,
150000,
200000,
300000,
500000,
1000000
]
}
dataset = pd.DataFrame(data)
# ---------------------------------------------------------
# Preparing the Dataset
# ---------------------------------------------------------
target_column = "Salary"
# Drop the target AND the redundant text "Position" column.
# Keep only the numeric position level as our single feature.
X = dataset.drop(columns=[target_column, "Position"]).values
y = dataset[target_column].values
# ---------------------------------------------------------
# Training the Simple Linear Regression Model
# ---------------------------------------------------------
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
# ---------------------------------------------------------
# Training the Polynomial Linear Regression Model
# ---------------------------------------------------------
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)
# ---------------------------------------------------------
# Visualizing the Simple Linear Regression Results
# ---------------------------------------------------------
plt.scatter(X, y, color="red")
plt.plot(X, lin_reg.predict(X), color="blue")
plt.title("Truth or Bluff (Simple Linear Regression)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
# ---------------------------------------------------------
# Visualizing the Polynomial Linear Regression Results
# ---------------------------------------------------------
plt.scatter(X, y, color="red")
plt.plot(X, lin_reg_2.predict(X_poly), color="blue")
plt.title("Truth or Bluff (Polynomial Linear Regression)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
# ---------------------------------------------------------
# Predicting a New Result with Simple Linear Regression
# ---------------------------------------------------------
print(lin_reg.predict([[6.5]])) # ~ $330,000
# ---------------------------------------------------------
# Predicting a New Result with Polynomial Linear Regression
# ---------------------------------------------------------
print(lin_reg_2.predict(poly_reg.transform([[6.5]]))) # ~ $159,00016. Important Things to Remember
1. Polynomial regression is for non-linear relationships.
When a straight line can't capture the pattern, polynomial terms can.
2. It's a special case of Multiple Linear Regression.
We transform one input into multiple powered features, then train a linear regressor on them.
3. The degree controls complexity.
Higher degree = more flexibility = higher overfitting risk. Tune it to your problem.
4. Feature transformation is essential at both training and prediction.
X_poly = poly_reg.fit_transform(X) # training
poly_reg.transform([[6.5]]) # prediction5. predict needs a 2D array-like.
Use [[6.5]], not [6.5].
6. You don't always need a train/test split.
Here we train on the full dataset because we want the best single prediction. In real projects, use a train/test split or cross-validation.
7. Polynomial regression shines where relationships curve.
Examples: epidemic spread across a population, salary vs. seniority, and many physical processes.
Final Takeaway
Polynomial Linear Regression lets us model non-linear relationships while still using the familiar Linear Regression algorithm.
The process is simple:
Original Input (Position Level: x)
|
v
Polynomial Feature Transformation
(x, x², x³, x⁴)
|
v
Linear Regression
(Learn coefficients)
|
v
Prediction
(Estimated Salary)The most important concept to remember is:
We don't change the regression algorithm itself. We transform the input features to help Linear Regression learn a non-linear relationship.
You've now learned how to build, visualize, and use your first Polynomial Linear Regression model! 🎉