To solve the problem, we'll analyze how polynomial regression models of varying degrees fit the given data, especially focusing on overfitting in high-degree polynomials and how regularization can mitigate it.
Step 1: Generate the Data
First, we'll generate the dataset as per the provided code:
import numpy as np
import matplotlib.pyplot as plt
def true_fun(X):
return np.cos(1.5 * np.pi * X)
np.random.seed(0)
n_samples = 30
X = np.sort(np.random.rand(n_samples))
y = true_fun(X) + np.random.randn(n_samples) * 0.1
Step 2: Fit Polynomial Regression Models of Degrees 1, 4, and 15
We'll use PolynomialFeatures to generate polynomial features and LinearRegression to fit the models.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
degrees = [1, 4, 15]
plt.figure(figsize=(18, 5))
X_test = np.linspace(0, 1, 100)
for i, degree in enumerate(degrees):
# Create polynomial features
polynomial_features = PolynomialFeatures(degree=degree, include_bias=False)
# Create a pipeline model
model = make_pipeline(polynomial_features, LinearRegression())
# Fit the model
model.fit(X[:, np.newaxis], y)
# Predict
y_plot = model.predict(X_test[:, np.newaxis])
# Plot
plt.subplot(1, 3, i + 1)
plt.scatter(X, y, label="Training Points")
plt.plot(X_test, true_fun(X_test), label="True Function")
plt.plot(X_test, y_plot, label="Model Prediction")
plt.title(f"Degree {degree}")
plt.legend()
Observation:
- Degree 1: The model underfits; it cannot capture the curvature of the true function.
- Degree 4: The model fits the data reasonably well, capturing the main patterns.
- Degree 15: The model overfits; it captures the noise in the training data and deviates significantly from the true function in regions without data.
Step 3: Train Degree 15 Model with Regularization
We'll use Ridge and Lasso regression for regularization, trying different values of the regularization parameter alpha.
Ridge Regression Regularization
from sklearn.linear_model import Ridge
alphas = [1e-7, 1e-3, 1e-1, 1]
plt.figure(figsize=(14, 10))
for i, alpha in enumerate(alphas):
model = make_pipeline(PolynomialFeatures(degree=15, include_bias=False),
Ridge(alpha=alpha))
model.fit(X[:, np.newaxis], y)
y_plot = model.predict(X_test[:, np.newaxis])
# Plot
plt.subplot(2, 2, i + 1)
plt.scatter(X, y, label="Training Points")
plt.plot(X_test, true_fun(X_test), label="True Function")
plt.plot(X_test, y_plot, label=f"Ridge Prediction (alpha={alpha})")
plt.title(f"Degree 15 Ridge Regression (alpha={alpha})")
plt.legend()
Lasso Regression Regularization
from sklearn.linear_model import Lasso
alphas = [1e-7, 1e-3, 1e-1, 1]
plt.figure(figsize=(14, 10))
for i, alpha in enumerate(alphas):
model = make_pipeline(PolynomialFeatures(degree=15, include_bias=False),
Lasso(alpha=alpha, max_iter=10000))
model.fit(X[:, np.newaxis], y)
y_plot = model.predict(X_test[:, np.newaxis])
# Plot
plt.subplot(2, 2, i + 1)
plt.scatter(X, y, label="Training Points")
plt.plot(X_test, true_fun(X_test), label="True Function")
plt.plot(X_test, y_plot, label=f"Lasso Prediction (alpha={alpha})")
plt.title(f"Degree 15 Lasso Regression (alpha={alpha})")
plt.legend()
Step 4: Conclusions
Without Regularization:
- The degree 15 polynomial model overfits the training data.
- It captures the noise rather than the underlying true function.
- The model's predictions are wildly erratic, especially in regions with sparse data.
With Regularization:
-
Ridge Regression:
- As
alpha increases, the model becomes smoother.
- Small
alpha (e.g., 1e-7) results in a model similar to the unregularized one.
- Larger
alpha values (e.g., 1e-1, 1) reduce overfitting.
- The model starts to underfit if
alpha is too large.
-
Lasso Regression:
- Lasso can reduce coefficients to zero, effectively performing feature selection.
- With increasing
alpha, the model simplifies and may underfit.
- High
alpha values can lead to overly simplistic models.
Overall:
- Regularization helps prevent overfitting in high-degree polynomial models.
- Choosing the right
alpha is crucial; too small may not prevent overfitting, too large may cause underfitting.
- Ridge tends to produce smoother models, while Lasso can eliminate features.
- Regularization adds bias to reduce variance, aiming for a better generalization.
Visualizations
Degree 1, 4, and 15 Models Without Regularization:
[image: Degree 1, 4, and 15 Models] open
Degree 15 Models with Ridge Regularization:
[image: Ridge Regularization] open
Degree 15 Models with Lasso Regularization:
[image: Lasso Regularization] open
Note: Replace the image links with the actual plots generated from your code.
By analyzing these models, we see that regularization is essential when dealing with high-degree polynomials to prevent overfitting and to produce models that generalize better to unseen data.