python - 同时求和 4 维矩阵的 3 个维度

标签 python python-2.7 numpy matrix

我有 4d 矩阵,mat4。有没有办法可以同时对矩阵的多个维度求和,而不是使用 np.sum(mat, axis=) 并定义 3 次 axis 来求和三个维度?

#Sum `mat4` except `axis=0`

mat4 = np.random.rand(2,3,4,5)
matsum = np.sum(mat4, axis=3)
matsum = np.sum(matsum, axis=2)
matsum = np.sum(matsum, axis=1)

print matsum.shape
>> (2L,)

最佳答案

axis 关键字可以是 inttuple,因此 你可以简单地使用

np.sum(mat, axis=(1, 2, 3))

来自np.sum文档:

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

关于python - 同时求和 4 维矩阵的 3 个维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52033761/

相关文章:

python-2.7 - 为什么我的代码会陷入无限循环?

Python - 使用 joblib 进行循环并行化

Python 3.6 : Why does pickle. 转储(nparray)永久增加引用计数?

python - 如何在 xmlrpc 服务器而不是客户端上查看回溯?

python - 如何转换列的值以扩展数据框?

python - 将时间增量四舍五入到最接近的 15 分钟

python - python audiolab中的蜂鸣声

python - 如何根据另一列中的值创建有序列(尽管不是累积计数)?

python - 查找两个数据帧之间的交集并取平均值 - Python

python - 如何提高这个程序的效率?