问题描述
我正在尝试在已生成的散点图上生成线性回归,但是我的数据是列表格式,我可以找到的所有使用polyfit
的示例都需要使用arange
. arange
但是不接受列表.我搜索过很多关于如何将列表转换为数组的东西,似乎还不清楚.我想念什么吗?
I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using polyfit
require using arange
. arange
doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems clear. Am I missing something?
接下来,我怎样才能最好地使用整数列表作为polyfit
的输入?
Following on, how best can I use my list of integers as inputs to the polyfit
?
这是我关注的polyfit示例:
here is the polyfit example I am following:
from pylab import *
x = arange(data)
y = arange(data)
m,b = polyfit(x, y, 1)
plot(x, y, 'yo', x, m*x+b, '--k')
show()
推荐答案
arange
生成列表(嗯,numpy数组);键入help(np.arange)
以获得详细信息.您无需在现有列表上调用它.
arange
generates lists (well, numpy arrays); type help(np.arange)
for the details. You don't need to call it on existing lists.
>>> 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"和更高阶的等价物,因此我的代码版本看起来像这样:
I should add that I tend to use poly1d
here rather than write out "m*x+b" and the higher-order equivalents, so my version of your code would look something like this:
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')
plt.xlim(0, 5)
plt.ylim(0, 12)
这篇关于使用matplotlib/numpy进行线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!