matplotlib/numpy线性回归

2024-04-19 08:08:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

下面是我下面的polyfit示例:

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() 

Tags: 数据fromimport示例列表dataplot格式
3条回答

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')
plt.xlim(0, 5)
plt.ylim(0, 12)

enter image description here

此代码:

from scipy.stats import linregress

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

列出一个列表,其中包含以下内容:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate

Source

import numpy as np
import matplotlib.pyplot as plt 
from scipy import stats

x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
mn=np.min(x)
mx=np.max(x)
x1=np.linspace(mn,mx,500)
y1=gradient*x1+intercept
plt.plot(x,y,'ob')
plt.plot(x1,y1,'-r')
plt.show()

使用这个。。

相关问题 更多 >