最小方形适合2D线

时间:2017-08-20 22:53:19

标签: python least-squares

我意识到我可以使用numpy来找到这样的行:

import numpy as np
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,6,7])
b = np.array([5,4,3,2,-2,-1])
k,m = np.polyfit(a,b,1)
plt.scatter(a,b)
plt.plot([0,10],[m,10*k+m])
plt.show()

enter image description here

但是我想使用原始的python代码。我的数学太生疏了,但如果可以用几行代码完成,我真的很感激帮助!

1 个答案:

答案 0 :(得分:1)

如果您正在寻找基于最小化二次误差的simple linear regression,那么纯Python实现非常简单(在上面的链接上检查α和β的等式):

def linear_fit(x, y):
    """For set of points `(xi, yi)`, return linear polynomial `f(x) = k*x + m` that
    minimizes the sum of quadratic errors.
    """
    meanx = sum(x) / len(x)
    meany = sum(y) / len(y)
    k = sum((xi-meanx)*(yi-meany) for xi,yi in zip(x,y)) / sum((xi-meanx)**2 for xi in x)
    m = meany - k*meanx
    return k, m

您的样本输入:

>>> x = [1,2,3,4,6,7]
>>> y = [5,4,3,2,-2,-1]
>>> linear_fit(x, y)
(-1.1614906832298135, 6.285714285714285)