代码之家  ›  专栏  ›  技术社区  ›  HIMANSHU RAI

在tf.while\u循环中可以定义多个条件吗

  •  1
  • HIMANSHU RAI  · 技术社区  · 8 年前

    是否可以定义tf终止的多个条件。while\u环在tensorflow中?例如,根据两个张量值实现两个特定值。如。 i==2 j==3

    我可以在正文中有几个代码块吗?在文档中的所有示例中,主体似乎更像是返回值或元组的单个语句。我想执行一组” 顺序的

    1 回复  |  直到 8 年前
        1
  •  3
  •   nessuno    8 年前

    tf.while_loop 接受泛型可调用函数(用 def

    因此,可以使用 logical operators 喜欢 tf.logical_and , tf.logical_or , ...

    body

    这样的做法完全可以接受,而且效果很好:

    import tensorflow as tf
    import numpy as np
    
    
    def body(x):
        a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)
        b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)
        c = a + b
        return tf.nn.relu(x + c)
    
    
    def condition(x):
        x = tf.Print(x, [x])
        return tf.logical_or(tf.less(tf.reduce_sum(x), 1000), tf.equal(x[0, 0], 15))
    
    
    x = tf.Variable(tf.constant(0, shape=[2, 2]))
    result = tf.while_loop(condition, body, [x])
    
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        print(sess.run(result))