Skip to main content
 首页 » 编程设计

python之恢复训练好的tensorflow模型,编辑与节点关联的值,并保存

2024年08月19日29myhome

我用 tensorflow 训练了一个模型,并在训练过程中使用了批量归一化。批量归一化要求用户传递一个名为 is_training 的 bool 值,以设置模型是处于训练阶段还是测试阶段。

训练模型时,is_training设置为常量,如下所示

is_training = tf.constant(True, dtype=tf.bool, name='is_training') 

我已经保存了训练好的模型,文件包括检查点、.meta 文件、.index 文件和一个.data。我想恢复模型并使用它运行推理。 该模型无法重新训练。所以,我想恢复现有模型,将 is_training 的值设置为 False ,然后将模型保存回来。 如何编辑与该节点关联的 bool 值,并再次保存模型?

请您参考如下方法:

您可以使用 tf.train.import_meta_graph 的 input_map 参数将图形张量重新映射到更新值。

config = tf.ConfigProto(allow_soft_placement=True) 
with tf.Session(config=config) as sess: 
    # define the new is_training tensor 
    is_training = tf.constant(False, dtype=tf.bool, name='is_training') 
 
    # now import the graph using the .meta file of the checkpoint 
    saver = tf.train.import_meta_graph( 
    '/path/to/model.meta', input_map={'is_training:0':is_training}) 
 
    # restore all weights using the model checkpoint  
    saver.restore(sess, '/path/to/model') 
 
    # save updated graph and variables values 
    saver.save(sess, '/path/to/new-model-name')