天天看点

算法梳理进阶任务二:代码实现简单线性回归(单变量)

代码实现简单线性回归(单变量)

1、算术法:直接通过公式求解截距和斜率

import time

start = time.time()

import numpy as np

def fitslr(x,y):

n=len(x)

dinominator=0

numerator=0

for i in range (0,n):

numerator +=(x[i]-np.mean(x))(y[i]-np.mean(y))

dinominator+= (x[i]-np.mean(x))**2

print(“numerator”,numerator)

print(“dinominator”,dinominator)

b1=numerator/float(dinominator)

b0=np.mean(y)/float(np.mean(x))

print(b1)

print(b0)

return b0,b1

def predict(x,b0,b1):

return b0+xb1

x=[1,3,2,1,3]

y=[14,24,18,17,27]

b0,b1=fitslr(x,y)

x_text=6

y_text=predict(6,b0,b1)

print(“x_text”,y_text)

end = time.time()

print (end-start)

2:向量法:调用线性回归模型

import time

start = time.time()

from sklearn.linear_model import LinearRegression

import numpy as np

x = np.array([1,3,2,1,3])

y = np.array([14,24,18,17,27])

model = LinearRegression()

model.fit(x.reshape(len(x),1), y)

print(model.coef_)

print(model.intercept_)

end = time.time()

print (end-start)

3、性能比较

运算结果在本例中两个方法都一样;

继续阅读