多项式回归
用适当幂次的多项式来近似反映因变量与自变量之间的关系。
- 什么是多项式模型?
它是由常数与自变量 经过有限次乘法与加法运算得到。
例如 就是多项式函数。
- 多项式回归的步骤:
- 生成多项式特征。
例如输入样本是维的如,则二阶多项式 的 特 征 集 为 。
在 sklearn 中 可 以 使 用 𝑷𝒐𝒍𝒚𝒏𝒐𝒎𝒊𝒂𝒍𝑭𝒆𝒂𝒕𝒖𝒓𝒆𝒔生成多项式特征。
- 利用得到的多项式特征,使用线性分类器处理。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# 披萨的直径和价格之间的关系
# 训练集数据
X_train = [[6], [8], [10], [14], [18]]
y_train = [[7], [9], [13], [17.5], [18]]
# 测试集数据
X_test = [[6], [8], [11], [16]]
y_test = [[8], [12], [15], [18]]
def R_2(y, y_hat):
'''
计算R方
:param y: 实际值
:param y_hat: 预测值
:return:
'''
# 均值
y_mean = np.mean(y)
# 残差平方和
res = np.sum(np.power((y - y_hat), 2))
# 样本总离差平方和
tss = np.sum(np.power((y - y_mean), 2))
# R方
r = 1 - res / tss
print(r)
def calc(degree):
'''
多项式拟合
:param degree:
:return:
'''
# 生成多项式特征X2
poly = PolynomialFeatures(degree)
poly.fit(X_train)
X2 = poly.transform(X_train)
# 拟合线性分类器
lr = LinearRegression()
lr.fit(X2, y_train)
prediction = lr.predict(poly.transform(X_test))
R_2(y_test, prediction)
测试结果:
degree | R2 |
---|---|
2 | 0.868 |
3 | 0.836 |
4 | 0.810 |
5 | 0.782 |
6 | 0.696 |
7 | 0.492 |
绘图看效果
def run(degree=3):
# 生成多次特征
poly = PolynomialFeatures(degree)
poly.fit(X)
X2 = poly.transform(X)
print('X2的大小', X2.shape)
# 继续使用线性模型
lr = LinearRegression()
lr.fit(X2, y)
fit = lr.predict(X2)
plt.figure(figsize=(10, 6))
plt.subplot(1, 2, 1)
plt.plot(X, fit, '.-', label='fit', color='blue')
plt.plot(X, y_train, 's-', label='actual', color='red')
plt.legend()
prediction = lr.predict(poly.transform(X_test))
plt.subplot(1, 2, 2)
plt.plot(X_test, prediction, '.-', label='prediction', color='blue')
plt.plot(X_test, y_test, 's-', label='actual', color='red')
plt.legend()
plt.show()
degree=1
degree=2
degree=3
degree=4
从4开始,出现过拟合
degree=7
在测试集的表现,已经出现严重偏差
避免过拟合的办法:
正则化、加噪、dropout等
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)