我正在尝试学习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]
。我真的不明白我做错了什么。我只是创建下一个字词,然后将a
与b
和b
相同,与newterm
相同。
答案 0 :(得分:4)
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)