Tensorflow:保存和恢复模型参数

Tensorflow: Saving and restoring the model parameters

我是 TensorFlow 的初学者,目前正在训练一个 CNN。

我正在使用 Saver 来保存模型使用的参数,但我担心它本身是否会存储模型使用的所有变量,并且足以将值恢复到 re-运行 程序以执行 classification/testing 在经过训练的网络上。

让我们看看TensorFlow给出的著名例子MNIST。

在示例中,我们有一堆卷积块,所有这些块都有权重,以及在程序 运行 时初始化的偏差变量。

W_conv1 = init_weight([5,5,1,32])
b_conv1 = init_bias([32])

处理好几层后,我们创建一个会话,并初始化所有添加到图中的变量。

sess = tf.Session()
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()

这里,可不可以把saver.save的代码注释掉,训练后用saver.restore(sess,file_path)代替,以恢复weight,bias等等,参数回图?这是应该的吗?

for i in range(1000):
 ...

  if i%500 == 0:
    saver.save(sess,"model%d.cpkt"%(i))

我目前正在大数据集上训练,所以终止并重新开始训练是浪费时间和资源,所以我请求有人在我开始训练之前澄清一下。

如果你只想保存一次最终结果,你可以这样做:

with tf.Session() as sess:
  for i in range(1000):
    ...


  path = saver.save(sess, "model.ckpt") # out of the loop
  print "Saved:", path

在其他程序中,您可以使用从saver.save 返回的路径加载模型以进行预测或其他操作。您可以在 https://github.com/sugyan/tensorflow-mnist.

查看一些示例

基于 and Sung Kim solution I wrote a very simple model exactly for this problem. Basically in this way you need to create an object from the same class and restore its variables from the saver. You can find an example of this solution here中的解释。