【发布时间】:2018-07-10 09:41:04
【问题描述】:
我在绘制一些回归线时遇到了一些问题。我的问题可能是我没有正确理解这些函数所做的数学运算,所以我在这里要求确定。
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()
上面的代码显示了一个很好的绘制图形,例如:
但是...如果我反转我的y 轴中的点,只是为了测试我的功能,例如在main() 功能中我会这样做:
yarr = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]
yarr.reverse()
我得到以下...
我显然希望我的plot_regression_line 函数为我绘制我正在等待考虑我输入的数据的线。而且我不明白为什么这不起作用。
我认为问题出在 estimate_coef 函数,尤其是 b_0 的计算方式,但我不知道应该应用哪些更改才能使函数按预期工作。
【问题讨论】:
-
感谢您的链接,但您可能知道,我对公式有疑问。
标签: python numpy matplotlib linear-regression