Python TensorFlow:argmax(-min)

Python TensorFlow:argmax(-min),python,arrays,indexing,tensorflow,Python,Arrays,Indexing,Tensorflow,我刚刚注意到TensorFlow中有一个意想不到的行为(至少对我来说是这样)。我以为tf.argmax(argmin)从外到内在张量的列上运行,但显然它没有 例如: import numpy as np import tensorflow as tf sess = tf.InteractiveSession() arr = np.array([[31, 23, 4, 24, 27, 34], [18, 3, 25, 0, 6, 35],

我刚刚注意到TensorFlow中有一个意想不到的行为(至少对我来说是这样)。我以为
tf.argmax
argmin
)从外到内在张量的列上运行,但显然它没有

例如:

import numpy as np
import tensorflow as tf

sess = tf.InteractiveSession()

arr = np.array([[31, 23,  4, 24, 27, 34],
                [18,  3, 25,  0,  6, 35],
                [28, 14, 33, 22, 20,  8],
                [13, 30, 21, 19,  7,  9],
                [16,  1, 26, 32,  2, 29],
                [17, 12,  5, 11, 10, 15]])

# arr has rank 2 and shape (6, 6)
tf.rank(arr).eval()
> 2
tf.shape(arr).eval()
> array([6, 6], dtype=int32)
tf.argmax
接受两个参数:
input
dimension
。由于数组
arr
的索引是
arr[行,列]
,我希望
tf.argmax(arr,0)
返回每行的最大元素索引,而我希望
tf.argmax(arr,1)
返回每列的最大元素。同样适用于
tf.argmin

然而,事实恰恰相反:

tf.argmax(arr, 0).eval()
> array([0, 3, 2, 4, 0, 1])

# 0 -> 31 (arr[0, 0])
# 3 -> 30 (arr[3, 1])
# 2 -> 33 (arr[2, 2])
# ...
# thus, this is clearly searching for the maximum element
# for every column, and *not* for every row

tf.argmax(arr, 1).eval()
> array([5, 5, 2, 1, 3, 0])

# 5 -> 34 (arr[0, 5])
# 5 -> 35 (arr[1, 5])
# 2 -> 33 (arr[2, 2])
# ...
# this clearly returns the maximum element per row,
# albeit 'dimension' was set to 1
有人能解释这种行为吗


广义的每个n维张量
t
t[i,j,k,…]
索引。因此,
t
具有秩n和形状
(i,j,k,…)
。因为维度0对应于
i
,所以维度1对应于
j
,依此类推。为什么
tf.argmax
(&-
argmin
)忽略此方案?

tf.argmax
维度
参数视为减少的轴
tf.argmax(arr,0)
减少跨维度
0
,即行。跨行减少意味着您将获得每个列的argmax


这可能是违反直觉的,但它符合
tf.reduce\u max
等中使用的约定。

在n维张量中,任何给定维度都有n-1维,形成离散的二维子空间。按照同样的逻辑,它有n-2个三维子空间,一直到n-(n-1),n维子空间。可以将任何聚合表示为剩余子空间内的函数,也可以表示为正在聚合的子空间中的函数。由于子空间在聚合后将不再存在,Tensorflow选择将其作为跨该维度的操作来实现


坦白地说,这是Tensorflow的创建者的一个实现选择,现在你知道了。

还有与numpy相同的约定。你能解释为什么跨行减少意味着获得每个列的argmax吗?另外:对于n维张量,这是如何表现的?在5D张量中,我有点搞不清哪个维度与减少
I,j,k,l
m
有关。根据定义,如果在行中搜索最大值,就是在列中搜索。对于任何
d
维数组,将
argmax
穿过
i
th轴意味着,对于
d-1
剩余索引的任何可能组合,您正在搜索
arr[ind1,ind2,…,ind_i_减1,:,ind_i_加上_1,…,ind_d]
中的最大值。