轉載:https://www.jianshu.com/p/06548e3e8f4b
轉換代碼如下:
"""
此文件可以把ckpt模型轉爲pb模型
"""
import tensorflow as tf
#from create_tf_record import *
from tensorflow.python.framework import graph_util
def freeze_graph(input_checkpoint,output_graph):
'''
:param input_checkpoint:
:param output_graph: PB模型保存路徑
:return:
'''
# checkpoint = tf.train.get_checkpoint_state(model_folder) #檢查目錄下ckpt文件狀態是否可用
# input_checkpoint = checkpoint.model_checkpoint_path #得ckpt文件路徑
# 指定輸出的節點名稱,該節點名稱必須是原模型中存在的節點
# 直接用最後輸出的節點,可以在tensorboard中查找到,tensorboard只能在linux中使用
output_node_names = "inference/prediction"
saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=True)
graph = tf.get_default_graph() # 獲得默認的圖
input_graph_def = graph.as_graph_def() # 返回一個序列化的圖代表當前的圖
with tf.Session() as sess:
saver.restore(sess, input_checkpoint) #恢復圖並得到數據
output_graph_def = graph_util.convert_variables_to_constants( # 模型持久化,將變量值固定
sess=sess,
input_graph_def=input_graph_def,# 等於:sess.graph_def
output_node_names=output_node_names.split(","))# 如果有多個輸出節點,以逗號隔開
with tf.gfile.GFile(output_graph, "wb") as f: #保存模型
f.write(output_graph_def.SerializeToString()) #序列化輸出
print("%d ops in the final graph." % len(output_graph_def.node)) #得到當前圖有幾個操作節點
# input_checkpoint='inceptionv1/model.ckpt-0'
# out_pb_path='inceptionv1/frozen_model.pb'
input_checkpoint='checkpoints/textcnn/best_validation'
out_pb_path='checkpoints/frozen_model.pb'
freeze_graph(input_checkpoint, out_pb_path)
只要把四個文件夾放到imput_checkpoint文件夾下,然後改下output_node_names = "inference/prediction"引號中的最後一層的名字就行了!