1、Tensorflow 之 saver与checkpoint
1、Tensorflow 模型文件
- checkpoint
- model.ckpt-200.data-00000-of-00001
- model.ckpt-200.index
- model.ckpt-200.meta
1.1 meta文件
model.ckpt-200.meta文件保存的是圖結構,通俗地講就是神經網絡的網絡結構。一般而言網絡結構是不會發生改變,所以可以只保存一個就行了。我們可以使用下面的代碼只在第一次保存meta文件。
saver.save(sess, 'my-model', global_step=step,write_meta_graph=False)并且還可以使用tf.train.import_meta_graph(‘model.ckpt-200.meta’)能夠導入圖結構。
1.2 data文件
model.ckpt-200.data-00000-of-00001為數據文件,保存的是網絡的權值,偏置,操作等等。
1.3 index文件
model.ckpt-200.index是一個不可變得字符串表,每一個鍵都是張量的名稱,它的值是一個序列化的BundleEntryProto。 每個BundleEntryProto描述張量的元數據:“數據”文件中的哪個文件包含張量的內容,該文件的偏移量,校驗和,一些輔助數據等等。
注意: 以前的版本中tensorflow的model只保存一個文件中。
2 保存和恢復Tensorflow模型
2.1 保存模型
tf.train.Saver 類別提供了保存和恢復模型的方法。tf.train.Saver 構造函數針對圖中所有變量或指定列表的變量將 save 和 restore op 添加到圖中。Saver 對象提供了運行這些 op 的方法,指定了寫入或讀取檢查點文件的路徑。
一般而言,如果不指定任何參數,tf.train.Saver會保存所有的參數。下面是一個簡單的例子:
import tensorflow as tf # Create some variables. v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer) v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)inc_v1 = v1.assign(v1+1) dec_v2 = v2.assign(v2-1)# Add an op to initialize the variables. init_op = tf.global_variables_initializer()# Add ops to save and restore all the variables. saver = tf.train.Saver()# Later, launch the model, initialize the variables, do some work, and save the # variables to disk. with tf.Session() as sess:sess.run(init_op)# Do some work with the model. inc_v1.op.run()dec_v2.op.run()# Save the variables to disk.save_path = saver.save(sess, "tmp/model.ckpt")print("Model saved in path: %s" % save_path) View Code最后會將v1和v2以及op都保存下來。但是如果你只想保存v1和v2,你可以這樣寫。
tf.train.Saver(V1.values()+V2.values())2.2 加載模型
模型加載需要利用Saver.restore方法。可以加載固定參數,也可以加在所有參數。
saver.restore(sess,model_path)2.3 加載模型限制
pre-trained 模型常用來做遷移學習,但是卻存在一個限制,那就是網絡的前一層必須是一致的,以vgg16為例,如果你利用前面幾層提取特征,前面幾層的網絡必須得和vgg保持一致。而后面的網絡參數是隨機初始化的。
參考文獻
[1]?https://blog.csdn.net/gzj_1101/article/details/80299610
轉載于:https://www.cnblogs.com/ai-learning-blogs/p/11530553.html
總結
以上是生活随笔為你收集整理的1、Tensorflow 之 saver与checkpoint的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IO复用解述
- 下一篇: Laravel-admin hasMan