【问题标题】:Tensorflow while loop runs only onceTensorFlow while 循环只运行一次
【发布时间】:2017-03-16 12:39:03
【问题描述】:

下面的 while 循环应该打印 "\n\nInside while..." 10 次,但是当我运行图表时,"\n\nInside while..." 只打印一次。这是为什么呢?

i = tf.constant(0)

def condition(i):
   return i < 10

def body(i):
    print("\n\nInside while...", str(i))
    return i + 1

r = tf.while_loop(condition, body, [i])

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:

    您的问题来自于将 TensorFlow 图形构建与图形执行混为一谈。

    您传递给 tf.while_loop 的函数会执行一次,以生成负责执行循环本身的 TensorFlow 图。因此,如果您将 tf.Print 放在那里(例如,说 return tf.Print(i+1, [i+1])),您会在 TensorFlow 系统实际执行循环时看到它打印 10 次。

    【讨论】:

      【解决方案2】:

      我对 TensorFlow 几乎一无所知,也无法帮助您解决当前的问题,但是如果您以不同的方式编写代码,您可以完成类似的事情(也许)。按照您程序的逻辑,下面设计了while_loop 的不同实现。您的conditionbody 需要运行一个while 循环,该循环已通过传递给它的函数进行参数化。下面显示的是与口译员的对话,展示了如何做到这一点。

      >>> def while_loop(condition, body, local_data):
          while condition(*local_data):
              local_data = body(*local_data)
          return local_data
      
      >>> i = 0
      >>> def condition(i):
          return i < 10
      
      >>> def body(i):
          print('Inside while', i)
          return i + 1,
      
      >>> local_data = while_loop(condition, body, (i,))
      Inside while 0
      Inside while 1
      Inside while 2
      Inside while 3
      Inside while 4
      Inside while 5
      Inside while 6
      Inside while 7
      Inside while 8
      Inside while 9
      >>> local_data
      (10,)
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 2020-04-29
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        • 2013-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多