我有 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
关键字可以是 int
或 tuple
,因此
你可以简单地使用
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/