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



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

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

这是我的代码:

#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])调用的节点开始:变量的顺序毫无意义。张量流图评估从一个随机节点开始,跟随每个节点从叶子到根。

由于你想要强制特定的执行顺序,你必须使用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)

最新更新