【问题标题】:Retrain model in Tensorflow在 TensorFlow 中重新训练模型
【发布时间】:2017-02-14 10:54:37
【问题描述】:

我有一个使用 Tensorflow 的简单神经网络。 这是会议:

with tensorFlow.Session() as sess:
  sess.run(tensorFlow.global_variables_initializer())
  for epoch in range(epochs):
    i = 0
    epochLoss = 0
    for _ in range(int(len(data) / batchSize)):
      ex, ey = nextBatch(i)
      i += 1
      feedDict = {x :ex, y:ey }
      _, cos = sess.run([optimizer,cost], feed_dict= feedDict) 
      epochLoss += cos / (int(len(data)) / batchSize)
    print("Epoch", epoch + 1, "completed out of", epochs, "loss:", "{:.9f}".format(epochLoss))

  save_path = saver.save(sess, "model.ckpt")
  print("Model saved in file: %s" % save_path)

在最后两行我保存了模型并在另一个类中恢复了图形:

with new_graph.as_default():
    with tf.Session(graph=new_graph) as sess:
        sess.run(tf.global_variables_initializer())
        new_saver = tf.train.import_meta_graph('model.ckpt.meta')
        new_saver.restore(sess, tf.train.latest_checkpoint('./'))

我想重新训练模型,这意味着不初始化权重,只是从它停止的最后一点更新它们。

我该怎么做?

【问题讨论】:

  • 这个问题其实是关于保存和恢复模型的。

标签: python machine-learning tensorflow prediction


【解决方案1】:

来自https://www.tensorflow.org/api_docs/python/state_ops/saving_and_restoring_variables

tf.train.Saver.restore(sess, save_path)

恢复以前保存的变量。

此方法运行构造函数添加的用于恢复的操作 变量。它需要一个启动图表的会话。 该 要恢复的变量不必被初始化,因为 恢复本身就是一种初始化变量的方法。

以下示例来自https://www.tensorflow.org/how_tos/variables/

# Create some variables.
v1 = tf.Variable(..., name="v1")
v2 = tf.Variable(..., name="v2")
...
# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
  # Restore variables from disk.
  saver.restore(sess, "/tmp/model.ckpt")
  print("Model restored.")
  # Do some work with the model
  ...

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
相关资源
最近更新 更多