只需
reshape将这两个轴中的每个轴分成形状各不相同的两个轴,
(5,20)以形成一个
4D数组,然后沿具有长度的轴求和
20,如-
Z_new = Z.reshape(5,20,5,20).sum(axis=(1,3))
功能相同,但可能更快
np.einsum-
Z_new = np.einsum('ijkl->ik',Z.reshape(5,20,5,20))通用块大小
扩展到一般情况-
H,W = 5,5 # block-sizem,n = Z.shapeZ_new = Z.reshape(H,m//H,W,n//W).sum(axis=(1,3))
有了
einsum-
Z_new = np.einsum('ijkl->ik',Z.reshape(H,m//H,W,n//W))要计算跨块的平均值/平均值,请使用
mean代替
sum方法。
通用块大小和缩小操作
延伸到使用
reduction已经运营
ufuncs支持多个
axes带有参数
axis的减少,这将是-
def blockwise_reduction(a, height, width, reduction_func=np.sum): m,n = a.shape a4D = a.reshape(height,m//height,width,n//width) return reduction_func(a4D,axis=(1,3))
因此,要解决我们的特定情况,将是:
blockwise_reduction(Z, height=5, width=5)
对于逐块平均计算,将是-
blockwise_reduction(Z, height=5, width=5, reduction_func=np.mean)



