当前位置:网站首页>linear regression

linear regression

2022-07-07 05:47:00 Python code doctor

import numpy as np
from matplotlib import pyplot as plt

#  Define training data 
x = np.array([0.86, 0.96, 1.12, 1.35, 1.55, 1.63, 1.71, 1.78])
y = np.array([12, 15, 20, 35, 48, 51, 59, 66])

def fit(x,y):
    if len(x) != len(y):
        return
    numerator = 0.0
    denominator = 0.0
    x_mean = np.mean(x)
    y_mean = np.mean(y)

    for i in range(len(x)):
        numerator += (x[i]-x_mean)*(y[i]-y_mean)
        denominator += np.square(x[i]-x_mean)

    b0 = numerator / denominator
    b1 = y_mean-b0*x_mean

    return b0,b1

b0,b1 = fit(x,y)

def predit(x,b0,b1):
    return b0*x+b1


#  forecast 
x_test = np.array([0.75,1.08,1.26,1.51,1.6,1.67,1.85])
y_test = np.array([10,17,27,41,50,64,75])

y_predit = predit(x_test,b0,b1)


#  The plot 
plt.plot(x,y,'k.')
plt.plot(x_test,y_predit,'g-')
yr = predit(x,b0,b1)

for idx,x in enumerate(x):
    plt.plot([x,x],[y[idx],yr[idx]],'r-')

print(predit(1.75,b0,b1))

plt.show()
原网站

版权声明
本文为[Python code doctor]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070008240113.html