简体   繁体   English

改进我的移动平均函数的 Numpy 方法

[英]Numpy Methods to improve my Moving Average function

I have a function to calculate the moving average of numpy arrays imported from a file.我有一个函数来计算从文件导入的 numpy 数组的移动平均值。 This function works fine, but I was wondering if anyone knows a quicker method, using one of numpy methods to have the same outcome??这个函数工作正常,但我想知道是否有人知道更快的方法,使用 numpy 方法之一来获得相同的结果?

Data:数据:

b = [[1, 2, 3],
 [2, 3, 4],
 [3, 4, 5],
 [6, 7, 8],
 [4, 5, 6]]

def mod_movAvg(arr):
    rowNum, colNum = arr.shape
    res = np.zeros((rowNum - 1, colNum))
    for col in range(colNum):
        for row in range(rowNum - 1):
            res[row][col] = 0.5*(arr[row][col] + arr[row+1][col])
    return res

output:输出:

[[1.5 2.5 3.5]
 [2.5 3.5 4.5]
 [4.5 5.5 6.5]
 [5.  6.  7. ]]

Convolution is the keyword here. Convolution是这里的关键词。 You have a 2D array but perform the convolution only along one axis, so maybe this question is relevant.您有一个二维数组,但仅沿一个轴执行卷积,所以这个问题可能是相关的。

  • for 1D convolution you could use numpy.convolve()对于一维卷积,您可以使用numpy.convolve()
  • for 2D convolution you could use scipy.signal.covolve2d()对于 2D 卷积,您可以使用scipy.signal.covolve2d()

In you case you move the kernel with shape (2,1)在你的情况下,你用形状(2,1)移动内核

[[0.5],[0.5]]

over the array to get the values在数组上获取值

res[row][col] = 0.5*arr[row][col] + 0.5*arr[row+1][col]

Applied to your example:应用于您的示例:

import scipy.signal as sg

b = [[1, 2, 3],
     [2, 3, 4],
     [3, 4, 5],
     [6, 7, 8],
     [4, 5, 6]]

res = sg.convolve2d(b, [[0.5], [0.5]], mode='valid')

This approach is fast and easy to generalize:这种方法快速且易于推广:

kernel = (3, 2)
sg.convolve2d(arr, np.full(kernel, 1/np.size(kernel)), mode='valid')

First, b can be converted to a numpy matrix (which are stored more efficiently in memory) using:首先,可以使用以下方法将b转换为 numpy 矩阵(它们在内存中的存储效率更高):

b = np.matrix(b)

Then, you can just do what you want more efficiently using:然后,您可以使用以下方法更有效地做您想做的事:

result = 0.5 * (b[:-1,:] + b[1:,:])

result will be a numpy matrix too. result也将是一个 numpy 矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM