TensorFlow:我的斐波那契数列有什么问题?

TensorFlow: What is wrong with my fibonacci sequence?

我正在尝试学习 TensorFlow,所以我想写一个斐波那契数列(其中的一部分,ofc)。

此练习的灵感来自 IBM 认知 class。

这是我的代码:

#import stuff
import tensorflow as tf

# define the first 2 terms of the sequence
a = tf.Variable(0)
b = tf.Variable(1)

# define the next term. By definition it is the sum of the previous ones
newterm = tf.add(a,b)     # or newterm = a+b

# define the update operations. I want a to become b, and b to become the new term
update1 = tf.assign(a, b)
update2 = tf.assign(b, newterm)

# initialize variables
init = tf.global_variables_initializer()

# run
with tf.Session() as sess:
    sess.run(init)
    fibonacci = [a.eval(), b.eval()]
    for i in range(10):
         new, up1, up2 = sess.run([newterm, update1, update2])
         fibonacci.append(new)
    print(fibonacci)

然而这会打印 [0, 1, 2, 4, 8, 12, 24, 48, 96, 144, 240, 480]。我真的不明白我做错了什么。我只是创建下一个术语,然后使 ab 相同,bnewterm 相同。

Tensorflow 使用静态图描述计算。您首先必须定义图表,然后执行它。

图形执行从您放入sess.run([var1,var2, ..., vaN])调用的节点开始:变量的顺序是无意义。 Tensorflow 图评估从一个随机节点开始,并跟随每个节点从叶到根。

由于要强制执行特定顺序,因此必须使用 tf.control_dependencies 在图形中引入排序约束,从而使操作按特定顺序执行。

看看我是如何修改你的代码让它工作的,应该很清楚了。

import tensorflow as tf

# define the first 2 terms of the sequence
a = tf.Variable(0)
b = tf.Variable(1)

# you have to force the order of assigments:
# first execute newterm, then execute update1 and than update2

# define the next term. By definition it is the sum of the previous ones
newterm = tf.add(a,b)     # or newterm = a+b

with tf.control_dependencies([newterm]):
    update1 = tf.assign(a, b)

    # thus, execute update2 after update1 and newterm
    # have been executed

    with tf.control_dependencies([update1]):
        update2 = tf.assign(b, newterm)

# initialize variables
init = tf.global_variables_initializer()

# run
with tf.Session() as sess:
    sess.run(init)
    fibonacci = [a.eval(), b.eval()]
    for i in range(10):
         next, up1, up2 = sess.run([newterm, update1, update2])
         fibonacci.append(next)
    print(fibonacci)