TensorFlow:沿轴的张量的最大值 [英] TensorFlow: Max of a tensor along an axis

查看:868
本文介绍了TensorFlow:沿轴的张量的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题分为两个相互联系的部分:

My question is in two connected parts:

  1. 如何计算张量的特定轴上的最大值?例如,如果我有

  1. How do I calculate the max along a certain axis of a tensor? For example, if I have

x = tf.constant([[1,220,55],[4,3,-1]])

我想要

x_max = tf.max(x, axis=1)
print sess.run(x_max)

output: [220,4]

我知道有一个tf.argmaxtf.maximum,但是都没有给出沿单个张量轴的最大值.现在,我有一种解决方法:

I know there is a tf.argmax and a tf.maximum, but neither give the maximum value along an axis of a single tensor. For now I have a workaround:

x_max = tf.slice(x, begin=[0,0], size=[-1,1])
for a in range(1,2):
    x_max = tf.maximum(x_max , tf.slice(x, begin=[0,a], size=[-1,1]))

但是它看起来并不理想.有更好的方法吗?

But it looks less than optimal. Is there a better way to do this?

给定张量的argmax的索引,我如何使用这些索引索引到另一个张量?以上面的x示例为例,我该如何执行以下操作:

Given the indices of an argmax of a tensor, how do I index into another tensor using those indices? Using the example of x above, how do I do something like the following:

ind_max = tf.argmax(x, dimension=1)    #output is [1,0]
y = tf.constant([[1,2,3], [6,5,4])
y_ = y[:, ind_max]                     #y_ should be [2,6]

我知道切片(如最后一行)在TensorFlow中尚不存在(#206 ).

I know slicing, like the last line, does not exist in TensorFlow yet (#206).

我的问题是:对于我的具体情况,最好的解决方法是什么(也许使用其他方法,例如collect,select等)?

其他信息:我知道xy仅将是二维张量!

Additional information: I know x and y are going to be two dimensional tensors only!

推荐答案

tf.reduce_max() 运算符完全提供了此功能.默认情况下,它计算给定张量的全局最大值,但是您可以指定reduction_indices的列表,该列表的含义与NumPy中的axis相同.要完成您的示例:

The tf.reduce_max() operator provides exactly this functionality. By default it computes the global maximum of the given tensor, but you can specify a list of reduction_indices, which has the same meaning as axis in NumPy. To complete your example:

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,则您通过使用 tf.reshape() ,如下将argmax索引转换为向量索引,并使用

If you compute the argmax using tf.argmax(), you could obtain the the values from a different tensor y by flattening y using tf.reshape(), converting the argmax indices into vector indices as follows, and using tf.gather() to extract the appropriate values:

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)"

这篇关于TensorFlow:沿轴的张量的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆