tensorflow 保存訓練模型ckpt 查看ckpt文件中的變量名和對應值


 

TensorFlow 模型保存與恢復

 

一個快速完整的教程,以保存和恢復Tensorflow模型。

在本教程中,我將會解釋:

  1. TensorFlow模型是什么樣的?
  2. 如何保存TensorFlow模型?
  3. 如何恢復預測/轉移學習的TensorFlow模型?
  4. 如何使用導入的預先訓練的模型進行微調和修改?

這個教程假設你已經對神經網絡有了一定的了解。如果不了解的話請查閱相關資料。

1. 什么是TensorFlow模型?

訓練了一個神經網絡之后,我們希望保存它以便將來使用。那么什么是TensorFlow模型?Tensorflow模型主要包含我們所培訓的網絡參數的網絡設計或圖形和值。因此,Tensorflow模型有兩個主要的文件:

a) Meta graph:
     這是一個協議緩沖區,它保存了完整的Tensorflow圖形;即所有變量、操作、集合等。該文件以.meta作為擴展名。

b) Checkpoint file:

    這是一個二進制文件,它包含了所有的權重、偏差、梯度和其他所有變量的值。這個文件有一個擴展名.ckpt。然而,Tensorflow從0.11版本中改變了這一點。現在,我們有兩個文件,而不是單個.ckpt文件:

[python]  view plain  copy
 
  1. mymodel.data-00000-of-00001  
  2. mymodel.index  

 

.data文件是包含我們訓練變量的文件,我們待會將會使用它。

與此同時,Tensorflow也有一個名為checkpoint的文件,它只保存的最新保存的checkpoint文件的記錄。

因此,為了總結,對於大於0.10的版本,Tensorflow模型如下:

在0.11之前的Tensorflow模型僅包含三個文件:

[python]  view plain  copy
 
  1. inception_v1.meta  
  2. inception_v1.ckpt  
  3. checkpoint  

 

現在我們已經知道了Tensorflow模型的樣子,接下來我們來看看TensorFlow是如何保存模型的。

2. 保存TensorFlow模型

比方說,你正在訓練一個卷積神經網絡來進行圖像分類。作為一種標准的練習,你要時刻關注損失和准確率。一旦看到網絡已經收斂,我們可以暫停模型的訓練。在完成培訓之后,我們希望將所有的變量和網絡結構保存到一個文件中,以便將來使用。因此,在Tensorflow中,我們希望保存所有參數的圖和值,我們將創建一個tf.train.Saver()類的實例。

[python]  view plain  copy
  1. saver = tf.train.Saver()  

請記住,Tensorflow變量僅在會話中存在。因此,您必須在一個會話中保存模型,調用您剛剛創建的save方法。

[python]  view plain  copy
  1. saver.save(sess, 'my-test-model')  

這里,sess是會話對象,而'my-test-model'是保存的模型的名稱。讓我們來看一個完整的例子:

[python]  view plain  copy
  1. import tensorflow as tf  
  2. w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')  
  3. w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')  
  4. saver = tf.train.Saver()  
  5. sess = tf.Session()  
  6. sess.run(tf.global_variables_initializer())  
  7. saver.save(sess, 'my_test_model')  
  8.    
  9. # This will save following files in Tensorflow v >= 0.11  
  10. # my_test_model.data-00000-of-00001  
  11. # my_test_model.index  
  12. # my_test_model.meta  
  13. # checkpoint  

如果我們在1000次迭代之后保存模型,我們將通過通過global_step來調用save:

[python]  view plain  copy
  1. saver.save(sess, 'my_test_model',global_step=1000)  

這將會將'-1000'追加到模型名稱,並創建以下文件:

[python]  view plain  copy
  1. my_test_model-1000.index  
  2. my_test_model-1000.meta  
  3. my_test_model-1000.data-00000-of-00001  
  4. checkpoint  

比方說,在訓練時,我們在每次1000次迭代后都保存模型,所以.meta文件是第一次創建的(在第1000次迭代中),我們不需要每次都重新創建.meta文件(我們在2000,3000次沒有保存.meta文件)。我們僅為進一步的迭代保存模型,因為圖不會改變。因此,當我們不想保存meta-graph時,我們用這個:

[python]  view plain  copy
  1. saver.save(sess, 'my-model', global_step=step,write_meta_graph=False)  

如果你希望僅保留4個最新的模型,並且希望在訓練過程中每兩個小時后保存一個模型,那么你可以使用max_to_keep和keep_checkpoint_every_n_hours這樣做。

[python]  view plain  copy
  1. #saves a model every 2 hours and maximum 4 latest models are saved.  
  2. saver = tf.train.Saver(max_to_keep=4, keep_checkpoint_every_n_hours=2)  

注意,如果我們在tf.train.Saver()中沒有指定任何東西,它將保存所有的變量。如果,我們不想保存所有的變量,而只是一些變量。我們可以指定要保存的變量/集合。在創建tf.train。保護程序實例,我們將它傳遞給我們想要保存的變量的列表或字典。讓我們來看一個例子:

[python]  view plain  copy
  1. import tensorflow as tf  
  2. w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')  
  3. w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')  
  4. saver = tf.train.Saver([w1,w2])  
  5. sess = tf.Session()  
  6. sess.run(tf.global_variables_initializer())  
  7. saver.save(sess, 'my_test_model',global_step=1000)  

這可以用於在需要時保存特定的Tensorflow圖。

3. 導入訓練好的模型

如果你想用別人預先訓練好的模型來進行微調,你需要做以下兩件事:

 

a)創建網絡

你可以通過編寫python代碼創建網絡,以手工創建每一層,並將其作為原始模型。但是,如果你考慮一下,我們已經在.meta文件中保存了這個網絡,我們可以使用tf.train.import()函數來重新創建這個網絡:

[python]  view plain  copy
  1. saver = tf.train.import_meta_graph('my_test_model-1000.meta')  

記住,import_meta_graph將在.meta文件中定義的網絡附加到當前圖。因此,這將為你創建圖形/網絡,但是我們仍然需要加載我們在這張圖上訓練過的參數的值。

b)載入參數

我們可以通過調用這個保護程序的實例來恢復網絡的參數,它是tf.train.Saver()類的一個實例。

[python]  view plain  copy
  1. with tf.Session() as sess:  
  2. new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')  
  3. new_saver.restore(sess, tf.train.latest_checkpoint('./'))  

在此之后,像w1和w2這樣的張量的值已經恢復並且可以被訪問:

[python]  view plain  copy
  1. with tf.Session() as sess:      
  2.     saver = tf.train.import_meta_graph('my-model-1000.meta')  
  3.     saver.restore(sess,tf.train.latest_checkpoint('./'))  
  4.     print(sess.run('w1:0'))  
  5. ##Model has been restored. Above statement will print the saved value of w1  

因此,現在你已經了解了如何為Tensorflow模型保存和導入工作。在下一節中,我描述了上面的實際使用,以加載任何預先訓練過的模型。

4.使用導入的模型

現在你已經了解了如何保存和恢復Tensorflow模型,讓我們開發一個實用的例子來恢復任何預先訓練的模型,並使用它進行預測、微調或進一步訓練。當您使用Tensorflow時,你將定義一個圖,該圖是feed examples(訓練數據)和一些超參數(如學習速率、迭代次數等),它是一個標准的過程,我們可以使用占位符來存放所有的訓練數據和超參數。接下來,讓我們使用占位符構建一個小網絡並保存它。注意,當網絡被保存時,占位符的值不會被保存。

[python]  view plain  copy
 
  1. import tensorflow as tf  
  2.    
  3. #Prepare to feed input, i.e. feed_dict and placeholders  
  4. w1 = tf.placeholder("float", name="w1")  
  5. w2 = tf.placeholder("float", name="w2")  
  6. b1= tf.Variable(2.0,name="bias")  
  7. feed_dict ={w1:4,w2:8}  
  8.    
  9. #Define a test operation that we will restore  
  10. w3 = tf.add(w1,w2)  
  11. w4 = tf.multiply(w3,b1,name="op_to_restore")  
  12. sess = tf.Session()  
  13. sess.run(tf.global_variables_initializer())  
  14.    
  15. #Create a saver object which will save all the variables  
  16. saver = tf.train.Saver()  
  17.    
  18. #Run the operation by feeding input  
  19. print sess.run(w4,feed_dict)  
  20. #Prints 24 which is sum of (w1+w2)*b1   
  21.    
  22. #Now, save the graph  
  23. saver.save(sess, 'my_test_model',global_step=1000)  

現在,當我們想要恢復它時,我們不僅要恢復圖和權重,還要准備一個新的feed_dict,它將把新的訓練數據輸入到網絡中。我們可以通過graph.get_tensor_by_name()方法來引用這些保存的操作和占位符變量。

[python]  view plain  copy
 
  1. #How to access saved variable/Tensor/placeholders   
  2. w1 = graph.get_tensor_by_name("w1:0")  
  3.    
  4. ## How to access saved operation  
  5. op_to_restore = graph.get_tensor_by_name("op_to_restore:0")  

如果我們只是想用不同的數據運行相同的網絡,您可以簡單地通過feed_dict將新數據傳遞給網絡。

[python]  view plain  copy
  1. import tensorflow as tf  
  2.    
  3. sess=tf.Session()      
  4. #First let's load meta graph and restore weights  
  5. saver = tf.train.import_meta_graph('my_test_model-1000.meta')  
  6. saver.restore(sess,tf.train.latest_checkpoint('./'))  
  7.    
  8.    
  9. # Now, let's access and create placeholders variables and  
  10. # create feed-dict to feed new data  
  11.    
  12. graph = tf.get_default_graph()  
  13. w1 = graph.get_tensor_by_name("w1:0")  
  14. w2 = graph.get_tensor_by_name("w2:0")  
  15. feed_dict ={w1:13.0,w2:17.0}  
  16.    
  17. #Now, access the op that you want to run.   
  18. op_to_restore = graph.get_tensor_by_name("op_to_restore:0")  
  19.    
  20. print sess.run(op_to_restore,feed_dict)  
  21. #This will print 60 which is calculated   
  22. #using new values of w1 and w2 and saved value of b1.   

如果你希望通過添加更多的層數並對其進行訓練,從而向圖中添加更多的操作,可以這樣做

[python]  view plain  copy
  1. import tensorflow as tf  
  2.    
  3. sess=tf.Session()      
  4. #First let's load meta graph and restore weights  
  5. saver = tf.train.import_meta_graph('my_test_model-1000.meta')  
  6. saver.restore(sess,tf.train.latest_checkpoint('./'))  
  7.    
  8.    
  9. # Now, let's access and create placeholders variables and  
  10. # create feed-dict to feed new data  
  11.    
  12. graph = tf.get_default_graph()  
  13. w1 = graph.get_tensor_by_name("w1:0")  
  14. w2 = graph.get_tensor_by_name("w2:0")  
  15. feed_dict ={w1:13.0,w2:17.0}  
  16.    
  17. #Now, access the op that you want to run.   
  18. op_to_restore = graph.get_tensor_by_name("op_to_restore:0")  
  19.    
  20. #Add more to the current graph  
  21. add_on_op = tf.multiply(op_to_restore,2)  
  22.    
  23. print sess.run(add_on_op,feed_dict)  
  24. #This will print 120.  

但是,你是否可以在之前圖的結構上構建新的網絡?當然,您可以通過graph.get_tensor_by_name()方法訪問適當的操作,並在此基礎上構建圖。這是一個真實的例子。在這里,我們使用元圖加載一個vgg預訓練的網絡,並在最后一層中將輸出的數量更改為2,以便對新數據進行微調。

[python]  view plain  copy
  1. ......  
  2. ......  
  3. saver = tf.train.import_meta_graph('vgg.meta')  
  4. # Access the graph  
  5. graph = tf.get_default_graph()  
  6. ## Prepare the feed_dict for feeding data for fine-tuning   
  7.    
  8. #Access the appropriate output for fine-tuning  
  9. fc7= graph.get_tensor_by_name('fc7:0')  
  10.    
  11. #use this if you only want to change gradients of the last layer  
  12. fc7 = tf.stop_gradient(fc7) # It's an identity function  
  13. fc7_shape= fc7.get_shape().as_list()  
  14.    
  15. new_outputs=2  
  16. weights = tf.Variable(tf.truncated_normal([fc7_shape[3], num_outputs], stddev=0.05))  
  17. biases = tf.Variable(tf.constant(0.05, shape=[num_outputs]))  
  18. output = tf.matmul(fc7, weights) + biases  
  19. pred = tf.nn.softmax(output)  
  20.    
  21. # Now, you run this with fine-tuning data in sess.run()  

希望這能讓你清楚地了解如何保存和恢復Tensorflow模型。

 

 

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

 

#http://blog.csdn.net/u011961856/article/details/77064631
#coding:utf-8
#tensorflow模型保存文件分析
import tensorflow as tf
import os
from tensorflow.python import pywrap_tensorflow

#保存model
v1= tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="v1")
v2= tf.Variable(tf.zeros([200]), name="v2")
v3= tf.Variable(tf.zeros([100]), name="v3")
saver = tf.train.Saver()
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    #saver.save(sess,"model.ckpt",global_step=1)
    saver.save(sess,"model.ckpt")

#恢復model
with tf.Session() as sess:
    saver.restore(sess, "model.ckpt")

#http://blog.csdn.net/u010698086/article/details/77916532
#顯示打印模型的信息
model_dir = "./"
checkpoint_path = os.path.join(model_dir, "model.ckpt")
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in var_to_shape_map:
    print("tensor_name: ", key)
    print(reader.get_tensor(key)) # Remove this is you want to print only variable names

 

('tensor_name: ', 'v1')
[[ 0.24313833 -0.00510722 -1.08679211 ..., -0.29464433  0.42220956
  -0.01746739]
 [ 0.16223565  0.19589604 -0.52801794 ...,  0.02914025 -0.01362503
  -0.38463125]
 [-0.31530145 -0.06385491  0.36014584 ..., -0.30602348 -0.17168237
  -0.15268792]
 ...,
 [ 0.35836434  0.49244356  0.50476414 ..., -0.53239399  0.05421086
   0.42910808]
 [ 0.07030667  0.90515828 -0.82259291 ..., -0.27345827  0.52107555
   0.54054832]
 [ 0.10563121 -0.03250603  0.30385104 ...,  0.07129911 -0.39154643
   0.41374397]]
('tensor_name: ', 'v2')
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.]
('tensor_name: ', 'v3')
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

 

從多個訓練模型中找到最近訓練保存的模型 tf.train.latest_checkpoint

    model_path = "checkpoint"
    if not model_path.endswith('/'):
        model_path += '/' chkpt_fname = tf.train.latest_checkpoint(model_path) print("model_name " +  chkpt_fname)

    with tf.Session() as sess:
        #saver.restore(sess, 'checkpoint/20000.ckpt')
        saver.restore(sess, chkpt_fname)

 




免責聲明!

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



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