快速完整教程:Tensorflow 模型的保存和恢復
本Tensorflow教程中,解釋一下部分:
- I. Tensorflow模型究竟是什麼樣?
- II. 如何保存Tensorflow模型?
- III. 如何恢復Tensorflow模型用於預測或者遷移學習?
- IV. 如何使用預訓練模型以及修改?
1. 什麼是Tensorflow模型?
在你訓練好一個神經網絡後,你就想要保存它爲將來所用,發佈到產品中。那麼,什麼是Tensorflow模型呢?Tensorflow模型主要包括網絡設計或圖,和我們所訓練的網絡參數。因此,Tensorflow模型有兩個主要的文件:
- Meta graph
這是保存完整的Tensorflow graph,所有的變量,運算等,採用**.meta**擴展名。 - Checkpoint file
此二進制文件包含了所有的權重,偏移量,梯度,和其他變量。文件採用.ckpt擴展名。然而,在版本0.11後包括兩個文件:
mymodel.data-00000-of-00001
mymodel.index
此外,Tensorflow也包含最新的checkpoint文件。
2. 保存Tensorflow模型
一旦網絡收斂,你將可以停止訓練,保存所有變量和網絡圖到文件中,爲將來所用。首先,創建**tf.train.Saver()**實例。
saver = tf.train.Saver()
記住,Tensorflow變量僅僅在session內存在,所以必須在模型session內部調用方法,進行保存。
saver.save(sess, 'my-test-model')
此處,sess是一個session對象,my-test-model是想要保存的模型名字。例子如下
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, 'my_test_model')
# This will save following files in Tensorflow v >= 0.11
# my_test_model.data-00000-of-00001
# my_test_model.index
# my_test_model.meta
# checkpoint
如果我們想保存模型在1000次迭代後,我們將需要傳遞步數
saver.save(sess, 'my_test_model',global_step=1000)
模型名將會後綴-1000
my_test_model-1000.index
my_test_model-1000.meta
my_test_model-1000.data-00000-of-00001
checkpoint
雖然我們在每1000次需要保存一次,但是graph不會改變,因此,不需要保存graph每次。
saver.save(sess, 'my-model', global_step=step,write_meta_graph=False)
如果你只是想保存最新的四個模型,並且每兩個小時保存一次:
#saves a model every 2 hours and maximum 4 latest models are saved.
saver = tf.train.Saver(max_to_keep=4, keep_checkpoint_every_n_hours=2)
注意,如何我們不指定保存任何東西,將保存所有的變量。指定保存例子見:
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([w1,w2])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver.save(sess, 'my_test_model',global_step=1000)
3. 導入預訓練模型
如果想要導入已經訓練好的模型,需要以下兩步:
- 創建網絡
可以使用Python代碼創建想用的網絡。然後,如果你想的話,我們也可以根據meta文件,使用**tf.train.import() **導入,如
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
導入的網絡將會接在當前的graph後面。但是你依然需要加載訓練的參數值。
- 加載參數
實例如下:
with tf.Session() as sess:
new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')
new_saver.restore(sess, tf.train.latest_checkpoint('./'))
4. 使用恢復的模型
無論什麼使用使用Tensorflow,graph都需要輸入訓練數據,一些超參數,如學習率,全局步長等等。注意當網絡保存時,placeholders是不保存的,例子如下:
import tensorflow as tf
#Prepare to feed input, i.e. feed_dict and placeholders
w1 = tf.placeholder("float", name="w1")
w2 = tf.placeholder("float", name="w2")
b1= tf.Variable(2.0,name="bias")
feed_dict ={w1:4,w2:8}
#Define a test operation that we will restore
w3 = tf.add(w1,w2)
w4 = tf.multiply(w3,b1,name="op_to_restore")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#Create a saver object which will save all the variables
saver = tf.train.Saver()
#Run the operation by feeding input
print sess.run(w4,feed_dict)
#Prints 24 which is sum of (w1+w2)*b1
#Now, save the graph
saver.save(sess, 'my_test_model',global_step=1000)
當恢復時,不僅僅是恢復權重和graph,也需要將數據輸入到網絡中。我們可以使用 graph.get_tensor_by_name() 訪問保存的參數。
#How to access saved variable/Tensor/placeholders
w1 = graph.get_tensor_by_name("w1:0")
## How to access saved operation
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
如何想要運行相同的網絡,採用不同的數據,可以通過feed_dict輸入到網絡中。
import tensorflow as tf
sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
# Now, let's access and create placeholders variables and
# create feed-dict to feed new data
graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}
#Now, access the op that you want to run.
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
print sess.run(op_to_restore,feed_dict)
#This will print 60 which is calculated
#using new values of w1 and w2 and saved value of b1.
如果想要添加更多的運算到graph中,例子如下:
import tensorflow as tf
sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
# Now, let's access and create placeholders variables and
# create feed-dict to feed new data
graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}
#Now, access the op that you want to run.
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
#Add more to the current graph
add_on_op = tf.multiply(op_to_restore,2)
print sess.run(add_on_op,feed_dict)
#This will print 120.
如果想要恢復部分的網絡使用?
可以使用**graph.get_tensor_by_name()**後,在此基礎上建立graph。下面是一個真是的例子,採用vgg預訓練網絡,在fc7後面添加新的網絡。
......
......
saver = tf.train.import_meta_graph('vgg.meta')
# Access the graph
graph = tf.get_default_graph()
## Prepare the feed_dict for feeding data for fine-tuning
#Access the appropriate output for fine-tuning
fc7= graph.get_tensor_by_name('fc7:0')
#use this if you only want to change gradients of the last layer
fc7 = tf.stop_gradient(fc7) # It's an identity function
fc7_shape= fc7.get_shape().as_list()
new_outputs=2
weights = tf.Variable(tf.truncated_normal([fc7_shape[3], num_outputs], stddev=0.05))
biases = tf.Variable(tf.constant(0.05, shape=[num_outputs]))
output = tf.matmul(fc7, weights) + biases
pred = tf.nn.softmax(output)
# Now, you run this with fine-tuning data in sess.run()