天天看點

simple linear Regression

理論看程式就好了:

import numpy as np
import matplotlib.pyplot as plt
def train_number(x,y):
    n=np.shape(x)[0]
    number1=0
    number2=0
    for i in range(n):#簡單的線性回歸的方程的公式
        number1+=(x[i]-np.mean(x))*(y[i]-np.mean(y))
        number2+=(x[i]-np.mean(x))**2
    b1=number1/number2#求出的回歸線的斜率
    b0=np.mean(y)-b1*np.mean(x)#求出回歸線的截距
    return b0,b1
def plot_show(x,y):#畫出回歸線和點
    plt.plot(x,y,color='red')
    plt.show()

def predict(x,bo,b1):#預測點 可以算一下誤差
    n=np.shape(x)[0]
    y=[]
    for i in range(n):
        y.append(float(bo+b1*x[i]))
    return y
def main():
    x_train=[1.32,2,3,4]
    y_train=[3,4,5,6]
    x_test=[3,4,5]
    b0,b1=train_number(x_train,y_train)
    y_test=predict(x_test,b0,b1)
    plt.plot([1.32,2,3,4],[3,4,5,6],color='red',marker='.')
    plt.show()
    print(x_test,y_test)
if __name__=='__main__':
    main()





      

繼續閱讀