我的问题分为两个相关的部分:
X= tf.constant([1,220,55,4,3,-1])
我想要像这样的东西
x_max = tf.max(x,axis=1)打印sess.run(x_max)输出: 220,4
我知道有一个tf.argmax
和一个tf.maximum
,但都没有给出沿着单个张量的轴的最大值。现在,我有一个变通方法:
范围(1,2)内的x_max = tf.slice(x,begin=0,0,size=-1,1):x_max = tf.maximum(x_max,tf.slice(x,begin=0,a,size=-1,1))
但它看起来并不是最优的。有没有更好的方法呢?
argmax
的索引,如何使用这些索引索引到另一个张量?以上面的x
为例,我该如何做如下所示:ind_max = tf.argmax(x,dimension=1) #输出为1,0 y= tf.constant([1,2,3,6,5,4) y_ = y:,ind_max #y_应为2,6
我知道切片,就像最后一行一样,在TensorFlow (#206)中还不存在。
我的问题是:对于我的特定情况,最好的变通方法是什么(可能使用其他方法,如收集、选择等)?
补充信息:我知道x
和y
将只是二维张量!
发布于 2016-01-25 16:30:28
tf.reduce_max()
操作符提供的正是这种功能。默认情况下,它计算给定张量的全局最大值,但您可以指定一个reduction_indices
列表,该列表的含义与NumPy中的axis
相同。要完成您的示例:
x = tf.constant([[1, 220, 55], [4, 3, -1]])
x_max = tf.reduce_max(x, reduction_indices=[1])
print sess.run(x_max) # ==> "array([220, 4], dtype=int32)"
如果使用tf.argmax()
计算argmax,则可以从不同的张量y
获得值,方法是使用tf.reshape()
将y
展平,将argmax索引转换为向量索引,如下所示,并使用tf.gather()
提取适当的值:
ind_max = tf.argmax(x, dimension=1)
y = tf.constant([[1, 2, 3], [6, 5, 4]])
flat_y = tf.reshape(y, [-1]) # Reshape to a vector.
# N.B. Handles 2-D case only.
flat_ind_max = ind_max + tf.cast(tf.range(tf.shape(y)[0]) * tf.shape(y)[1], tf.int64)
y_ = tf.gather(flat_y, flat_ind_max)
print sess.run(y_) # ==> "array([2, 6], dtype=int32)"
发布于 2018-10-13 02:10:06
从TensorFlow 1.10.0-dev20180626开始,接受axis
和keepdims
关键字参数,提供与numpy.max
类似的功能。
In [55]: x = tf.constant([[1,220,55],[4,3,-1]])
In [56]: tf.reduce_max(x, axis=1).eval()
Out[56]: array([220, 4], dtype=int32)
要获得与输入张量维度相同的结果张量,请使用keepdims=True
In [57]: tf.reduce_max(x, axis=1, keepdims=True).eval()Out[57]:
array([[220],
[ 4]], dtype=int32)
如果没有显式指定axis
参数,则返回张量级别最大元素(即所有轴都被减少)。
In [58]: tf.reduce_max(x).eval()
Out[58]: 220
https://stackoverflow.com/questions/34987509
复制相似问题