Python 如何计算numpy中的坡度

Python 如何计算numpy中的坡度,python,numpy,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 = s

如果我有一个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 
结果

[  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

只需使用包含您感兴趣的点(时段——我假设您在这里谈论的是财务数据)的数据子集:

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])
范围内的i(len(x)):

如果我我假设你是指每3和5个元素计算的斜率,这样你就有了一系列(精确的,不是最小二乘)斜率

如果是这样的话,你只需要做以下几点:

third_period_slope = np.diff(y[::3]) / np.diff(x[::3])
fifth_period_slope = np.diff(y[::5]) / np.diff(x[::5])
不过,我可能完全误解了你的意思。我以前从来没有提到过“三周期斜率”这个词

如果您想要更多的“移动窗口”计算(以便输入元素的数量与输出元素的数量相同),只需将其建模为卷积,窗口为
[-1,0,1]
[-1,0,0,1]

例如


对整个50个观测值进行线性回归,可以得到斜率和截距。你能解释一下“N周期斜率”的确切含义吗?如果系列1,2……….50,我想要46,47,48,49,50的斜率和48,49,50的斜率。作为一个数组。所以所有元素都有相应的斜率,我认为有些元素像斜率(x,3)或斜率(x,5),其中返回值只是斜率向量或数组……这是基本思想,除了在你的定义中,什么是i?,在我的定义中是循环变量,所以每个i都给出了不同点集的斜率;而且,linregress将返回一个元组,而不是单个值,因此您可以将它们全部分配给变量,或者只分配元组并选择第一个条目,如r=stats.linregress(x[i:i+n],y[i:i+n]),然后slope=r[0],或者只返回slope=(stats.linregress(x[i:i+n],y[i:i+n])[0]你能用注释解决上面的问题吗?我不理解“卷积”,理解“con”的意思。读一读卷积,你会感谢你自己以后这么做的。它们相当普遍!:)卷积和@tom的答案之间的区别在于,卷积只使用第1点和第3点,然后只使用第2点和第4点等,而不是使用第1点、第2点和第3点,然后是第2点、第3点和第4点等。正如我前面所说的,我假设您不需要线性回归,而是需要精确拟合。(线性回归会慢几个数量级,但如果你没有大量的点,那就无关紧要了。)如果没有定义y,那么只有x的数组呢?在这种情况下,你可以除以步长。e、 g.
slope=np.convolve(x,window,mode='same')/(len(window)-1)
您需要决定在边界处要做什么。默认情况下,使用0填充内容。如果要完全避免边界,请使用
mode='valid'
而不是
mode='same'
third_period_slope = np.diff(y[::3]) / np.diff(x[::3])
fifth_period_slope = np.diff(y[::5]) / np.diff(x[::5])
window = [-1, 0, 1]
slope = np.convolve(y, window, mode='same') / np.convolve(x, window, mode='same')