1. 新版tensorflow在訓練過程中保存模型爲ckpt格式時會產生四個文件,分別是:
2. 如果需要把ckpt文件用於測試代碼,建議固化模型參數,即轉換爲pb模型。
轉換代碼網上都有,隨便找了個可用的,如下:
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文件路徑
# 指定輸出的節點名稱,該節點名稱必須是原模型中存在的節點
output_node_names = "InceptionV3/Logits/SpatialSqueeze"
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)) #得到當前圖有幾個操作節點
# for op in graph.get_operations():
# print(op.name, op.values())
一開始轉換的時候出現了轉換出pb模型內只有一個tensor節點,經排查原因爲代碼段內的
output_node_names
沒有設置正確,因此轉換代碼無法讀到.meta文件的整個模型流程。
3. 總結:整個代碼的核心就是要找準輸出節點,建議可用tensorboard或者netron來查看模型的graph。