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文件保存的是圖結(jié)構(gòu),通俗地講就是神經(jīng)網(wǎng)絡(luò)的網(wǎng)絡(luò)結(jié)構(gòu)。一般而言網(wǎng)絡(luò)結(jié)構(gòu)是不會(huì)發(fā)生改變,所以可以只保存一個(gè)就行了。我們可以使用下面的代碼只在第一次保存meta文件。
saver.save(sess, 'my-model', global_step=step,write_meta_graph=False)并且還可以使用tf.train.import_meta_graph(‘model.ckpt-200.meta’)能夠?qū)雸D結(jié)構(gòu)。
1.2 data文件
model.ckpt-200.data-00000-of-00001為數(shù)據(jù)文件,保存的是網(wǎng)絡(luò)的權(quán)值,偏置,操作等等。
1.3 index文件
model.ckpt-200.index是一個(gè)不可變得字符串表,每一個(gè)鍵都是張量的名稱,它的值是一個(gè)序列化的BundleEntryProto。 每個(gè)BundleEntryProto描述張量的元數(shù)據(jù):“數(shù)據(jù)”文件中的哪個(gè)文件包含張量的內(nèi)容,該文件的偏移量,校驗(yàn)和,一些輔助數(shù)據(jù)等等。
注意: 以前的版本中tensorflow的model只保存一個(gè)文件中。
2 保存和恢復(fù)Tensorflow模型
2.1 保存模型
tf.train.Saver 類別提供了保存和恢復(fù)模型的方法。tf.train.Saver 構(gòu)造函數(shù)針對(duì)圖中所有變量或指定列表的變量將 save 和 restore op 添加到圖中。Saver 對(duì)象提供了運(yùn)行這些 op 的方法,指定了寫(xiě)入或讀取檢查點(diǎn)文件的路徑。
一般而言,如果不指定任何參數(shù),tf.train.Saver會(huì)保存所有的參數(shù)。下面是一個(gè)簡(jiǎn)單的例子:
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最后會(huì)將v1和v2以及op都保存下來(lái)。但是如果你只想保存v1和v2,你可以這樣寫(xiě)。
tf.train.Saver(V1.values()+V2.values())2.2 加載模型
模型加載需要利用Saver.restore方法。可以加載固定參數(shù),也可以加在所有參數(shù)。
saver.restore(sess,model_path)2.3 加載模型限制
pre-trained 模型常用來(lái)做遷移學(xué)習(xí),但是卻存在一個(gè)限制,那就是網(wǎng)絡(luò)的前一層必須是一致的,以vgg16為例,如果你利用前面幾層提取特征,前面幾層的網(wǎng)絡(luò)必須得和vgg保持一致。而后面的網(wǎng)絡(luò)參數(shù)是隨機(jī)初始化的。
參考文獻(xiàn)
[1]?https://blog.csdn.net/gzj_1101/article/details/80299610
轉(zhuǎn)載于:https://www.cnblogs.com/ai-learning-blogs/p/11530553.html
總結(jié)
以上是生活随笔為你收集整理的1、Tensorflow 之 saver与checkpoint的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IO复用解述
- 下一篇: Laravel-admin hasMan