一、线性回归
import matplotlib.pyplot as plt
import seaborn as sns
sns.set() #设置图形样式
import numpy as np
#简单线性回归
'''
创造数据
'''
rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = 2 * x - 5 + rng.rand(50)
from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=True)
model.fit(x[:, np.newaxis], y)
xfit = np.linspace(0, 10, 1000)
yfit = model.predict(xfit[:, np.newaxis])
plt.scatter(x, y, s = 10, color = 'black')
plt.plot(xfit, yfit, color = 'red')
plt.show()
print("Model slope:", model.coef_[0]) #斜率
print("Model intercept:", model.intercept_) #截距
结果1:
结果2:
Model slope: 2.0082302432277497
Model intercept: -4.533652972099125
二、多项式回归
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
def PolynomialRegression(degree = 2, **kwargs):
return make_pipeline(PolynomialFeatures(degree),
LinearRegression(**kwargs))
#创造些数据
import numpy as np
'''
定义函数,创建数据
'''
def make_data(N, err = 1.0, rseed = 1):
# 随机抽样数据
rng = np.random.RandomState(rseed)
X = rng.rand(N,