dan*_*451 16 python arrays indexing tensorflow
我刚注意到TensorFlow中的一个意外(至少对我来说)行为.我认为tf.argmax
( - argmin
)从外到内操作Tensor的行列,但显然它没有?!
例:
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)
Run Code Online (Sandbox Code Playgroud)
tf.argmax
有两个参数:input
和dimension
.由于数组的索引arr
是arr[rows, columns]
,我希望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
Run Code Online (Sandbox Code Playgroud)
有人可以解释这种行为吗?
广义的每个n维张量都t
被索引t[i, j, k, ...]
.因此,t
具有等级n和形状(i, j, k, ...)
.由于尺寸0对应于i
尺寸1 j
,等等.为什么tf.argmax
(& - argmin
)会忽略这个方案?
lba*_*les 21
想想作为你减少的轴的dimension
论点tf.argmax
.tf.argmax(arr, 0)
减少跨维度0
,即行.减少行数意味着您将获得每个列的argmax.
这可能违反直觉,但它符合等中使用的约定tf.reduce_max
.