【问题标题】:Writing piece-wise functions in TensorFlow / if then in TensorFlow在 TensorFlow / if then 在 TensorFlow 中编写分段函数
【发布时间】:2016-06-23 00:51:19
【问题描述】:

如何编写分段 TensorFlow 函数,即其中包含 if 语句的函数?

当前代码

import tensorflow as tf

my_fn = lambda x : x ** 2 if x > 0 else x + 5
with tf.Session() as sess:
  x = tf.Variable(tf.random_normal([100, 1]))
  output = tf.map_fn(my_fn, x)

错误:

TypeError:不允许将tf.Tensor 用作Python bool。使用if t is not None:而不是if t:来测试是否定义了张量,并使用逻辑TensorFlow ops来测试张量的值。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    使用tf.cond 实现此目的的最简单方法

    res = tf.cond(tf.greater(x, 0), lambda: tf.square(x), lambda: x + 5)
    

    【讨论】:

      【解决方案2】:

      你应该看看tf.where

      对于你的例子,你可以这样做:

      condition = tf.greater(x, 0)
      res = tf.where(condition, tf.square(x), x + 5)
      

      编辑:从tf.select 移动到tf.where

      【讨论】:

      • tf.select 在 1.0 版本中更改为 tf.where。谷歌搜索很快就会产生这个结果,但在这个答案中可能值得注意@Olivier。干杯!
      【解决方案3】:

      tf.select 也不再像此线程所指示的那样工作 https://github.com/tensorflow/tensorflow/issues/8647

      对我有用的是tf.where

      condition = tf.greater(x, 0)
      res = tf.where(condition, tf.square(x), x + 5)
      

      【讨论】:

        【解决方案4】:

        这里的问题是my_fn 无法检查条件x>0,因为xtf.Tensor,这意味着只有在启动 tensorflow 会话并且您请求运行包含x 的图形的一部分。要在图表本身中包含 if-then 逻辑,您必须使用 tensorflow 提供的操作,例如tf.select.

        【讨论】:

          猜你喜欢
          • 2016-02-14
          • 2020-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多