1. 程式人生 > >[Tensorflow] 模型持久化

[Tensorflow] 模型持久化

模型持久化

1. 程式碼實現

呼叫API: tf.train.Saver即可
模型一般會儲存在後綴為.ckpt的檔案中.

儲存模型示例
v1 = tf.Variable(tf.random_normal([1], stddev=1, seed=1))
v2 = tf.Variable(tf.random_normal([1], stddev=1, seed=1))
result = v1 + v2

init_op = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run
(init_op) saver.save(sess, "Saved_model/model.ckpt")

實際中, Saved_model目錄下會有三個檔案:

  • model.ckpt.meta: 儲存計算圖的結構.
  • model.ckpt: 儲存Tensorflow程式中每個變數的取值.
  • checkpoint: 儲存一個目錄下所有的模型檔案列表.
[email protected]:~/Study/MNIST/TrainSaver/Saved_model$ ll
total 24
drwxr-xr-x 2 yasin yasin 4096 Mar 31 19:16 ./
drwxr-xr
-x 3 yasin yasin 4096 Mar 31 19:32 ../ -rw-r--r-- 1 yasin yasin 77 Mar 31 19:16 checkpoint -rw-r--r-- 1 yasin yasin 8 Mar 31 19:16 model.ckpt.data-00000-of-00001 -rw-r--r-- 1 yasin yasin 143 Mar 31 19:16 model.ckpt.index -rw-r--r-- 1 yasin yasin 3190 Mar 31 19:16 model.ckpt.meta
載入模型示例
import tensorflow as tf
# 載入模型的結構
saver = tf.train.import_meta_graph("Saved_model/model.ckpt.meta") with tf.Session() as sess: # 載入模型中的張量取值 saver.restore(sess, "Saved_model/model.ckpt") # 通過張量名稱來獲取張量 print sess.run(tf.get_default_graph().get_tensor_by_name("add:0"))

輸出:

[3.]