回归分析系列14— 多项式回归

17 多项式回归

17.1 简介

多项式回归是线性回归的一种扩展,它允许回归模型包括输入变量的高次项。这种方法特别适合处理非线性关系的数据。

17.2 多项式回归模型

在多项式回归中,模型形式如下:

eq?y%20%3D%20%5Cbeta_0%20+%20%5Cbeta_1%20x%20+%20%5Cbeta_2%20x%5E2%20+%20%5Cdots%20+%20%5Cbeta_p%20x%5Ep%20+%20%5Cepsilon

其中,p 是多项式的阶数,β0,β1,…,βp是待估计的系数。通过增加高次项,模型能够捕捉到输入变量与输出变量之间的非线性关系。

在Python中,我们可以使用scikit-learn中的PolynomialFeaturesLinearRegression类来实现多项式回归。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

# 生成模拟数据
np.random.seed(42)
X = np.sort(np.random.rand(100, 1) * 10, axis=0)
y = 2 - 3 * X + X**2 + np.random.randn(100, 1) * 2

# 构建多项式回归模型
degree = 2  # 二次多项式
polyreg = make_pipeline(PolynomialFeatures(degree), LinearRegression())
polyreg.fit(X, y)

# 预测
X_fit = np.linspace(0, 10, 100).reshape(-1, 1)
y_pred = polyreg.predict(X_fit)

# 绘图
plt.scatter(X, y, color='blue')
plt.plot(X_fit, y_pred, color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title(f'Polynomial Regression (degree={degree})')
plt.show()

17.3 选择多项式的阶数

在多项式回归中,选择合适的多项式阶数非常重要。阶数过低可能导致欠拟合,而阶数过高则可能导致过拟合。通过交叉验证,可以帮助我们选择最合适的阶数。

from sklearn.model_selection import cross_val_score

# 定义不同阶数的多项式
degrees = [1, 2, 3, 4, 5]

# 评估不同阶数下的模型性能
for degree in degrees:
    polyreg = make_pipeline(PolynomialFeatures(degree), LinearRegression())
    scores = cross_val_score(polyreg, X, y, scoring='neg_mean_squared_error', cv=5)
    print(f"Degree {degree}: Mean Squared Error: {-scores.mean():.2f}")

17.4 高维数据中的多项式回归

在处理高维数据时,多项式回归容易产生过拟合问题。为了缓解这一问题,可以结合正则化技术,如岭回归或套索回归。

from sklearn.linear_model import Ridge

# 构建正则化的多项式回归模型
degree = 3
polyreg_ridge = make_pipeline(PolynomialFeatures(degree), Ridge(alpha=1.0))
polyreg_ridge.fit(X, y)

# 预测
y_pred_ridge = polyreg_ridge.predict(X_fit)

# 绘图
plt.scatter(X, y, color='blue')
plt.plot(X_fit, y_pred_ridge, color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title(f'Ridge Polynomial Regression (degree={degree})')
plt.show()

17.5 多项式回归的应用

多项式回归适用于许多实际问题,特别是当数据中存在明显的非线性关系时。例如,在经济学中,多项式回归可以用于预测非线性趋势的经济指标;在医学研究中,它可以用于建模药物剂量与疗效之间的复杂关系。

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值