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()






猜你喜欢

转载自blog.csdn.net/qq_23859701/article/details/79016598