tf.argmax()的主要功能是找出最大值并返回索引,注意是索引。下面是主要的内参数
tf.argmax(
input,
axis=None,
name=None,
dimension=None,
output_type=tf.int64
)
# input代表输入的数组
# axis代表张量的最大维数0代表1维,1代表行二维为None(0)
# name代表操作的名称,默认为None
# dimension:按某维度查找。0代表列,1代表行默认为None(0)。
# output_type,为输出的数据类型,可以指定为
举例说明:
import tensorflow as tf
import tensorflow.compat.v1 as tf1
tf1.disable_eager_execution()
a =[[1,2,3],[4,5,6],[1,5,4]]
b = [1,2,3,4,5,6,7,8,9,10,0]
with tf1.Session() as sess:
print(sess.run(tf.argmax(a, 0)))
print(sess.run(tf.argmax(a, 1)))
print(sess.run(tf.argmax(b, 0)))
结果如下:
2020-12-14 09:19:14.848367: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
[1 1 1]
[2 2 1]
9
基于上述程序进一步说明dimension和axis的问题。
在tf.argmax(input , 0) 中数字指的是axis。
在sess下加一行
print(sess.run(tf.argmax(b, 1, name='1')))
程序会报错
tensorflow.python.framework.errors_impl.InvalidArgumentError: Expected dimension in the range [-1, 1), but got 1
[[{{node 1_1}}]]
这个错误的意思是,这个向量的维数应在在[-1,1)的范围内不包含1,但是输入的axis是1,因此报错。
运行下面的程序
print(sess.run(tf.argmax(a, 0)))
print(sess.run(tf.argmax(a, 1)))
print(sess.run(tf.argmax(a, dimension=0)))
print(sess.run(tf.argmax(a, dimension=1)))
# print(sess.run(tf.argmax(a, 1,dimension=0)))
print(sess.run(tf.argmax(b, 0, name = '1')))
结果如下:
[1 1 1]
[2 2 1]
[1 1 1]
[2 2 1]
9
可以看到 axis = 0 的时候和 dimension = 0 的时候效果是一样的。因为实现相同效果的方法不一样,axis是按照维度筛选最大的值,demension是直接按照列筛选。
axis 和 dimension 不可同时指定
print(sess.run(tf.argmax(a, 1,dimension=0)))
ValueError: Cannot specify both 'dimension' and 'axis'
即使两个值最后实现的效果相同,也不可以同时指定。
进一步,在三维的张量中:
c = [[[1,2,3],[4,5,6],[1,5,4]],[[1,9,3],[4,5,6],[1,5,4]],[[7,2,3],[4,18,6],[1,5,4]]]
print(sess.run(tf.argmax(c, 0)))
print(sess.run(tf.argmax(c, 1)))
print(sess.run(tf.argmax(c, dimension=0)))
print(sess.run(tf.argmax(c, dimension=1)))
运行结果如下:
2020-12-14 09:35:03.115308: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
[[2 1 0]
[0 2 0]
[0 0 0]]
[[1 1 1]
[1 0 1]
[0 1 1]]
[[2 1 0]
[0 2 0]
[0 0 0]]
[[1 1 1]
[1 0 1]
[0 1 1]]
结论:dimension 和 axis在使用过程中表现出来的效果可能相同,但是原理不同且不可同时指定,使用argmax过程中需要注意。