天天看点

一元线性回归2

通过Python的Scikit-Learn库可以轻松搭建一元线性回归模型。

#1.绘制散点图:

import matplotlib.pyplot as plt
x=[[1],[2],[4],[5]]
y=[2,4,6,8]
plt.scatter(x,y)
plt.show()
           
一元线性回归2

#2.引入Scikit-Learn库搭建模型

from sklearn.linear_model import LinearRegression
regr=LinearRegression()
regr.fit(x,y)

           

#3.模型预测

#模型预测,假设自变量为1.5

y_pre=regr.predict([[1.5]])

y_pre
Out[69]: array([2.9])

#同时预测多个变量

y_pre2=regr.predict([[1.5],[2.5],[4.5]])

y_pre2
Out[72]: array([2.9, 4.3, 7.1])
           

#4.模型可视化

还可以将搭建好的模型以可视化的形式展示出来,代码如下。

plt.scatter(x,y)
plt.plot(x,regr.predict(x))
plt.show()
           

绘制效果如下图所示,此时的一元线性回归模型就是

继续阅读