【问题标题】:TensorFlow: Max of a tensor along an axisTensorFlow:沿轴的张量的最大值
【发布时间】:2016-05-01 11:05:04
【问题描述】:

我的问题是两个相关的部分:

  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]
    

    我知道有一个tf.argmax 和一个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)。

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

    附加信息:我知道xy 将只是二维张量!

【问题讨论】:

    标签: python tensorflow deep-learning max tensor


    【解决方案1】:

    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)
    

    要获得与输入张量相同维度的结果张量,请使用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
    

    【讨论】:

      【解决方案2】:

      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,则可以通过使用 tf.reshape()y 展平,将 argmax 索引转换为向量索引,并使用 @987654324,从不同的张量 y 获取值@提取适当的值:

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

      【讨论】:

      • 为了完整起见,在第二个示例中,请在第 3 行添加:amax = tf.argmax(y, 1) 并删除第一行。
      • reduction_indices 已弃用。改用axis
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2020-02-08
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多