2016-08-01 13 views
5

Ich habe folgende einfache Platzhalter:Wie können Parameter in Tensorflow an Funktionen innerhalb von Sekunden übergeben werden?

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

Es gibt zwei Funktionen f1 und f2 wie folgt definiert:

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

Jetzt möchte ich Ergebnis auf pred Zustand berechnen auf Basis:

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

Aber es gibt mir einen Fehler, der fn1 and fn2 must be callable sagt.

Wie kann ich schreiben fn1 und fn2, damit sie Parameter zur Laufzeit erhalten können? Ich möchte folgendes nennen:

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

Antwort

1

Die einfachste wäre Ihre Funktionen in dem Aufruf zu definieren:

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

Sie Parameter an die Funktionen Lambda unter Verwendung passieren kann und der Code ist als Balg.

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

Dann können Sie es als Gebrüll nennen:

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