机器学习--多项式回归08

多项式回归
在这里插入图片描述
sklearn实现多项式回归

导入包

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

载入数据

data = pd.read_csv("job.csv", delimiter=",")
data

Position Level Salary
0 Business Analyst 1 45000
1 Junior Consultant 2 50000
2 Senior Consultant 3 60000
3 Manager 4 80000
4 Country Manager 5 110000
5 Region Manager 6 150000
6 Partner 7 200000
7 Senior Partner 8 300000
8 C-level 9 500000
9 CEO 10 1000000

数据切分

x_data = data.iloc[0:,1]
y_data = data.iloc[0:,2]
plt.scatter(x_data,y_data)
plt.show()

在这里插入图片描述

x_data

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Name: Level, dtype: int64

因为sklearn输入的数据都需要是二维的

x_data = x_data[:,np.newaxis]
y_data = y_data[:,np.newaxis]
x_data

array([[ 1.],
[ 2.],
[ 3.],
[ 4.],
[ 5.],
[ 6.],
[ 7.],
[ 8.],
[ 9.],
[10.]])

创建并拟合模型
线性模型

estimator = LinearRegression()
estimator.fit(x_data, y_data)

plt.plot(x_data, y_data, 'b.')
plt.plot(x_data, estimator .predict(x_data), 'r')
plt.show()

在这里插入图片描述

定义多项式回归,degree的值可以调节多项式的特征

model  = PolynomialFeatures(degree=5) 
# 特征处理
transfer= model.fit_transform(x_data)
# 定义回归模型
eatimator= LinearRegression()
# 训练模型
eatimator.fit(transfer, y_data)
transfer

array([[1.0000e+00, 1.0000e+00, 1.0000e+00, 1.0000e+00, 1.0000e+00,
1.0000e+00],
[1.0000e+00, 2.0000e+00, 4.0000e+00, 8.0000e+00, 1.6000e+01,
3.2000e+01],
[1.0000e+00, 3.0000e+00, 9.0000e+00, 2.7000e+01, 8.1000e+01,
2.4300e+02],
[1.0000e+00, 4.0000e+00, 1.6000e+01, 6.4000e+01, 2.5600e+02,
1.0240e+03],
[1.0000e+00, 5.0000e+00, 2.5000e+01, 1.2500e+02, 6.2500e+02,
3.1250e+03],
[1.0000e+00, 6.0000e+00, 3.6000e+01, 2.1600e+02, 1.2960e+03,
7.7760e+03],
[1.0000e+00, 7.0000e+00, 4.9000e+01, 3.4300e+02, 2.4010e+03,
1.6807e+04],
[1.0000e+00, 8.0000e+00, 6.4000e+01, 5.1200e+02, 4.0960e+03,
3.2768e+04],
[1.0000e+00, 9.0000e+00, 8.1000e+01, 7.2900e+02, 6.5610e+03,
5.9049e+04],
[1.0000e+00, 1.0000e+01, 1.0000e+02, 1.0000e+03, 1.0000e+04,
1.0000e+05]])

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')
plt.ylabel('Salary')
plt.show()

在这里插入图片描述

预测

用该模型进行预测

plt.plot(x_data, y_data, 'b.')
x_test = np.linspace(1,10,100)
x_test = x_test[:,np.newaxis]
plt.plot(x_test, lin_reg.predict(poly_reg.fit_transform(x_test)), c='r')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值