1、一元线性和多元类似
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#元数据生成
x_data = np.random.randn(35)
y_data = np.random.randn(35)
plt.scatter(x_data,y_data)
plt.show()
x_data维度必须改下,不然会报错:Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
model = LinearRegression()
model.fit(x_data.reshape(-1, 1),y_data.reshape(-1, 1))
plt.plot(x_data,y_data,"b.")
plt.plot(x_data,model.predict(x_data.reshape(-1, 1)),"r")
plt.show()
2、多项式回归
from sklearn.preprocessing import PolynomialFeatures
#多项式回归数据特征处理
poly_reg = PolynomialFeatures(degree=3)
x_data1 = poly_reg.fit_transform(x_data.reshape(-1, 1))
#后续与一元类似,也要使用LinearRegression方法
lin_reg = LinearRegression()
lin_reg.fit(x_data1,y_data.reshape(-1, 1))
plt.plot(x_data,y_data,"b.")
plt.plot(x_data,lin_reg.predict(x_data1),c="r")
plt.show()