# 1.4 创建多项式回归器
import sys
import numpy as np
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
import sklearn.metrics as sm
import matplotlib.pyplot as plt
#0 导入数据
#x从-3 - 3均匀取值
x = np.random.uniform(-3, 3 ,size=100)
X = x.reshape(-1, 1)
#y是二次方程
y = 0.5 * x**2 + x +2 + np.random.normal(0, 1, size = 100)
plt.scatter(x, y)
# 1 线性拟合
from sklearn.linear_model import LinearRegression
#实例化线性模型
lr = LinearRegression()
lr.fit(X, y)
y_predict = lr.predict(X)
plt.figure()
plt.scatter(x, y )
plt.plot(x, y_predict)
plt.show()
#2 多项式拟合
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2)
#degree=2 生成2次特征,可以调整
poly.fit(X)
X2 = poly.transform(X)
print('X2的大小',X2.shape)
X2[0:5, :]
#继续使用线性模型
lr.fit(X2, y)
y_predict2 = lr.predict(X2)
plt.scatter(x, y)
plt.plot(np.sort(x), y_predict2[np.argsort(x)] )
plt.show()
结果:
将多项式次数变成 10
poly = PolynomialFeatures(degree=10)
拟合后的结果