tensorflow 只恢复变量

tensorflow restore only variables

我在 Tensorflow 中进行了一些训练,并使用保护程序保存了整个会话:

# ... define model

# add a saver
saver = tf.train.Saver()

# ... run a session
    # ....
    # save the model
    save_path = saver.save(sess,fileSaver)

它工作正常,我可以通过使用完全相同的模型并调用来成功恢复整个会话:

saver.restore(sess, importSaverPath)

现在我只想修改优化器,同时保持模型的其余部分不变(除了优化器之外,计算图保持不变):

# optimizer used before
# optimizer = tf.train.AdamOptimizer
#    (learning_rate = learningRate).minimize(costPrediction)
# the new optimizer I want to use
optimizer = tf.train.RMSPropOptimizer
    (learning_rate = learningRate, decay = 0.9, momentum = 0.1,
    epsilon = 1e-5).minimize(costPrediction)

我还想从我保存的最后一个图形状态继续训练(即,我想恢复我的变量状态并继续另一个训练算法)。我当然不能用:

saver.restore

不再,因为图表已更改。

所以我的问题是:当整个会话已保存时,有没有一种方法可以使用 saver.restore 命令仅恢复变量(或者甚至,为了以后使用,仅恢复变量的子集)?我在 API 文档和网上寻找了这样的功能,但找不到任何示例/足够详细的解释来帮助我让它工作。

可以通过将变量列表作为 var_list 参数传递给 Saver constructor. However, when you change the optimizer, additional variables may have been created (momentum accumulators, for instance) and variable associated with the previous optimizer, if any, would have been removed from the model. So simply using the old Saver object to restore will not work, especially if you had constructed it with the default constructor, which uses tf.all_variables 作为 var_list 参数的参数来恢复变量的子集。您必须在您在模型中创建的变量子集上构建 Saver 对象,然后 restore 才会起作用。请注意,这将使新优化器创建的新变量保持未初始化状态,因此您必须显式初始化它们。

您可以先从 MetaGraph protobuf 恢复原始 Saver,然后使用该保护程序安全地恢复 所有 旧变量。具体的例子可以看一下eval.py脚本:

我看到了同样的问题。灵感来自 keveman 的回答。我的解决方案是:

  1. 定义你的新图,(这里只有新的优化器相关变量与旧图不同)。

  2. 使用 tf.global_variables() 获取所有变量。这个 return 我称之为 g_vars 的 var 列表。

  3. 使用 tf.contrib.framework.get_variables_by_suffix('some variable filter') 获取所有与优化器相关的变量。过滤器可以是 RMSProp 或 RMSPRrop_*。这个函数 return 是一个变量列表,我称之为 exclude_vars。

  4. 获取g_vars中的变量,而不是exclude_vars中的变量。只需使用

    vars = [item for item in g_vars if item not in exclude_vars]

这些变量是新旧图形中的常用变量,您现在可以从旧模型中恢复它们。