张量流图中恢复变量的错误输出

Wrong output for restored variable in tensorflow graph

我目前正在研究变量的保存和恢复。为此,我创建了两个脚本。其中一个保存一个简单的图表,而另一个恢复它。这里是保存图表的测试脚本:

import tensorflow as tf

a = tf.Variable(3.0, name='a')
b = tf.Variable(5.0, name='b')

b = tf.assign_add(b, a)

n_steps = 5

global_step = tf.Variable(0, name='global_step', trainable=False)

saver = tf.train.Saver()

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    for step in range(n_steps):
        print(sess.run(b))

        global_step.assign_add(1).eval()
        print(global_step.eval())

        saver.save(sess, './my_test_model', global_step=global_step)

基本上,我想 运行 循环 5 次,每次我这样做时,我都会将 a 添加到 b。我还想通过 global_step 跟踪步数。这按预期工作。输出是:

8.0     # value of b
1       # step
11.0
2
14.0
3
17.0
4
20.0
5

现在在恢复变量时,我尝试获取所有三个变量。脚本是:

import tensorflow as tf

from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file

# List ALL tensors.
print_tensors_in_checkpoint_file(tf.train.latest_checkpoint('./'), all_tensors=True, tensor_name='')

tf.reset_default_graph()

a = tf.get_variable('a', shape=[])
b = tf.get_variable('b', shape=[])
global_step = tf.get_variable('global_step', shape=[])

saver = tf.train.Saver()

with tf.Session() as sess:

    ckpt = tf.train.latest_checkpoint('./')
    if ckpt:
        print(ckpt)

        saver.restore(sess, ckpt)

    else:
        print('Nothing restored')

    print(a.eval())
    print(b.eval())
    print(global_step.eval())

这个输出是

tensor_name:  a
3.0
tensor_name:  b
20.0
tensor_name:  global_step
5
./my_test_model-5
INFO:tensorflow:Restoring parameters from ./my_test_model-5
3.0
20.0
7e-45

global_step 的值怎么可能正确存储在检查点中,但在评估时我得到这么小的 7e-45?此外,在恢复时,我似乎无法定义任何其他变量,因为它声明它无法在检查点中找到变量。例如,我如何定义一个变量并将其添加到恢复图的 b

感谢您的帮助!

TF 文档似乎没有详细记录,但您应该为 global_step 变量指定数据类型。

不正确

global_step = tf.get_variable('global_step', shape=[], dtype=tf.float32) 结果 global_step=7e-5。默认类型假定为 dtf.float32。

正确

global_step = tf.get_variable('global_step', shape=[], dtype=tf.int32) 结果 global_step=5