一元线性回归即只包括一个自变量和一个因变量,简单来说这个模型就是可以近似用一条直线来表示。
我们随便取些数值来表示吧!

以上数值都是随便输的。以x为自变量,y为因变量来表示吧。
#首先导入需要的包,numpy和matplotlib
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline#在用jupyter notebook时没有这个代码可以会报错。看运气吧 我在学校机房操作时出现 figute size 640x480 with 1 axex的报错,所以在这里加了这个代码
from sklearn import linear_model
#获取数据
def getDate(filename):
date=pd.read_excel(filename,encoding='utf-8')
return date['x'],date['y']
x,y=getDate(r'C:\Users\Administrator\Desktop\01.xlsx')
plt.scatter(x,y)
plt.show()
def show_linear_line(X_parameters,Y_parameters):
regr=linear_model.LinearRegression()#引入线性模型
regr.fit(X_parameters,Y_parameters)#拟合数据
plt.scatter(X_parameters,Y_parameters,color='blue',linewidth=5)
plt.plot(X_parameters,regr.predict(X_parameters),color='red',linewidth=2)
plt.xticks(())
plt.yticks(())
plt.show()
#调用show_linear_line
show_linear_line(x.values.reshape(-1, 1),y.values.reshape(-1, 1))
目前只是了解一元线性,多元线性还不熟悉。希望下次可以更新多元线性回归的一些例子!
代码运行后的结果是