Tensorflow 模型保存和加載


原文鏈接:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/

什么是tensorflow model

模型訓練完畢之后,你可能需要在產品上使用它。那么tensorflow model是什么?tensorflow模型主要包含網絡的結構的定義或者叫graph和訓練好的網絡結構里的參數。因此tensorflow model包含2個文件

a)Meta graph:

使用protocol buffer來保存整個tensorflow graph.例如所有的variables, operations, collections等等。這個文件使用.meta后綴

b) Checkpoint file:

二進制文件包含所有的weights,biases,gradients和其他variables的值。這個文件使用.ckpt后綴,有2個文件:

mymodel.data-00000-of-00001
mymodel.index

.data文件就是保存訓練的variables我們將要使用它。

和這些文件一起,tensorflow還有一個文件叫checkpoint用來簡單保存最近一次保存checkpoint文件的記錄。

所以,總結起來就是 tensorflow models 對於版本0.11以上看起來是這樣:

-rw-rw-r-- 1 yyai yyai 88102292  6月  8 22:36 model.ckpt-50.data-00001-of-00002
-rw-rw-r-- 1 yyai yyai     1614  6月  8 22:36 model.ckpt-50.index
-rw-rw-r-- 1 yyai yyai  2208508  6月  8 22:36 model.ckpt-50.meta
-rw-rw-r-- 1 yyai yyai      255  6月  8 22:36 checkpoint

現在我們知道一個tensorflow model的樣子,可以看怎樣保存模型。

保存模型

假設你訓練一個卷積網絡來做圖片分類。通常你可以觀察loss和accuracy值。當你觀察到網絡已經收斂,你可以手動停止訓練或者你可以等到設定的epochs值跑完。 訓練完畢以后,你希望保存所有的variables和network graph以便將來使用。如果你希望保存graph和所有parameters的值,可以使用tensorflow,來創建一個tf.train.Saver()的實例 saver = tf.train.Saver()

記住tensorflow里的variables在session才存活,所有,你需要在session里保存model,使用剛剛創建的saver對象里的save 方法。

saver.save(sees, ‘my-test-model’)

這里,sess就是session對象,’my-test-model’就是你給你的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個iteration保存一次model,可以使用save方法給他傳遞一個步長:

saver.save(sess, 'my_test_model',global_step=1000)

它將會在model名稱的后面加上’-1000’,例如下面文件:

my_test_model-1000.index
my_test_model-1000.meta
my_test_model-1000.data-00000-of-00001
checkpoint

如果,我們每1000個iteration保存一次model,但是.meta文件只在第一次創建也就是第1000個iteration並且我們不需要每次都重新創建.meta文件。我們只需每次保存model,graph不會有變化。因此,當我們不需要寫meta-graph文件時可以這樣做:

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

如果我們只是想保存4個最近的model並且當訓練2小時之后想要保存一個model,我們可以使用maxtokeep和keepcheckpointeverynhours例如:

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

注意,如果我們沒有在tr.tran.Saver()的參數里指定任何值,它將會保存所有的variables。要是我們不想保存所有variables而只想保存其中的一些改怎么辦呢。我們而已指定想要保存的variables/collections。當創建tf.train.Saver實例,我們傳遞一個想要保存的variables字典或者列表參數給它。例如:

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)

Importing 一個 pre-trained model

如果你想使用別人的pre-trained model 來 fine-tuning, 有2件事你可以需要做:

a) 創建network:

你可以寫python代碼來創建network的每一個和每一層model,然后,想想你會發現,我們已經保存了network在.metafile里,我們可以使用tf.train.import()函數來重新創建network例如:saver = tf.train.importmetagraph('mytestmodel-1000.meta')

記住,importmetagraph 附加上了.meta文件里之前定義的network到當前的graph里。所以,這樣會為你創建graph/network,但是我們還是需要在當前的graph里加載之前訓練好的paramters的值

b)加載parameters: 我們可以恢復network里的parameters,值需要調用saver里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('./‘))

然后,tensors的值 比如w1和w2就被加載了並且可以被訪問到:

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.

4 恢復models來工作

下面給出一個實際的列子,創建一個小的network 使用placeholders並且保存它,注意network被保存的時候,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)

現在,當我們想要恢復model的時候, 我們不僅需要恢復graph和weights, 還需准備新的feeddict作為訓練數據給到network.我們可以。我們可以使用graph.gettensorbyname()方法 來獲取保存的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向network輸入新數據

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來增加更多的layers然后再訓練它,你可以這樣做:

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.

你也可以只使用之前訓練好的網絡里的一部分內容。例如這里,我們加載一個vgg pre-trained network 使用meta graph並且在最后一個層改變輸出的個數為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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM