如何沿矩阵轴执行滚动求和? [英] How to perform a rolling sum along a matrix axis?

查看:48
本文介绍了如何沿矩阵轴执行滚动求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定矩阵 X 具有 T 行和列 k:

Given matrix X with T rows and columns k:

T = 50
H = 10
k = 5 
X = np.arange(T).reshape(T,1)*np.ones((T,k))

如何在滞后H的情况下沿行轴执行X的滚动累积和?

How to perform a rolling cumulative sum of X along the rows axis with lag H?

Xcum = np.zeros((T-H,k))
for t in range(H,T):
    Xcum[t-H,:] = np.sum( X[t-H:t,:], axis=0 )

注意,在广播/矢量化最佳实践下,最好避免跨步和卷积.

Notice, preferably avoiding strides and convolution, under broadcasting/vectorization best practices.

推荐答案

听起来您想要以下内容:

Sounds like you want the following:

import scipy.signal
scipy.signal.convolve2d(X, np.ones((H,1)), mode='valid')

这当然使用卷积,但如上所述,问题是卷积运算.广播会导致算法更慢/内存密集.

This of course uses convolve, but the question, as stated, is a convolution operation. Broadcasting would result in a much slower/memory intensive algorithm.

这篇关于如何沿矩阵轴执行滚动求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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