如何在numpy中计算斜率

7 投票
2 回答
22132 浏览
提问于 2025-04-17 01:48

如果我有一个包含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 个回答

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

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

7

我猜你是说在每第三个和第五个元素上计算的斜率,这样你就能得到一系列(准确的,不是最小二乘法的)斜率,对吧?

如果是这样的话,你可以按照以下方式操作:

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, 0, 0, 0, 1]

比如:

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

撰写回答