以下包含python实现和sklearn实现方法:
#---------------Simple Linear Regression------------------------------
import numpy as np
def predict(x,y):
n = len(x)
b1 =0
b2 =0
for i in range(n):
b1 = (x[i]-np.mean(x))*(y[i]-np.mean(y))+b1 #np.mean()返回矩阵均值
b2 = (x[i]-np.mean(x))**2+b2
b1 = b1/b2
b0 = np.mean(y)-b1*np.mean(x)
print ('y =',b1,'x','+',b0)
x = [1,3,2,1,3]
y = [14,24,18,17,27]
predict(x,y)
# x = np.array([[1,2],
# [3,3],
# [1,2]])
# print (np.mean(x,axis=0),
# np.cumsum(x),#返回list包含所有元素的累计和
# np.cumprod(x)#返回list包含所有元素的累积)
#---------------也可用sklearn实现------------------
from sklearn import linear_model
#LinearRegression也可进行单一变量线性回归模型的建立
regr = linear_model.LinearRegression()
#传入参数需要用到list[list]形式
x = [[1],[3],[2],[1],[3]]
y = [14,24,18,17,27]
regr.fit(x,y)
print (regr.coef_,regr.intercept_)
#----------------------numpy可以直接实现-------------------------
import numpy as np
x = [1,3,2,1,3]
y = [14,24,18,17,27]
coef = np.polyfit(x,y,1) #返回系数
print (coef)