使用 matplotlib / numpy 进行线性回归

2023-12-11

我正在尝试在我生成的散点图上生成线性回归,但是我的数据采用列表格式,并且我可以找到使用的所有示例polyfit需要使用arange. arange但不接受列表。我已经搜索了很多有关如何将列表转换为数组的信息,但似乎没有什么明确的。我错过了什么吗?

接下来,我如何最好地使用我的整数列表作为输入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()

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)

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 matplotlib / numpy 进行线性回归 的相关文章