【问题标题】:Tensorflow use weights of a trained model to resume training [duplicate]Tensorflow使用训练模型的权重来恢复训练[重复]
【发布时间】:2018-07-28 00:48:21
【问题描述】:

我想在 tensorflow 中训练一个模型,然后导出训练后的权重(和偏差),并使用它们在具有不同较小学习率的新图中恢复训练。我不需要保存或使用之前训练的模型的架构(我将再次定义模型架构)。我需要的只是将新的权重初始化为等于训练的权重。有没有一种简单的方法可以做到这一点?谢谢。

为了恢复和重用权重,我使用了以下代码,但没有成功:

tf.reset_default_graph()
sess = tf.Session()
new_saver = tf.train.import_meta_graph("model20256.meta") 
new_saver.restore(sess, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()

#Import trained weights as tensors
W1__ = graph.get_tensor_by_name('W1:0')
b1__ = graph.get_tensor_by_name('b1:0')
W2__ = graph.get_tensor_by_name('W2:0')
b2__ = graph.get_tensor_by_name('b2:0')

#Create new weight variables initialized by the trained weights    
W1_=tf.Variable(W1__)
W2_=tf.Variable(W2__)
b1_=tf.Variable(b1__)
b2_=tf.Variable(b2__)


sess_ = tf.Session()
sess_.run(tf.global_variables_initializer())

#Define a new graph
g = tf.Graph()
with g.as_default():
    #Copy variables to the new graph
    W1=tf.contrib.copy_graph.copy_variable_to_graph(W1_,g)
    W2=tf.contrib.copy_graph.copy_variable_to_graph(W2_,g)
    b1=tf.contrib.copy_graph.copy_variable_to_graph(b1_,g)
    b2=tf.contrib.copy_graph.copy_variable_to_graph(b2_,g)

【问题讨论】:

  • 你能给出一些代码来展示你到目前为止所做的尝试吗?
  • 好的,刚刚添加了一些代码。

标签: python tensorflow


【解决方案1】:

在您的会话中,将 sess_.run(tf.global_variables_initializer()) 替换为 new_saver.restore(sess, tf.train.latest_checkpoint('./'))

【讨论】:

    猜你喜欢
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多