获取轴上numpy.argmax元素的索引 [英] Get indices of numpy.argmax elements over an axis
问题描述
我有N维矩阵,其中包含具有N个参数的函数的值。每个参数都有离散数量的值。我需要最大化除了一个参数之外的所有参数的函数,从而产生大小等于非最大化参数的值的一维向量。我还需要保存其他参数所采用的值。
I have N-dimensional matrix which contains the values for a function with N parameters. Each parameter has a discrete number of values. I need to maximize the function over all parameters but one, resulting in a one-dimensional vector of size equal to the number of values of the non-maximized parameter. I also need to save which values are taken by the other parameters.
为此,我想迭代地应用 numpy.max
在不同的轴上减少矩阵的维数以找到我需要的东西。最后的向量将仅取决于我遗漏的参数。
To do so I wanted to iteratively apply numpy.max
over different axes to reduce the dimensionality of the matrix to find what I need. The final vector will then depend on just the parameter I left out.
然而,我无法找到最终元素的原始索引(其中包含有关其他参数取的值)。我虽然使用 numpy.argmax
的方式与 numpy.max
相同,但我无法取回原件index。
I'm however having trouble finding the original indices of the final elements (which contain the information about the values taken by the other parameters). I though about using numpy.argmax
in the same way as numpy.max
but I can't obtain back the original indices.
我正在尝试的一个例子是:
An example of what I'm trying is:
x = [[[1,2],[0,1]],[[3,4],[6,7]]]
args = np.argmax(x, 0)
返回
[[1 1]
[1 1]]
这意味着argmax正在选择原始矩阵中的元素(2,1,4,7)。但如何获得他们的指数?我尝试 unravel_index
,直接使用 args
作为矩阵 x $ c的索引$ c>,从numpy到index的一堆函数没有成功。
Which means that argmax is selecting the elements (2,1,4,7) within the original matrix. But how to get their indices? I tried unravel_index
, using the args
directly as an index for matrix x
, a bunch of functions from numpy to index with no success.
使用 numpy.where
不是一个解决方案,因为输入矩阵内部可能有相同的值,所以我无法辨别不同的原始值。
Using numpy.where
is not a solution since the input matrix may have equal values inside, so I would not be able to discern from different original values.
推荐答案
x.argmax(0)
给出第1轴的索引以获得最大值。使用 np.indices
生成另一个轴的索引。
x.argmax(0)
gives the indexes along the 1st axis for the maximum values. Use np.indices
to generate the indices for the other axis.
x = np.array([[[1,2],[0,1]],[[3,4],[6,7]]])
x.argmax(0)
array([[1, 1],
[1, 1]])
a1, a2 = np.indices((2,2))
(x.argmax(0),a1,a2)
(array([[1, 1],
[1, 1]]),
array([[0, 0],
[1, 1]]),
array([[0, 1],
[0, 1]]))
x[x.argmax(0),a1,a2]
array([[3, 4],
[6, 7]])
x[a1,x.argmax(1),a2]
array([[1, 2],
[6, 7]])
x[a1,a2,x.argmax(2)]
array([[2, 1],
[4, 7]])
如果 x
有其他尺寸,适当生成 a1
和 a2
。
If x
has other dimensions, generate a1
, and a2
appropriately.
官方文档没有说明如何使用 argmax
,但早期的SO线程已经讨论过了。我从在多维数组上使用numpy.argmax()获得了这个一般性的想法
The official documentation does not say much about how to use argmax
, but earlier SO threads have discussed it. I got this general idea from Using numpy.argmax() on multidimensional arrays
这篇关于获取轴上numpy.argmax元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!