Polynomial Regression
Imagine you are observing the trajectory of an object falling from the sky; its falling speed is not uniform but increases faster and faster. If you use a straight line to fit this trajectory, the result will be poor, because a straight line cannot describe such a curved change. At this point, we need a line that can bend — polynomial regression is a powerful tool for solving this kind of problem.
Simply put,Polynomial RegressionIt is an extension of linear regression. By adding higher-degree terms (such as squared and cubic terms) to the original features, it maps the data into a higher-dimensional space, thereby fitting the nonlinear relationships in the data with a "curve."
I. Core Concepts: From Straight Lines to Curves
1.1 Review of Linear Regression
The model formula for linear regression is very simple: y = w₁ * x + b Where:
yis the target value we want to predict.xis the input feature.w₁is the weight (slope) of the feature.bis the bias term (intercept).
This model determines that it can only draw astraight line。
1.2 Introducing Polynomial Regression
The core idea of polynomial regression is:Treat higher powers of the features as new features, and then apply linear regression on this expanded feature set.
For example, a quadratic polynomial regression model: y = w₁ * x + w₂ * x² + b
You see, although the equation contains x², but if we treat x and x² as two independent features X1 and X2, then the model becomes: y = w₁ * X1 + w₂ * X2 + b This is essentially still aLinear models, except that it is with respect toFeatures X1 and X2 linear. That is why we say polynomial regression is an "extension of linear regression."
1.3 Key Terms
- Degree / Order: The highest exponent in a polynomial. A degree of 2 is a quadratic curve (parabola), a degree of 3 is a cubic curve, and so on.
- Overfitting: If the chosen degree is too high, the model becomes very "twisty," passing perfectly through all the training data points, but its predictive ability on new data drops sharply. It is like using a complex net to catch a few points — if the mesh is too fine, you end up catching no big fish.
- Underfitting: If the degree is too low (for example, using a straight line to fit clearly curved data), the model cannot capture the basic patterns in the data, and its predictive ability is equally poor.
The flowchart below shows the typical thought process for applying polynomial regression:

II. Practical: Implementing Polynomial Regression with Python
We will use scikit-learn This powerful machine learning library makes implementing polynomial regression very simple.
2.1 Preparing the Environment and Data
First, make sure the necessary libraries are installed, and create a set of simulated nonlinear data.
Example
Import the necessary libraries
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
preprocessing
import
PolynomialFeatures
from
sklearn.
linear_model
import
LinearRegression
from
sklearn.
metrics
import
mean_squared_error
,
r2_score
Set the random seed to ensure consistent results across runs
np.
random
.
seed
(
42
)
Create simulated data: y is a quadratic function of x plus some random noise
X
=
6
- np.
random
.
rand
(
100
,
1
)
3
Generate 100 random numbers in the interval [-3, 3)
y
=
0.5
- X**
2
- X +
2
- np.
random
.
randn
(
100
,
1
)
y = 0.5x² + x + 2 + noise
Visualize the original data
plt.
scatter
(
X
,
y
,
s
=
10
,
alpha
=
0.7
,
label
=
'Original Data'
)
plt.
xlabel
(
'X'
)
plt.
ylabel
(
'y'
)
plt.
title
(
'Simulated Nonlinear Data'
)
plt.
legend
(
)
plt.
show
(
)
Run this code, and you will see that the data points roughly form a "U" shape (parabolic) distribution; fitting them with a straight line is clearly inappropriate.
2.2 Core Steps: Feature Transformation and Model Training
The key step is to use PolynomialFeatures to generate higher-degree features.
Example
1. Create polynomial features
The parameter degree determines the degree of the polynomial; here we try degree 2
poly_features
=
PolynomialFeatures
(
degree
=
2
,
include_bias
=
False
)
Transform the original feature X into a new feature matrix X_poly containing X and X^2
X_poly
=
poly_features.
fit_transform
(
X
)
(
f
"Shape of original X: {X.shape}"
)
(
f
"Shape of transformed X_poly: {X_poly.shape}"
)
(
f
"First 5 rows of X_poly:\n{X_poly[:5]}"
)
The output shows that X_poly has two columns: the first is X, and the second is X^2
2. Train a linear regression model on the transformed features
lin_reg
=
LinearRegression
(
)
lin_reg.
fit
(
X_poly
,
y
)
Use X_poly instead of the original X
3. View the learned model parameters (weights and bias)
(
f
"\nModel parameters (weights w1, w2): {lin_reg.coef_.ravel()}"
)
(
f
"Model bias (intercept b): {lin_reg.intercept_}"
)
The output should be close to the parameters [1, 0.5] and 2 used when we generated the data
2.3 Visualizing the Fit
Let's see what the trained "curve" model looks like.
Example
To draw a smooth curve, we need to generate a set of evenly distributed points
X_new
=
np.
linspace
(
3
,
3
,
100
)
.
reshape
(
100
,
1
)
Apply the same polynomial feature transformation to these new points
X_new_poly
=
poly_features.
transform
(
X_new
)
Make predictions with the model
y_new
=
lin_reg.
predict
(
X_new_poly
)
Start plotting
plt.
scatter
(
X
,
y
,
s
=
10
,
alpha
=
0.7
,
label
=
'Training data'
)
plt.
plot
(
X_new
,
y_new
,
'r-'
,
linewidth
=
2
,
label
=
'Polynomial Regression Fit (degree=2)'
)
plt.
xlabel
(
'X'
)
plt.
ylabel
(
'y'
)
plt.
title
(
'Quadratic Polynomial Regression Fit'
)
plt.
legend
(
)
plt.
show
(
)
You should see a beautiful red curve that nicely captures the parabolic trend of the data.
III. Important Topic: How to Choose the Right Degree?
Choosing the degree is a trade-off process. We can gain an intuitive feel by visualizing the fit for different degrees.
Example
Try different degrees: 1 (linear), 2, 15 (too high)
degrees
=
[
1
,
2
,
15
]
plt.
figure
(
figsize
=
(
15
,
4
)
)
for
i
,
degree
in
enumerate
(
degrees
)
:
Create subplots
ax
=
plt.
subplot
(
1
,
len
(
degrees
)
,
i +
1
)
Generate polynomial features and train the model
poly_features
=
PolynomialFeatures
(
degree
=
degree
,
include_bias
=
False
)
X_poly
=
poly_features.
fit_transform
(
X
)
lin_reg
=
LinearRegression
(
)
lin_reg.
fit
(
X_poly
,
y
)
Predict and plot
y_new
=
lin_reg.
predict
(
poly_features.
transform
(
X_new
)
)
ax.
scatter
(
X
,
y
,
s
=
10
,
alpha
=
0.7
)
ax.
plot
(
X_new
,
y_new
,
'r-'
,
linewidth
=
2
)
ax.
set_title
(
f
'Degree = {degree}'
)
ax.
set_xlabel
(
'X'
)
ax.
set_ylabel
(
'y'
)
Compute and display the R² score (closer to 1 is better)
y_pred
=
lin_reg.
predict
(
X_poly
)
r2
=
r2_score
(
y
,
y_pred
)
ax.
text
(
0.05
,
0.95
,
f
'$R^2$ = {r2:.3f}'
,
transform
=
ax.
transAxes
,
verticalalignment
=
'top'
,
bbox
=
dict
(
boxstyle
=
'round'
,
facecolor
=
'wheat'
,
alpha
=
0.5
)
)
plt.
tight_layout
(
)
plt.
show
(
)
Observation and explanation:
- Degree=1 (linear): a straight line,
R²with a low score, clearlyUnderfitting, unable to express the curvature of the data. - Degree=2 (quadratic): a smooth curve,
R²with a high score and a very good fit. - Degree=15 (15th degree): The curve oscillates violently, passing through many data points, but predicts weird trends between the data points. On the training data it
R²may be close to 1, but predictions on new data will be very poor — this is a typical case ofOverfitting。
3.1 A More Scientific Approach: Cross-Validation
In practice, we useCross-validationto evaluate the performance of models with different degrees on unseen data, and select the model with the best performance on the validation set.scikit-learn 's cross_val_score can easily accomplish this.
Example
from
sklearn.
model_selection
import
cross_val_score
Test a range of degrees
degrees_to_try
=
range
(
1
,
11
)
cv_scores
=
[
]
for
degree
in
degrees_to_try:
poly_features
=
PolynomialFeatures
(
degree
=
degree
,
include_bias
=
False
)
X_poly
=
poly_features.
fit_transform
(
X
)
lin_reg
=
LinearRegression
(
)
Use 5-fold cross-validation with negative mean squared error as the score (sklearn convention: higher scores are better, so negative MSE is used)
scores
=
cross_val_score
(
lin_reg
,
X_poly
,
y
,
cv
=
5
,
scoring
=
'neg_mean_squared_error'
)
cv_scores.
append
(
-scores.
mean
(
)
)
Take the average and convert back to positive MSE
Find the degree that minimizes the cross-validation error
best_degree
=
degrees_to_try
[
np.
argmin
(
cv_scores
)
]
(
f
"According to cross-validation, the best degree is: {best_degree}"
)
Visualize how the cross-validation error changes with the degree
plt.
plot
(
degrees_to_try
,
cv_scores
,
'bo-'
)
plt.
xlabel
(
'Polynomial Degree'
)
plt.
ylabel
(
'5-Fold Cross-Validation Average MSE'
)
plt.
title
(
'Cross-Validation for Selecting the Best Degree'
)
plt.
axvline
(
x
=
best_degree
,
color
=
'r'
,
linestyle
=
'--'
,
label
=
f
'Best degree={best_degree}'
)
plt.
legend
(
)
plt.
grid
(
True
)
plt.
show
(
)
IV. Practice Exercises
Now it's time to consolidate what you've learned hands-on.
Exercise 1: Diagnose and Fix Run the code below. It attempts to fit the data with polynomial regression but does not work well. Analyze what might be wrong and modify the code to fit correctly.
Example
Code with problems
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
preprocessing
import
PolynomialFeatures
from
sklearn.
linear_model
import
LinearRegression
X
=
np.
array
(
[
1
,
2
,
3
,
4
,
5
]
)
.
reshape
(
1
,
1
)
y
=
np.
array
(
[
2
,
4
,
9
,
16
,
25
]
)
Roughly y = x^2
Try fitting with a degree-1 polynomial (linear)
poly
=
PolynomialFeatures
(
degree
=
1
)
X_poly
=
poly.
fit_transform
(
X
)
model
=
LinearRegression
(
)
.
fit
(
X_poly
,
y
)
X_plot
=
np.
linspace
(
1
,
5
,
100
)
.
reshape
(
1
,
1
)
X_plot_poly
=
poly.
transform
(
X_plot
)
y_plot
=
model.
predict
(
X_plot_poly
)
plt.
scatter
(
X
,
y
,
label
=
'Data'
)
plt.
plot
(
X_plot
,
y_plot
,
'r-'
,
label
=
'Fit'
)
plt.
legend
(
)
plt.
show
(
)
Exercise 2: Explore a Real Dataset Use scikit-learn built-in 波士顿房价数据集 or 糖尿病数据集, select a feature that has a nonlinear relationship with the target value, and apply polynomial regression.
- Plot a scatter chart of the original data.
- Try different degrees (2, 3, 4) and visualize the fitted curves.
- Use cross-validation to find the polynomial degree that best predicts this feature.
Exercise 3: Challenge — Multivariate Polynomial Regression Our example above has only one feature x. Polynomial regression applies equally to multiple features. For example, with two features x1 and x2 , thedegree=2 the polynomial features would include:x1, x2, x1², x1*x2, x2². Try creating a simulated dataset with two features (x1, x2) (for example,y = x1 + x2² + 噪声), and use PolynomialFeatures(degree=2) to fit it. Observe the shape of the generated feature matrix and understand its meaning.