Szukaj…


Parametry

Parametr Detale
pred tensor TensorFlow typu bool
fn1 wywoływana funkcja, bez argumentów
fn2 wywoływana funkcja, bez argumentów
Nazwa (opcjonalnie) nazwa operacji

Uwagi

  • pred nie może być True ani False , musi to być tensor
  • Funkcje fn1 i fn2 powinny zwracać tę samą liczbę wyjść, z tymi samymi typami.

Podstawowy przykład

x = tf.constant(1.)
bool = tf.constant(True)

res = tf.cond(bool, lambda: tf.add(x, 1.), lambda: tf.add(x, 10.))
# sess.run(res) will give you 2.

Gdy f1 i f2 zwracają wiele tensorów

Dwie funkcje fn1 i fn2 mogą zwracać wiele tensorów, ale muszą zwracać dokładnie taką samą liczbę i typy wyjść.

x = tf.constant(1.)
bool = tf.constant(True)

def fn1():
    return tf.add(x, 1.), x

def fn2():
    return tf.add(x, 10.), x

res1, res2 = tf.cond(bool, fn1, fn2)
# tf.cond returns a list of two tensors
# sess.run([res1, res2]) will return [2., 1.]

zdefiniuj i użyj funkcji f1 i f2 z parametrami

Możesz przekazać parametry do funkcji w tf.cond () za pomocą lambda, a kod jest jak poniżej.

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

Następnie możesz nazwać to ryczeniem:

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


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow