numpy.convolve的加权移动平均值 [英] weighted moving average with numpy.convolve

查看:208
本文介绍了numpy.convolve的加权移动平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个移动平均函数,该函数使用numpy中的卷积函数,该函数应等效于(加权移动平均线).当我的权重都相等时(如简单的算术平均值),效果很好:

I'm writing a moving average function that uses the convolve function in numpy, which should be equivalent to a (weighted moving average). When my weights are all equal (as in a simple arithmatic average), it works fine:

data = numpy.arange(1,11)
numdays = 5
w = [1.0/numdays]*numdays
numpy.convolve(data,w,'valid')

给予

array([ 3.,  4.,  5.,  6.,  7.,  8.])

但是,当我尝试使用加权平均值时

However, when I try to use a weighted average

w = numpy.cumsum(numpy.ones(numdays,dtype=float),axis=0); w = w/numpy.sum(w)

而不是(对于相同的数据)3.667,4.667,5.667,6.667,...我希望,我得到

instead of the (for the same data) 3.667,4.667,5.667,6.667,... I expect, I get

array([ 2.33333333,  3.33333333,  4.33333333,  5.33333333,  6.33333333,
        7.33333333])

如果删除有效"标志,我什至看不到正确的值.我真的很想对WMA和MA使用convolve,因为它可以使代码更简洁(相同的代码,不同的权重),否则我认为我必须遍历所有数据并进行切片.

If I remove the 'valid' flag, I don't even see the correct values. I would really like to use convolve for the WMA as well as MA as it makes the code cleaner (same code, different weights) and otherwise I think I'll have to loop through all the data and take slices.

关于这种行为有什么想法吗?

Any ideas about this behavior?

推荐答案

您想要的是卷积中的np.correlate,第二个参数基本上被反转了,因此您期望的结果将是np.convolve(data, w[::-1], 'valid').

What you want is np.correlate in a convolution the second argument is inverted basically, so that your expected result would be with np.convolve(data, w[::-1], 'valid').

这篇关于numpy.convolve的加权移动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆