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

标签 python tensorflow fibonacci

我正在尝试学习 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]) 的节点开始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/

相关文章:

java - 如何检查一个数字的每个数字是否大于或等于另一个数字?

python - 取消新阵列与旧阵列的链接 : python

python - coursera作业python文件编译错误

python - 通过线性回归进行 tensorflow 图像分割

python - 在一个字典中创建多个动态字典

python - PyQt - 如何正确使用 "setStyleSheet"方法?

Python:使用 TensorFlow 计算神经网络的准确性

c++ - 斐波那契数列乘积之和

javascript - 为什么这个斐波那契数函数在第 4000 个值时返回无穷大?

performance - 哪个斐波那契函数计算速度更快?