【问题标题】:How to pass parmeters to functions inside tf.cond in Tensorflow?如何将参数传递给 Tensorflow 中 tf.cond 中的函数?
【发布时间】:2016-08-01 10:56:02
【问题描述】:

我有以下简单的占位符:

x = tf.placeholder(tf.float32, shape=[1])
y = tf.placeholder(tf.float32, shape=[1])
z = tf.placeholder(tf.float32, shape=[1])

有两个函数fn1fn2定义为:

def fn1(a, b): 
    return tf.mul(a, b)
def fn2(a, b): 
    return tf.add(a, b)

现在我想根据 pred 条件计算结果:

pred = tf.placeholder(tf.bool, shape=[1])
result = tf.cond(pred, fn1(x,y), fn2(y,z))

但它给了我一个错误说fn1 and fn2 must be callable

如何编写fn1fn2 以便它们可以在运行时接收参数? 我想拨打以下电话:

sess.run(result, feed_dict={x:1,y:2,z:3,pred:True})

【问题讨论】:

    标签: python if-statement tensorflow


    【解决方案1】:

    您可以使用 lambda 将参数传递给函数,代码如下所示。

    x = tf.placeholder(tf.float32)
    y = tf.placeholder(tf.float32)
    z = tf.placeholder(tf.float32)
    
    def fn1(a, b):
      return tf.mul(a, b)
    
    def fn2(a, b):
      return tf.add(a, b)
    
    pred = tf.placeholder(tf.bool)
    result = tf.cond(pred, lambda: fn1(x, y), lambda: fn2(y, z))
    

    那你可以叫它如下:

    with tf.Session() as sess:
      print sess.run(result, feed_dict={x: 1, y: 2, z: 3, pred: True})
      # The result is 2.0
    

    【讨论】:

      【解决方案2】:

      最简单的方法是在调用中定义你的函数:

      result = tf.cond(pred, lambda: tf.mul(a, b), lambda: tf.add(a, b))
      

      【讨论】:

        猜你喜欢
        • 2021-05-22
        • 2017-07-11
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-30
        • 1970-01-01
        相关资源
        最近更新 更多