加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何计算numpy中的斜率

发布时间:2020-12-16 23:44:47 所属栏目:Python 来源:网络整理
导读:如果我有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)
如果我有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,-1]
window2 = [1,-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是Im之后的除了-6,-6.5和-14不是我正在寻找的结果.

这工作…….

window    = [1,-1]
slope     = np.convolve(xx,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,1]或[-1]窗口的卷积,1].

例如.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读