Tensorflow模型的保存與恢復

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

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

2) 如何保存tensorflow的模型?

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

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

1. Tensorflow模型是什么?

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

A)?Meta graph:

這是一個保存完整Tensorflow graph的protocol buffer,比如說,所有的?variables, operations, collections等等。這個文件的后綴是.meta

B)?Checkpoint file:

這是一個包含所有權重(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中,我們可以創(chuàng)建一個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’,下面的文件將會被創(chuàng)建:

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()中并沒有指定任何東西,因此它將保存所有變量。如果我們不想保存所有的變量,只想保存其中一些變量,我們可以在創(chuàng)建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)創(chuàng)建網絡Create the network:

?????? 你可以通過寫python代碼,來手動地創(chuàng)建每一個、每一層,使得跟原始網絡一樣。

但是,如果你仔細想的話,我們已經將模型保存在了.meta文件中,因此我們可以使用tf.train.import()函數來重新創(chuàng)建網絡,使用方法如下:

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 placeholdersw1 = 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 restorew3 = 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 variablessaver = tf.train.Saver()#Run the operation by feeding inputprint sess.run(w4,feed_dict)#Prints 24 which is sum of (w1+w2)*b1 #Now, save the graphsaver.save(sess,'my_test_model',global_step=1000)

現(xiàn)在,我們想要恢復這個網絡,我們不僅需要恢復圖(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 operationop_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 weightssaver = 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 datagraph = 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 weightssaver = 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 datagraph = 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 graphadd_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 graphgraph = tf.get_default_graph()## Prepare the feed_dict for feeding data for fine-tuning #Access the appropriate output for fine-tuningfc7= graph.get_tensor_by_name('fc7:0')#use this if you only want to change gradients of the last layerfc7 = tf.stop_gradient(fc7)# It's an identity functionfc7_shape= fc7.get_shape().as_list()

new_outputs=2weights = 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()

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容