2017-08-03 145 views
7

我已成功地轉換預先訓練.ckpt模型中使用這個腳本.pb(protobuf的)格式:轉換.pb文件來.ckpt(tensorflow)

import os 
import tensorflow as tf 

# Get the current directory 
dir_path = os.path.dirname(os.path.realpath(__file__)) 
print "Current directory : ", dir_path 
save_dir = dir_path + '/Protobufs' 

graph = tf.get_default_graph() 

# Create a session for running Ops on the Graph. 
sess = tf.Session() 

print("Restoring the model to the default graph ...") 
saver = tf.train.import_meta_graph(dir_path + '/model.ckpt.meta') 
saver.restore(sess,tf.train.latest_checkpoint(dir_path)) 
print("Restoring Done .. ") 

print "Saving the model to Protobuf format: ", save_dir 

#Save the model to protobuf (pb and pbtxt) file. 
tf.train.write_graph(sess.graph_def, save_dir, "Binary_Protobuf.pb", False) 
tf.train.write_graph(sess.graph_def, save_dir, "Text_Protobuf.pbtxt", True) 
print("Saving Done .. ") 

現在,我要的是副verca程序。我如何加載protobuf文件並將其轉換爲.ckpt(檢查點)格式?

我試圖做到這一點與下面的腳本,但它總是失敗:

import tensorflow as tf 
import argparse 

# Pass the filename as an argument 
parser = argparse.ArgumentParser() 
parser.add_argument("--frozen_model_filename", default="/path-to-pb-file/Binary_Protobuf.pb", type=str, help="Pb model file to import") 
args = parser.parse_args() 

    # We load the protobuf file from the disk and parse it to retrieve the 
    # unserialized graph_def 
with tf.gfile.GFile(args.frozen_model_filename, "rb") as f: 
    graph_def = tf.GraphDef() 
    graph_def.ParseFromString(f.read()) 

    #saver=tf.train.Saver() 
    with tf.Graph().as_default() as graph: 

     tf.import_graph_def(
      graph_def, 
      input_map=None, 
      return_elements=None, 
      name="prefix", 
      op_dict=None, 
      producer_op_list=None 
     ) 
     sess = tf.Session(graph=graph) 
     saver=tf.train.Saver() 
     save_path = saver.save(sess, "path-to-ckpt/model.ckpt") 
     print("Model saved to chkp format") 

我相信,這將是有這些轉換腳本非常有幫助。

P.S:權重已經嵌入到.pb文件中。

謝謝。

回答

0

看來你只能在兩個文件中獲得圖形定義,而不是凍結模型。使用freeze_graph file

+0

該模型從恢復(sess,tf.train.latest_checkpoint(dir_path))加載檢查點(與權重)的位置。 –

+0

好!在第二個腳本中,您沒有加載任何模型,只是導入了圖形。儘管您在第一個腳本中加載模型,但它不會將變量寫入到pb文件中。 –

+0

好吧我在tf.train.write_graph函數中將sess.graph_def更改爲sess.graph,但同樣的運氣。 –

0

如果您在PB文件加載模型得到

# This two lines only save the graph as proto file; it doesn't save the variables and their values. 
tf.train.write_graph(sess.graph_def, save_dir, "Binary_Protobuf.pb", False) 
tf.train.write_graph(sess.graph_def, save_dir, "Text_Protobuf.pbtxt", True) 

冷凍圖形,確實可以再培訓作爲pretrain模型。 我使用「tf.global_variables()」來獲取可以訓練的變量,但是當我加載一個pb模型時沒有任何變量返回。

tf.global_variables() 
相關問題