我正在尝试学习 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]
。我真的不明白我做错了什么。我只是创建下一个术语,然后使 a
与 b
相同,并且 b
与 newterm
相同>.
最佳答案
Tensorflow 使用静态图描述计算。您首先必须定义图表,然后执行它。
图形执行从您放入 sess.run([var1,var2, ..., vaN])
的节点开始call:变量的顺序无意义。 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)
关于python - TensorFlow:我的斐波那契数列有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218627/