绘制回归线

时间:2018-01-31 10:07:20

标签: 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()

上面的代码显示了精心绘制的图形,例如:

Good plot

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

yarr = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]
yarr.reverse()

我得到以下内容......

Wrong plot

显然希望我的plot_regression_line函数能够绘制我正在等待考虑我输入数据的行。我无法理解为什么这不起作用。

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

1 个答案:

答案 0 :(得分:4)

我不知道,你从哪里得到回归公式。 Wikipedia has a different one.如果您将其转录为脚本约定,则应为

SS_xy = np.sum((x - m_x) * (y - m_y))
SS_xx = np.sum(x*x - m_x*m_x)

为您提供了两种情况的正确回归线。而且您不需要再计算n,因为在计算平均值时已经考虑了它。