Tensorflow筆記系列:
1. Tensorflow模型文件
我們在checkpoint_dir目錄下保存的文件結構如下:
|--checkpoint_dir
| |--checkpoint
| |--MyModel.meta
| |--MyModel.data-00000-of-00001
| |--MyModel.index
1.1 meta文件
MyModel.meta文件保存的是圖結構,meta文件是pb(protocol buffer)格式文件,包含變量、op、集合等。
1.2 ckpt文件
ckpt文件是二進制文件,保存了所有的weights、biases、gradients等變量。在tensorflow 0.11之前,保存在.ckpt文件中。0.11後,通過兩個文件保存,如:
MyModel.data-00000-of-00001
MyModel.index
1.3 checkpoint文件
我們還可以看,checkpoint_dir目錄下還有checkpoint文件,該文件是個文本文件,裏面記錄了保存的最新的checkpoint文件以及其它checkpoint文件列表。在inference時,可以通過修改這個文件,指定使用哪個model
2 保存Tensorflow模型
tensorflow 提供了tf.train.Saver類來保存模型,值得注意的是,在tensorflow中,變量是存在於Session環境中,也就是說,只有在Session環境下才會存有變量值,因此,保存模型時需要傳入session:
saver = tf.train.Saver()
saver.save(sess,"./checkpoint_dir/MyModel")
看一個簡單例子:
import tensorflow as tf
w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')
w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver.save(sess, './checkpoint_dir/MyModel')
執行後,在checkpoint_dir目錄下創建模型文件如下:
checkpoint
MyModel.data-00000-of-00001
MyModel.index
MyModel.meta
另外,如果想要在1000次迭代後,再保存模型,只需設置global_step參數即可
保存的模型文件名稱會在後面加-1000,如下:
checkpoint
MyModel-1000.data-00000-of-00001
MyModel-1000.index
MyModel-1000.meta
3 導入訓練好的模型
在第1小節中我們介紹過,tensorflow將圖和變量數據分開保存爲不同的文件。因此,在導入模型時,也要分爲2步:構造網絡圖和加載參數
3.1 構造網絡圖
一個比較笨的方法是,手敲代碼,實現跟模型一模一樣的圖結構。其實,我們既然已經保存了圖,那就沒必要在去手寫一次圖結構代碼。
saver=tf.train.import_meta_graph(’./checkpoint_dir/MyModel-1000.meta’)
上面一行代碼,就把圖加載進來了
3.2 加載參數
僅僅有圖並沒有用,更重要的是,我們需要前面訓練好的模型參數(即weights、biases等),本文第2節提到過,變量值需要依賴於Session,因此在加載參數時,先要構造好Session:
import tensorflow as tf
with tf.Session() as sess:
new_saver = tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta')
new_saver.restore(sess, tf.train.latest_checkpoint('./checkpoint_dir'))
此時,W1和W2加載進了圖,並且可以被訪問:
import tensorflow as tf
with tf.Session() as sess:
saver = tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./checkpoint_dir'))
print(sess.run('w1:0'))
##Model has been restored. Above statement will print the saved value
執行後,打印如下:
[ 0.51480412 -0.56989086]