gpt4 book ai didi

python - 如何将参数传递给 Tensorflow 中 tf.cond 中的函数?

转载 作者:太空狗 更新时间:2023-10-29 22:03:27 26 4
gpt4 key购买 nike

我有以下简单的占位符:

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 = 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})

最佳答案

您可以使用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

关于python - 如何将参数传递给 Tensorflow 中 tf.cond 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38697045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com