从预训练模型微调后丢失 TensorFlow 模型中的输出节点名称

Losing output node names in TensorFlow model after fine-tuning from pre-trained model

我按照 https://tensorflow-object-detection-api-tutorial.readthedocs.io 上的教程微调预训练模型以检测图像中的新对象。预训练模型为ssd_inception_v2_coco.

我在几千步后成功地训练和评估了模型,损失从 26 下降到 1。但是,我未能使用以下代码创建冻结模型:

#this code runs in model dir
import tensorflow as tf

#make .pb file from model at step 1000
saver = tf.train.import_meta_graph(
        './model.ckpt-1000.meta', clear_devices=True)

graph = tf.get_default_graph()
input_graph_def = graph.as_graph_def()
sess = tf.Session()
saver.restore(sess, "./model.ckpt-1000")

#node names
i=0
for n in tf.get_default_graph().as_graph_def().node:
  print(n.name,i);    
  i+=1
#end for
print("total:",i);

output_node_names=[
  "detection_boxes","detection_classes",
  "detection_scores","num_detections"
];
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,input_graph_def,output_node_names);

#save to .pb file
output_graph="./model.pb"
with tf.gfile.GFile(output_graph, "wb") as f:
  f.write(output_graph_def.SerializeToString());
#end with

sess.close();

错误是:

微调模型似乎丢失了输出节点名称。原预训练模型中有这些输出节点名(将上面代码中的checkpoint文件改成原训练模型中的):detection_boxes, detection_classes, detection_scores,以及 num_detections。输出节点名称与原始名称完全相同,这是它们的索引(来自上面的节点名称 'for' 循环):

我的问题是如何保留原始预训练模型的输出节点名称?节点名称在代码中定义,但这里没有代码,只有一些配置和文件 'train.py'.

PS。 total_loss后面有个叫summary_op的东西,不知道是不是输出(?):

为了有'image_tensor'(输入),和其他输出节点名'detection_boxes', 'detection_classes', 'detection_scores', 'num_detections ',使用 tensorflow/models/research/object_detection 中名为 'export_inference_graph.py' 的实用程序脚本。该脚本甚至优化了用于推理的冻结图(冻结模型)。正如在我的测试模型上检查的那样,节点数量从 26,000 个减少到 5,000 个;这对推理速度非常有用。

这是 link 到 export_inference_graph.py: https://github.com/tensorflow/models/blob/0558408514dacf2fe2860cd72ac56cbdf62a24c0/research/object_detection/export_inference_graph.py

如何运行:

#bash command
python3 export_inference_graph.py \
--input_type image_tensor \
--pipeline_config_path PATH_TO_PIPELINE.config \
--trained_checkpoint_prefix PATH_TO/model.ckpt-NUMBER \
--output_directory PATH_TO_NEW_DIR 

有问题的 .pb 创建代码仅适用于从头开始创建并手动定义节点名称的模型,对于从 TensorFlow Model Zoo https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md 下载的预训练模型微调的模型检查点,它行不通!