【问题标题】:Detecting whether last dimension is 1 or 5 in TensorFlow?在TensorFlow中检测最后一个维度是1还是5?
【发布时间】:2017-11-24 15:57:17
【问题描述】:

我正在编写 TensorFlow (python) 逻辑来确定张量的最后一个维度是 1 还是 5。如果张量是标量,则此表达式应该为 false。在图构建时,张量的形状是未知的。

给定张量input,我已经尝试过

tf.logical_and(
  # The tensor must not be a scalar.
  tf.greater(tf.rank(input), 0),
  # Check the last dimension.
  tf.logical_or(
    tf.equal(tf.shape(input)[-1], 1),
    tf.equal(tf.shape(input)[-1], 5)
  )
)

但是,当 input 张量是标量时,此逻辑会引发错误,因为表达式的 tf.greater(tf.rank(input), 0) 部分无法导致 TensorFlow 短路(并避免执行图表的 tf.logical_or 部分)。这是预期的行为。

有什么方法可以找到张量的最后一个维度,但让逻辑优雅地处理输入张量是标量的情况?

例如,也许有一种方法可以强制执行导致排名检查首先运行的控制依赖关系?

我想我可以在这里使用tf.cond,但我对调用 lambda 函数如何改变图形有点不安。

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    您可以简单地扩展输入张量的尺寸以使其适用于所有情况(即将标量情况转换为张量):

    import tensorflow as tf
    import numpy as np
    
    input = tf.placeholder(tf.float32)
    input_expanded = tf.expand_dims(input, axis=0)
    last_dim_size = tf.shape(input_expanded)[-1]
    
    result_tensor = tf.logical_and(
        # The tensor must not be a scalar.
        tf.greater(tf.rank(input_expanded) - 1, 0),
        # Check the last dimension.
        tf.logical_or(
            tf.equal(last_dim_size, 1),
            tf.equal(last_dim_size, 5)
        )
    )
    
    with tf.Session() as sess:
        for input_value in [1, np.zeros((2,)), np.zeros((1, 5)), np.zeros((1, 2, 6))]:
            result = sess.run(result_tensor, feed_dict={input: input_value})
            print('Input: {}'.format(input_value))
            print('Output: {}'.format(result))
            print()
    

    输出:

    Input: 1
    Output: False
    
    Input: [ 0.  0.]
    Output: False
    
    Input: [[ 0.  0.  0.  0.  0.]]
    Output: True
    
    Input: [[[ 0.  0.  0.  0.  0.  0.]
      [ 0.  0.  0.  0.  0.  0.]]]
    Output: False
    

    【讨论】:

      【解决方案2】:

      在 TF2 中,您可以简单地使用 .shape 并检查最后一个 ([-1]) 维度是否是您要查找的任何维度。您不必运行会话,因为在版本 2 中默认启用了 Eager Execution。

      some_tensor.shape[-1] in [1, 5]
      

      colab 演示:https://colab.research.google.com/drive/1L4XD04XBuPSBeaB7Bb-twpHJCyYPkZrt

      【讨论】:

        猜你喜欢
        • 2021-05-20
        • 2021-06-05
        • 2016-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        相关资源
        最近更新 更多