首页 文章

在张量流图中保存单个神经网络的权重

提问于
浏览
0

如何在张量流图中保存单个神经网络的权重,以便可以将其加载到具有相同架构的网络中的不同程序中?

我的训练代码仅需要3个其他神经网络用于训练过程 . 如果我使用 saver.save(sess, 'my-model)' ,那么我的用例似乎是正确的 .

也许这来自于我对张量流应该如何工作的误解 . 我正确地解决了这个问题吗?

1 回答

  • 2

    最好的方法是使用tensorflow变量范围 . 假设您有model_1,model_2和model_3,并且您只想保存model_1:

    首先,在训练代码中定义模型:

    with tf.variable_scope('model_1'):
        model one declaration here
        ...
    with tf.variable_scope('model_2'):
        model one declaration here
        ...
    with tf.variable_scope('model_3'):
        model one declaration here
        ...
    

    接下来,为model_1的变量定义保护程序:

    model_1_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="model_1")
    saver = tf.train.Saver(model_1_variables)
    

    训练时你可以像你提到的那样保存一个检查点:

    saver.save(sess, 'my-model')
    

    训练完成后,如果要在评估代码中恢复权重,请确保以相同的方式定义model_1和saver:

    with tf.variable_scope('model_1'):
        model one declaration here
        ...
    model_1_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="model_1")
    saver = tf.train.Saver(model_1_variables)
    sess = tf.Session()
    saver.restore(sess, 'my-model')`
    

相关问题