Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weighted moving average with numpy.convolve

Tags:

python

math

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

gives

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)

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

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?

like image 311
Dr. Andrew Avatar asked Oct 10 '12 09:10

Dr. Andrew


People also ask

How does numpy calculate moving average?

Method 1: Using Numpy A moving average can be calculated by finding the sum of elements present in the window and dividing it with window size.

How do you use convolve in Python?

Convolution is an operation that is performed on an image to extract features from it applying a smaller tensor called a kernel like a sliding window over the image. Depending on the values in the convolutional kernel, we can pick up specific patterns from the image.

What does numpy convolve do?

The np. convolve() is a built-in numpy library method used to return discrete, linear convolution of two one-dimensional vectors. The numpy convolve() method accepts three arguments which are v1, v2, and mode, and returns discrete the linear convolution of v1 and v2 one-dimensional vectors.

How do you find the moving average of an array in Python?

Use the pandas Module to Calculate the Moving Average We first convert the numpy array to a time-series object and then use the rolling() function to perform the calculation on the rolling window and calculate the Moving Average using the mean() function.


1 Answers

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').

like image 186
seberg Avatar answered Oct 03 '22 08:10

seberg