用python实现简单线性回归

import numpy as npy
def fitSLR(x,y):
    fenzi = 0
    fenmu = 0
    num=len(x)
    for i in range(num):
        fenzi=fenzi+(x[i]-npy.mean(x))*(y[i]-npy.mean(y))
        fenmu=fenmu+(x[i]-npy.mean(x))**2
    b1=fenzi/float(fenmu)
    b0=npy.mean(y)-b1*npy.mean(x)
    print(b1,b0)
    return b0,b1
def predict(text_x,b1,b0):
    return b1*text_x+b0
x=[1,3,2,1,3]
y=[14,24,18,17,27]
b0,b1=fitSLR(x,y)
rst=predict(6,b1,b0)
print(rst)

你可能感兴趣的:(python)