4D NumPy数组中每个2D矩阵的最大值 [英] Max of each 2D matrix in 4D NumPy array

查看:112
本文介绍了4D NumPy数组中每个2D矩阵的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个4D数组,其定义如下:

I have a 4D array, which is defined as follows:

B = np.array(
    [[[[0.5000, 0.5625],
       [0.5000, 0.5625]],

      [[1.2500, 0.5000],
       [0.5625, 0.6875]],

      [[0.5625, 0.6250],
       [0.5000, 0.5625]]]]
)

我想获取每个2D矩阵的最大值,以便得到以下结果:

I want to take the max of each 2D matrix, such that I get a result of:

array([0.5625, 1.250, 0.6250])

类似地,我想获取每个2D矩阵的最小值,以便得到以下结果:

Similarly, I want to take the min of each 2D matrix, such that I get a result of:

array([0.5000, 0.5000, 0.5000])

但是,当执行 np.max(B,axis = 0) np.max(B,axis = 1) np.max(B,axis = 2) np.max(B,axis = 3)-这些都不能给出正确的答案.我需要指定另一个参数来执行此操作吗?

However, when doing np.max(B, axis=0), np.max(B, axis=1), np.max(B, axis=2), or np.max(B, axis=3) -- none of these gives the right answer. Is there another argument I need to specify to do this operation?

正确的解决方案不应使用任何循环,理想情况下不应使用一个函数调用.

The correct solution should not use any loops and ideally one function call.

推荐答案

我认为这个问题是对 axis 参数如何工作的误解.对于大多数这些聚合方法, axis 关键字是要投影 的一个或多个轴,即这些轴被移除".从结果.因此,在这种情况下,您想调用类似的内容:

I think the issue is a misunderstanding of how the axis argument works. For most of these aggregation methods the axis keyword is the axis (or axes) to project along, i.e. these axes are "removed" from the result. So in this case you want to call something like:

In [7]: B.max((0, 2, 3))                                                                                                            
Out[7]: array([0.5625, 1.25  , 0.625 ])

min

In [8]: B.min((0, 2, 3))                                                                                                            
Out[8]: array([0.5, 0.5, 0.5])

或者您可以直接调用 numpy 方法

Or you can call the numpy method directly

In [9]: np.max(B, axis=(0, 2, 3))                                                                                                   
Out[9]: array([0.5625, 1.25  , 0.625 ])

这篇关于4D NumPy数组中每个2D矩阵的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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