多项式回归示例(sklearn实现)

39 篇文章 2 订阅
13 篇文章 0 订阅

多项式回归示例(sklearn实现)

1. 导包

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

2. 原始数据生成与展示

x_data = np.array([1, 2, 3, 4, 5, 6 ,7, 8, 9 ,10])
y_data = np.array([45, 55, 60, 85, 115, 140, 222, 350, 600, 1000])
plt.scatter(x_data, y_data)
plt.show()

原始数据图

3. 数据预处理

x_data = x_data[:, np.newaxis]
y_data = y_data[:, np.newaxis]
# 多项式特征转换
poly_reg = PolynomialFeatures(degree=3)
x_data_poly = poly_reg.fit_transform(x_data)

4. 建立模型,开始训练

model = LinearRegression()
model.fit(x_data_poly, y_data)

5. 预测结果与展示

# 生成待预测的数据
x_test = np.linspace(1, 10, 50)[:, np.newaxis]
x_test_poly = poly_reg.fit_transform(x_test)
# 开始预测
predict_result = model.predict(x_test_poly)
print(predict_result)

# 作图
# 原始数据
plt.plot(x_data, y_data, "b.")
# 预测数据
plt.plot(x_test, predict_result, c="r")
plt.show()

预测结果图

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值