Python TensorFlow:张量沿轴的最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34987509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:50:09  来源:igfitidea点击:

TensorFlow: Max of a tensor along an axis

pythontensorflowdeep-learningmaxtensor

提问by aphdstudent

My question is in two connected parts:

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

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

    I want something like

    x_max = tf.max(x, axis=1)
    print sess.run(x_max)
    
    output: [220,4]
    

    I know there is a tf.argmaxand 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?

  2. Given the indices of an argmaxof a tensor, how do I index into another tensor using those indices? Using the example of xabove, 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]
    

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

    My question is: what is the best workaround for my specific case (maybe using other methods like gather, select, etc.)?

    Additional information: I know xand yare going to be two dimensional tensors only!

  1. 如何计算张量沿某个轴的最大值?例如,如果我有

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

    我想要类似的东西

    x_max = tf.max(x, axis=1)
    print sess.run(x_max)
    
    output: [220,4]
    

    我知道有 atf.argmax和 a tf.maximum,但都没有给出沿单个张量轴的最大值。现在我有一个解决方法:

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

    但它看起来不太理想。有一个更好的方法吗?

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

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

    我的问题是:对于我的特定情况(可能使用其他方法,如收集、选择等),最好的解决方法什么?

    附加信息:我知道x并且y将只是二维张量!

采纳答案by mrry

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 axisin NumPy. To complete your example:

tf.reduce_max()运营商提供的正是这种功能。默认情况下,它计算给定张量的全局最大值,但您可以指定 的列表reduction_indices,其含义与axisNumPy 中的含义相同。要完成您的示例:

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

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

如果您使用 计算 argmax tf.argmax(),您可以y通过展平yusing tf.reshape(),将 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)"

回答by kmario23

As of TensorFlow 1.10.0-dev20180626, tf.reduce_maxaccepts axisand keepdimskeyword arguments offering the similar functionality of numpy.max.

TensorFlow 1.10.0- dev20180626 开始tf.reduce_max接受axiskeepdims关键字参数提供与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)

To have a resultant tensor of the same dimension as the input tensor, use keepdims=True

要获得与输入张量相同维度的合成张量,请使用 keepdims=True

In [57]: tf.reduce_max(x, axis=1, keepdims=True).eval()Out[57]: 
array([[220],
       [  4]], dtype=int32)


If the axisargument is not explicitly specified then the tensor level maximum element is returned (i.e. all axes are reduced).

如果axis未明确指定参数,则返回张量级最大元素(即所有轴都减少)。

In [58]: tf.reduce_max(x).eval()
Out[58]: 220