Python numpy:如何从argmax结果中获取max
我有一个任意形状的numpy数组,例如:Python numpy:如何从argmax结果中获取max,python,numpy,argmax,Python,Numpy,Argmax,我有一个任意形状的numpy数组,例如: a = array([[[ 1, 2], [ 3, 4], [ 8, 6]], [[ 7, 8], [ 9, 8], [ 3, 12]]]) a.shape = (2, 3, 2) 以及最后一个轴上的argmax结果: np.argmax(a, axis=-1) = array([[1, 1, 0],
a = array([[[ 1, 2],
[ 3, 4],
[ 8, 6]],
[[ 7, 8],
[ 9, 8],
[ 3, 12]]])
a.shape = (2, 3, 2)
以及最后一个轴上的argmax结果:
np.argmax(a, axis=-1) = array([[1, 1, 0],
[1, 0, 1]])
我想要马克斯:
np.max(a, axis=-1) = array([[ 2, 4, 8],
[ 8, 9, 12]])
但不需要重新计算一切。我试过:
a[np.arange(len(a)), np.argmax(a, axis=-1)]
但是得到:
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (2,3)
怎么做?二维的类似问题:您可以使用-
对于任意维数的一般ndarray情况,如中所述,我们可以使用-
shp = np.array(a.shape)
dim_idx = list(np.ix_(*[np.arange(i) for i in shp[:-1]]))
dim_idx.append(idx)
out = a[dim_idx]
对于具有任意形状的ndarray,可以展平argmax索引,然后恢复正确的形状,如下所示:
idx = np.argmax(a, axis=-1)
flat_idx = np.arange(a.size, step=a.shape[-1]) + idx.ravel()
maximum = a.ravel()[flat_idx].reshape(*a.shape[:-1])
对于任意形状阵列,以下操作应有效:) 或
什么是重塑的?对不起,它应该是
a
。现在正在更正。好的,但是如何处理任意形状的数组而不是精确的3维?使用np.xi\ucode>和tuple concatenateidx
@hpaulj生成第一维谢谢,应该可以了!更新了帖子,谢谢。某处有打字错误吗?似乎没有使用DIM
。@sygi抱歉,尝试了一些不需要的东西。删除了那条线。
idx = np.argmax(a, axis=-1)
flat_idx = np.arange(a.size, step=a.shape[-1]) + idx.ravel()
maximum = a.ravel()[flat_idx].reshape(*a.shape[:-1])
a = np.arange(5 * 4 * 3).reshape((5,4,3))
# for last axis
argmax = a.argmax(axis=-1)
a[tuple(np.indices(a.shape[:-1])) + (argmax,)]
# for other axis (eg. axis=1)
argmax = a.argmax(axis=1)
idx = list(np.indices(a.shape[:1]+a.shape[2:]))
idx[1:1] = [argmax]
a[tuple(idx)]
a = np.arange(5 * 4 * 3).reshape((5,4,3))
argmax = a.argmax(axis=0)
np.choose(argmax, np.moveaxis(a, 0, 0))
argmax = a.argmax(axis=1)
np.choose(argmax, np.moveaxis(a, 1, 0))
argmax = a.argmax(axis=2)
np.choose(argmax, np.moveaxis(a, 2, 0))
argmax = a.argmax(axis=-1)
np.choose(argmax, np.moveaxis(a, -1, 0))