绘制回归线

IMC*_*ins 1 python numpy matplotlib linear-regression

我在绘制一些回归线时遇到了一些问题。我的问题可能是我没有正确理解这些函数所做的数学运算,所以我在这里要求确定。

from matplotlib import pyplot as plt
import numpy as np

def estimate_coef(x, y):
    # number of observations/points
    n = np.size(x)

    # mean of x and y vector
    m_x, m_y = np.mean(x), np.mean(y)

    # calculating cross-deviation and deviation about x
    SS_xy = np.sum(y*x - n*m_y*m_x)
    SS_xx = np.sum(x*x - n*m_x*m_x)

    # calculating regression coefficients
    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1 * m_x

    return (b_0, b_1)

def plot_regression_line(xs, ys):
    # dev stands for deviation
    dev = estimate_coef(xs, ys)

    y_pred = []
    for x in xs:
        y_pred.append(dev[0] + dev[1] * x)

    # plotting the regression line
    plt.plot(xs, y_pred, color = "g")

def main():
    # Defining points.
    xarr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    yarr = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]

    # Setting points as numpy arrays.
    # It is more convenient this way for further process.
    x = np.array(xarr)
    y = np.array(yarr)

    # Plotting points.
    plt.scatter(x, y)

    plot_regression_line(x, y)
    plt.show()

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

上面的代码显示了一个很好的绘制图形,例如:

好剧情

但是...如果我反y转轴中的点,只是为了测试我的功能,例如在main()我会做的功能中:

yarr = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]
yarr.reverse()
Run Code Online (Sandbox Code Playgroud)

我得到以下...

错误的情节


显然希望我的plot_regression_line函数绘制我正在等待考虑我输入的数据的线。我不明白为什么这行不通。

我相信问题来自estimate_coef函数,尤其是函数的b_0计算方式,但我不知道我应该应用哪些更改以使我的函数按预期工作。

Mr.*_*. T 5

我不知道,你从哪里得到回归公式的。维基百科有一个不同的。如果你把它转录成你的脚本约定,它应该是

SS_xy = np.sum((x - m_x) * (y - m_y))
SS_xx = np.sum(x*x - m_x*m_x)
Run Code Online (Sandbox Code Playgroud)

这为您提供了两种情况下正确的回归线。并且您无需再进行计算n,因为在计算平均值时已将其考虑在内。