TL;DR
作为张量流变量(将在会话中评估)
global_step = tf.train.get_or_create_global_step()
# use global_step variable to calculate your hyperparameter
# this variable will be evaluated later in the session
saver = tf.train.Saver()
with tf.Session() as sess:
# restore all variables from checkpoint
saver.restore(sess, checkpoint_path)
# than init table and local variables and start training/evaluation ...
或者:作为 numpy 整数(没有任何会话):
reader = tf.train.NewCheckpointReader(absolute_checkpoint_path)
global_step = reader.get_tensor('global_step')
长答案
至少有两种方法可以从检查点检索全局。作为 tensorflow 变量或 numpy 整数。如果global_step 没有在Saver 的save 方法中作为参数提供,则无法解析文件名。对于预训练模型,请参阅答案末尾的备注。
作为 TensorFlow 变量
如果您需要global_step 变量来计算一些超参数,您可以使用tf.train.get_or_create_global_step()。这将返回一个张量流变量。因为该变量将在会话稍后进行评估,所以您只能使用 tensorflow 操作来计算您的超参数。所以例如:max(global_step, 100) 将不起作用。您必须使用等效于 tensorflow 的 tf.maximum(global_step, 100),可以在会话稍后进行评估。
在会话中,您可以使用saver.restore(sess, checkpoint_path) 使用检查点初始化全局步骤变量
global_step = tf.train.get_or_create_global_step()
# use global_step variable to calculate your hyperparameter
# this variable will be evaluated later in the session
hyper_parameter = tf.maximum(global_step, 100)
saver = tf.train.Saver()
with tf.Session() as sess:
# restore all variables from checkpoint
saver.restore(sess, checkpoint_path)
# than init table and local variables and start training/evaluation ...
# for verification you can print the global step and your hyper parameter
print(sess.run([global_step, hyper_parameter]))
或者:作为 numpy 整数(无会话)
如果您需要全局 step 变量作为标量而不启动会话,您也可以直接从检查点文件中读取此变量。你只需要一个NewCheckpointReader。由于旧 tensorflow 版本中有 bug,您应该将检查点文件的路径转换为绝对路径。使用阅读器,您可以将模型的所有张量作为 numpy 变量。
全局步骤变量的名称是一个常量字符串tf.GraphKeys.GLOBAL_STEP,定义为'global_step'。
absolute_checkpoint_path = os.path.abspath(checkpoint_path)
reader = tf.train.NewCheckpointReader(absolute_checkpoint_path)
global_step = reader.get_tensor(tf.GraphKeys.GLOBAL_STEP)
对预训练模型的说明:在大多数在线可用的预训练模型中,全局步长重置为零。因此,这些模型可用于初始化模型参数以进行微调,而不会覆盖全局步骤。