使用 matplotlib / numpy 进行线性回归

新手上路,请多包涵

我试图在我生成的散点图上生成线性回归,但是我的数据是列表格式,我可以找到的所有使用 polyfit 的示例都需要使用 arangearange 虽然不接受列表。我到处搜索如何将列表转换为数组,但似乎没有什么清楚的。我错过了什么吗?

接下来,如何最好地使用我的整数列表作为 polyfit 的输入?

这是我正在关注的 polyfit 示例:

 import numpy as np
import matplotlib.pyplot as plt

x = np.arange(data)
y = np.arange(data)

m, b = np.polyfit(x, y, 1)

plt.plot(x, y, 'yo', x, m*x+b, '--k')
plt.show()

原文由 user771224 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 616
2 个回答

arange 生成 列表(嗯,numpy 数组);输入 help(np.arange) 了解详情。您不需要在现有列表上调用它。

 >>> x = [1,2,3,4]
>>> y = [3,5,7,9]
>>>
>>> m,b = np.polyfit(x, y, 1)
>>> m
2.0000000000000009
>>> b
0.99999999999999833

我应该补充一点,我倾向于在这里使用 poly1d 而不是写出 “m*x+b” 和高阶等价物,所以我的代码版本看起来像这样:

 import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [3,5,7,10] # 10, not 9, so the fit isn't perfect

coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef)
# poly1d_fn is now a function which takes in x and returns an estimate for y

plt.plot(x,y, 'yo', x, poly1d_fn(x), '--k') #'--k'=black dashed line, 'yo' = yellow circle marker

plt.xlim(0, 5)
plt.ylim(0, 12)

在此处输入图像描述

原文由 DSM 发布,翻译遵循 CC BY-SA 4.0 许可协议

这段代码:

 from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

给出一个包含以下内容的列表:

坡度:浮动

回归线的斜率

拦截:浮动

回归线的截距

右值:浮点数

相关系数

p值:浮动

原假设为斜率为零的假设检验的双侧 p 值

标准错误:浮动

估计的标准误差

资源

原文由 George Pamfilis 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题