【Python】线性回归使用案例

这篇主要介绍Python的Sklearn实现线性回归进行拟合和预测的使用方法。
1.创建数据

import numpy as np
import matplotlib.pyplot as plt
rng = np.random.RandomState(20)
x = 10*rng.rand(50)
y = 2*x-1+rng.rand(50)
plt.scatter(x,y)

【Python】线性回归使用案例_第1张图片
2.构建线性回归模型

from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=True)
model
>LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)

3.模型拟合

x = x[:,np.newaxis]
model.fit(x,y)

4.查看模型参数
这个参数结果跟我们构建的数据集参数基本一样

model.coef_
>2.01889877
model.intercept_
>-0.5721372229186237

5.模型预测

xfit = np.linspace(-1,11)
xfit = xfit[:,np.newaxis]
yfit = model.predict(xfit)
plt.scatter(x,y)
plt.plot(xfit,yfit)

【Python】线性回归使用案例_第2张图片

我们下次再见,如果还有下次的话!!!

【新浪微博@516数据工作室】

长按下方二维码关注"516数据工作室"
【Python】线性回归使用案例_第3张图片

你可能感兴趣的:(Python)