机器学习基础——sklearn之多项回归

利用sklearn里的函数对多项式进行拟合
第一幅图是数据图
第二幅图是用一元线性回归拟合的图
第三幅图是用多项式回归拟合出来的

import numpy as np 
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression # 线性回归
from numpy import genfromtxt
from sklearn.preprocessing import PolynomialFeatures # 生成多项式

# 载入数据
data = genfromtxt(r"C:\\ML\\chapter-1\\job.csv",delimiter=",")
x_data = data[1:,1]
y_data = data[1:,2]
plt.scatter(x_data,y_data)
plt.show()

x_data = data[1:,1,np.newaxis] # 给数据加上维度
y_data = data[1:,2,np.newaxis]

# 创建并拟合模型  一元线性回归
model = LinearRegression()
model.fit(x_data,y_data)

# 画图
# 使用直线来拟合曲线,有对比性
plt.plot(x_data,y_data,'b.') # b代表blue .表示用.画出来
plt.plot(x_data,model.predict(x_data),'r') # 画线,r代表red
plt.show()

# 定义多项式回归,degree的值可以调节多项式的特征
poly_reg = PolynomialFeatures(degree=5)
# 特征处理
x_poly = poly_reg.fit_transform(x_data)
# 定义回归模型
lin_reg = LinearRegression()
# 训练模型
lin_reg.fit(x_poly,y_data)

# print(x_poly)
# 结果如下(当degree=1):
# [[ 1.  1.]
#  [ 1.  2.]
#  [ 1.  3.]
#  [ 1.  4.]
#  [ 1.  5.]
#  [ 1.  6.]
#  [ 1.  7.]
#  [ 1.  8.]
#  [ 1.  9.]
#  [ 1. 10.]]

# 结果如下(degree=2):
# [[  1.   1.   1.]
#  [  1.   2.   4.]
#  [  1.   3.   9.]
#  [  1.   4.  16.]
#  [  1.   5.  25.]
#  [  1.   6.  36.]
#  [  1.   7.  49.]
#  [  1.   8.  64.]
#  [  1.   9.  81.]
#  [  1.  10. 100.]]

# 画图
plt.plot(x_data,y_data,'b.')
plt.plot(x_data,lin_reg.predict(poly_reg.fit_transform(x_data)), c='r')
plt.title('Truth or Bluff (Polynomial Regression)') # 标题
plt.xlabel('Position level') # X坐标
plt.ylabel('Salary') # Y坐标
plt.show()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiao黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值