线性回归方程的参数求解过程

作者: Brave 分类: 学习 发布时间: 2018-10-07 23:10

一元线性回归方程y = a*X + b

#线性回归方程 y = a*X + b 求解a, b
import numpy as np 
import matplotlib.pyplot as plt
def calcAB(x,y):
    n = len(x)
    sumX, sumY, sumXY, sumXX = 0, 0, 0, 0
    for i in range(0, n):
        sumX += x[i]
        sumY += y[i]
        sumXX += x[i]*x[i]
        sumXY += x[i]*y[i]
    a = (n*sumXY - sumX*sumY)/(n*sumXX - sumX*sumX)
    b = (sumXX*sumY - sumX*sumXY)/(n*sumXX - sumX*sumX)
    return a,b
xi = [1,2,3,4,5,6,7,8,9,10]
yi = [10,11.5,12,13,14.5,15.5,16.8,17.3,18,18.7]
a,b = calcAB(xi, yi)
print("y = %10.5fx + %10.5f" %(a, b)

    y = 0.98606x + 9.30667

x = np.linspace(0, 10)
y = a * x + b
plt.plot(x, y)
plt.scatter(xi, yi)
plt.show()

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注