gpt4 book ai didi

python - 如何计算numpy中的斜率

转载 作者:太空狗 更新时间:2023-10-29 21:35:27 26 4
gpt4 key购买 nike

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

但是数组的长度是否相同

@乔:::

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

除了 -6、-6.5 和 -14 不是我正在寻找的结果外,斜率和斜率 2 是我想要的。

这有效......

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

最佳答案

我假设您的意思是每第 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, 0, 0, 0, 1]

例如

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

关于python - 如何计算numpy中的斜率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7350588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com