如何计算numpy的坡度

时间:2011-09-08 15:29:14

标签: python numpy

如果我有50个元素的数组,我如何计算3个周期斜率和5个周期斜率? 文档不会增加太多.....

>>> from scipy import stats
>>> import numpy as np
>>> x = np.random.random(10)
>>> y = np.random.random(10)
>>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

这会有用吗?

def slope(x, n): 
   if i<len(x)-n: 
        slope = stats.linregress(x[i:i+n],y[i:i+n])[0]
        return slope 

但是数组的长度是相同的

@joe :::

xx = [2.0 ,4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
x  = np.asarray(xx, np.float)
s  = np.diff(x[::3])/3

window  = [1, 0, 0, 0,  -1]
window2 = [1, 0,  -1]
slope   = np.convolve(x, window, mode='same') / (len(window) - 1)
slope2  = np.convolve(x, window2, mode='same') / (len(window2) - 1)

print x
print s

print slope
print slope2

结果.....

[  2.   4.   6.   8.  10.  12.  14.  16.  18.  20.  22.  24.  26.  28.  30.]
[ 2.  2.  2.  2.]
[ 1.5  2.   2.   2.   2.   2.   2.   2.   2.   2.   2.   2.   2.  -6.  -6.5]
[  2.   2.   2.   2.   2.   2.   2.   2.   2.   2.   2.   2.   2.   2. -14.]

斜率和斜率2是我之后的事情,除了-6,-6.5和-14不是我正在寻找的结果。

这有效.......

window    = [1, 0, 0, -1]
slope     = np.convolve(xx, window, mode='valid') / float(len(window) - 1)
padlength = len(window) -1
slope     = np.hstack([np.ones(padlength), slope])
print slope

2 个答案:

答案 0 :(得分:7)

我假设你的意思是计算每个第3和第5个元素的斜率,这样你就有了一系列(精确的,非最小二乘)斜率?

如果是这样,你只需按照以下方式做点什么:

third_period_slope = np.diff(y[::3]) / np.diff(x[::3])
fifth_period_slope = np.diff(y[::5]) / np.diff(x[::5])
但是,我可能完全误解了你的意思。在......之前,我从未领过“3期斜率”一词。

如果你想要更多的“移动窗口”计算(这样输入元素的数量与输出元素相同),只需将其建模为带有[-1, 0, 1]或{{1}窗口的卷积。 }。

E.g。

[-1, 0, 0, 0, 1]

答案 1 :(得分:3)

只需使用包含这些点的数据子集(期间 - 我假设您在这里谈论财务数据),您感兴趣的是:

for i in range(len(x)):
    if i<len(x)-3:
        slope, intercept, r_value, p_value, std_err = stats.linregress(x[i:i+3],y[i:i+3])
    if i<len(x)-5:
        slope, intercept, r_value, p_value, std_err = stats.linregress(x[i:i+5],y[i:i+5])

(这不是最有效的方法,顺便说一下,如果你想要的只是斜坡,但它很容易。)

相关问题