San*_*ram 7 python if-statement tensorflow
我有以下简单的占位符:
x = tf.placeholder(tf.float32, shape=[1])
y = tf.placeholder(tf.float32, shape=[1])
z = tf.placeholder(tf.float32, shape=[1])
Run Code Online (Sandbox Code Playgroud)
有两个功能fn1,fn2定义如下:
def fn1(a, b):
return tf.mul(a, b)
def fn2(a, b):
return tf.add(a, b)
Run Code Online (Sandbox Code Playgroud)
现在我想根据pred条件计算结果:
pred = tf.placeholder(tf.bool, shape=[1])
result = tf.cond(pred, fn1(x,y), fn2(y,z))
Run Code Online (Sandbox Code Playgroud)
但它给我一个错误的说法fn1 and fn2 must be callable.
我怎么写fn1,fn2以便他们可以在运行时接收参数?我想打电话给以下人士:
sess.run(result, feed_dict={x:1,y:2,z:3,pred:True})
Run Code Online (Sandbox Code Playgroud)
Kon*_*sea 18
您可以使用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))
Run Code Online (Sandbox Code Playgroud)
然后你可以称之为:
with tf.Session() as sess:
print sess.run(result, feed_dict={x: 1, y: 2, z: 3, pred: True})
# The result is 2.0
Run Code Online (Sandbox Code Playgroud)
最简单的方法是在调用中定义函数:
result = tf.cond(pred, lambda: tf.mul(a, b), lambda: tf.add(a, b))
Run Code Online (Sandbox Code Playgroud)