我想我误解了 numpy 中的索引。
我有一个形状为 (dim_x, dim_y, dim_z) 的 3D-numpy 数组,我想找到沿第三轴 (dim_z) 的最大值,然后设置它的值为 1,所有其他值为零。
问题是我最终在同一行中有几个 1,即使值不同也是如此。
代码如下:
>>> test = np.random.rand(2,3,2)
>>> test
array([[[ 0.13110146, 0.07138861],
[ 0.84444158, 0.35296986],
[ 0.97414498, 0.63728852]],
[[ 0.61301975, 0.02313646],
[ 0.14251848, 0.91090492],
[ 0.14217992, 0.41549218]]])
>>> result = np.zeros_like(test)
>>> result[:test.shape[0], np.arange(test.shape[1]), np.argmax(test, axis=2)]=1
>>> result
array([[[ 1., 0.],
[ 1., 1.],
[ 1., 1.]],
[[ 1., 0.],
[ 1., 1.],
[ 1., 1.]]])
我期待结束:
array([[[ 1., 0.],
[ 1., 0.],
[ 1., 0.]],
[[ 1., 0.],
[ 0., 1.],
[ 0., 1.]]])
可能我在这里遗漏了什么。据我了解,0:dim_x, np.arange(dim_y) 返回 dim_x 的 dim_y 元组和 np.argmax (test, axis=dim_z) 的形状是 (dim_x, dim_y) 所以如果索引是 [x, y, z] 的形式[x, y] 不应出现两次。
有人可以解释我错在哪里吗?提前致谢。
请您参考如下方法:
我们在寻找什么
我们得到沿最后一个轴的 argmax 索引 -
idx = np.argmax(test, axis=2)
对于给定的示例数据,我们有 idx :
array([[0, 0, 0],
[0, 1, 1]])
现在,idx 覆盖第一和第二轴,同时获取那些 argmax 索引。
要在输出中分配相应的值,我们需要为前两个轴创建范围数组,覆盖沿这些轴的长度并根据 idx 的形状对齐.现在,idx 是形状为 (m,n) 的 2D 数组,其中 m = test.shape[0] 和 n = test.shape[1]。
因此,分配到输出的前两个轴的范围数组必须是 -
X = np.arange(test.shape[0])[:,None]
Y = np.arange(test.shape[1])
注意,需要将第一个范围数组扩展到 2D 以使其与 idx 和 Y 的行对齐针对 idx 的列 -
In [239]: X
Out[239]:
array([[0],
[1]])
In [240]: Y
Out[240]: array([0, 1, 2])
示意性地放置-
idx :
Y array
--------->
x x x | X array
x x x |
v
原代码错误
你的代码是 -
result[:test.shape[0], np.arange(test.shape[1]), ..
这本质上是:
result[:, np.arange(test.shape[1]), ...
因此,您选择了第一个轴上的所有元素,而不是仅选择对应于 idx 索引的相应元素。在此过程中,您选择的元素比分配所需的元素多得多,因此您在 result 数组中看到的 1s 多于所需的元素。
更正
因此,唯一需要的校正是使用范围数组索引到第一个轴,一个可行的解决方案是 -
result[np.arange(test.shape[0])[:,None], np.arange(test.shape[1]), ...
备选方案
或者,使用之前使用 X 和 Y 创建的范围数组 -
result[X,Y,idx] = 1
获取 X,Y 的另一种方法是使用 np.mgrid -
m,n = test.shape[:2]
X,Y = np.ogrid[:m,:n]
