[翻譯] Tensorflow模型的保存與恢復

翻譯自:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/python

 

       在這篇tensorflow教程中,我會解釋:網絡

1) Tensorflow的模型(model)長什麼樣子?session

2) 如何保存tensorflow的模型?app

3) 如何恢復一個tensorflow模型來用於預測或者遷移學習?dom

4) 如何使用預訓練好的模型(imported pretrained models)來用於fine-tuning和 modificationide

 

 

1. Tensorflow模型是什麼?

當你已經訓練好一個神經網絡以後,你想要保存它,用於之後的使用,部署到產品裏面去。因此,Tensorflow模型是什麼?Tensorflow模型主要包含網絡的設計或者圖(graph),和咱們已經訓練好的網絡參數的值。所以Tensorflow模型有兩個主要的文件:函數

A) Meta graph:學習

這是一個保存完整Tensorflow graph的protocol buffer,好比說,全部的 variables, operations, collections等等。這個文件的後綴是 .meta 。ui

B) Checkpoint file:this

這是一個包含全部權重(weights),偏置(biases),梯度(gradients)和全部其餘保存的變量(variables)的二進制文件。它包含兩個文件:

mymodel.data-00000-of-00001

mymodel.index

其中,.data文件包含了咱們的訓練變量。

另外,除了這兩個文件,Tensorflow有一個叫作checkpoint的文件,記錄着已經最新的保存的模型文件。

:Tensorflow 0.11版本之前,Checkpoint file只有一個後綴名爲.ckpt的文件。

 

       所以,總結來講,Tensorflow(版本0.10之後)模型長這個樣子:

       Tensorflow版本0.11之前,只包含如下三個文件:

inception_v1.meta

inception_v1.ckpt

checkpoint

 

       接下來講明如何保存模型。

 

2. 保存一個Tensorflow模型

當網絡訓練結束時,咱們要保存全部變量和網絡結構體到文件中。在Tensorflow中,咱們能夠建立一個tf.train.Saver() 類的實例,以下:

saver = tf.train.Saver()

 

因爲Tensorflow變量僅僅只在session中存在,所以須要調用save方法來將模型保存在一個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

 

因爲網絡的圖(graph)在訓練的時候是不會改變的,所以,咱們沒有必要每次都重複保存.meta文件,可使用以下方法:

 

saver.save(sess, 'my-model',global_step=step,write_meta_graph=False)

若是你只想要保存最新的4個模型,而且想要在訓練的時候每2個小時保存一個模型,那麼你可使用max_to_keep 和 keep_checkpoint_every_n_hours,以下所示:

 

#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)

注意到,咱們在tf.train.Saver()中並無指定任何東西,所以它將保存全部變量。若是咱們不想保存全部的變量,只想保存其中一些變量,咱們能夠在建立tf.train.Saver實例的時候,給它傳遞一個咱們想要保存的變量的list或者字典。示例以下:

 

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. 導入一個已經訓練好的模型

若是你想要使用別人已經訓練好的模型來fine-tuning,那麼你須要作兩個步驟:

A)建立網絡Create the network:

       你能夠經過寫python代碼,來手動地建立每個、每一層,使得跟原始網絡同樣。

可是,若是你仔細想的話,咱們已經將模型保存在了 .meta 文件中,所以咱們可使用tf.train.import()函數來從新建立網絡,使用方法以下:

saver = tf.train.import_meta_graph('my_test_model-1000.meta')

       注意,這僅僅是將已經定義的網絡導入到當前的graph中,可是咱們仍是須要加載網絡的參數值。

 

B)加載參數Load the parameters

       咱們能夠經過調用restore函數來恢復網絡的參數,以下:

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('./'))

在這以後,像w1和w2的tensor的值已經被恢復,而且能夠獲取到:

with tf.Session() as sess:    
    saver = tf.train.import_meta_graph('my-model-1000.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./'))
    print(sess.run('w1:0'))
##Model has been restored. Above statement will print the saved value of w1.

       上面介紹瞭如何保存和恢復一個Tensorflow模型。下面介紹一個加載任何預訓練模型的實用方法。

 

 

4. Working with restored models

下面介紹如何恢復任何一個預訓練好的模型,並使用它來預測,fine-tuning或者進一步訓練。當你使用Tensorflow時,你會定義一個圖(graph),其中,你會給這個圖喂(feed)訓練數據和一些超參數(好比說learning rate,global step等)。下面咱們使用placeholder創建一個小的網絡,而後保存該網絡。注意到,當網絡被保存時,placeholder的值並不會被保存。

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)和權重,並且也須要準備一個新的feed_dict,將新的訓練數據餵給網絡。咱們能夠經過使用graph.get_tensor_by_name()方法來得到已經保存的操做(operations)和placeholder variables。

#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增長更多的操做(operations)而後訓練它,能夠像以下那麼作:

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的一部分,而後插入一些操做用於fine-tuning?固然能夠。僅僅須要經過 by graph.get_tensor_by_name() 方法來獲取合適的operation,而後在這上面創建graph。下面是一個實際的例子,咱們使用meta graph 加載了一個預訓練好的vgg模型,而且在最後一層將輸出個數改爲2,而後用新的數據fine-tuning。

......
......
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()
相關文章
相關標籤/搜索