tensorflow模型的save與restore,及checkpoint中讀取變量方式
創(chuàng)建一個NN
import tensorflow as tf
import numpy as np
#fake data x = np.linspace(-1, 1, 100)[:, np.newaxis] #shape(100,1) noise = np.random.normal(0, 0.1, size=x.shape) y = np.power(x, 2) + noise #shape(100,1) + noise tf_x = tf.placeholder(tf.float32, x.shape) #input x tf_y = tf.placeholder(tf.float32, y.shape) #output y l = tf.layers.dense(tf_x, 10, tf.nn.relu) #hidden layer o = tf.layers.dense(l, 1) #output layer loss = tf.losses.mean_squared_error(tf_y, o ) #compute loss train_op = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
1.使用save對模型進行保存
sess= tf.Session() sess.run(tf.global_variables_initializer()) #initialize var in graph saver = tf.train.Saver() # define a saver for saving and restoring for step in range(100): #train sess.run(train_op,{tf_x:x, tf_y:y}) saver.save(sess, 'params/params.ckpt', write_meta_graph=False) # mate_graph is not recommend
生成三個文件,分別是checkpoint,.ckpt.data-00000-of-00001,.ckpt.index
2.使用restore對提取模型
在提取模型時,需要將模型結(jié)構(gòu)再定義一遍,再將各參數(shù)加載出來
#bulid entire net again and restore tf_x = tf.placeholder(tf.float32, x.shape) tf_y = tf.placeholder(tf.float32, y.shape) l_ = tf.layers.dense(tf_x, 10, tf.nn.relu) o_ = tf.layers.dense(l_, 1) loss_ = tf.losses.mean_squared_error(tf_y, o_) sess = tf.Session() # don't need to initialize variables, just restoring trained variables saver = tf.train.Saver() # define a saver for saving and restoring saver.restore(sess, './params/params.ckpt')
3.有時會報錯Not found:b1 not found in checkpoint
這時我們想知道我在文件中到底保存了什么內(nèi)容,即需要讀取出checkpoint中的tensor
import os from tensorflow.python import pywrap_tensorflow checkpoint_path = os.path.join('params','params.ckpt') # Read data from checkpoint file reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path) var_to_shape_map = reader.get_variable_to_shape_map() # Print tensor name and value f = open('params.txt','w') for key in var_to_shape_map: # write tensors' names and values in file print(key,file=f) print(reader.get_tensor(key),file=f) f.close()
運行后生成一個params.txt文件,在其中可以看到模型的參數(shù)。
補充知識:TensorFlow按時間保存檢查點
一 實例
介紹一種更簡便地保存檢查點功能的方法——tf.train.MonitoredTrainingSession函數(shù),該函數(shù)可以直接實現(xiàn)保存及載入檢查點模型的文件。
演示使用MonitoredTrainingSession函數(shù)來自動管理檢查點文件。
二 代碼
import tensorflow as tf tf.reset_default_graph() global_step = tf.train.get_or_create_global_step() step = tf.assign_add(global_step, 1) with tf.train.MonitoredTrainingSession(checkpoint_dir='log/checkpoints',save_checkpoint_secs = 2) as sess: print(sess.run([global_step])) while not sess.should_stop(): i = sess.run( step) print( i)
三 運行結(jié)果
1 第一次運行后,會發(fā)現(xiàn)log文件夾下產(chǎn)生如下文件
2 第二次運行后,結(jié)果如下:
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Restoring parameters from log/checkpoints\model.ckpt-15147
INFO:tensorflow:Saving checkpoints for 15147 into log/checkpoints\model.ckpt.
[15147]
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
四 說明
本例是按照訓(xùn)練時間來保存的。通過指定save_checkpoint_secs參數(shù)的具體秒數(shù),來設(shè)置每訓(xùn)練多久保存一次檢查點。
可見程序自動載入檢查點是從第15147次開始運行的。
五 注意
1 如果不設(shè)置save_checkpoint_secs參數(shù),默認的保存時間是10分鐘,這種按照時間保存的模式更適合用于使用大型數(shù)據(jù)集來訓(xùn)練復(fù)雜模型的情況。
2 使用該方法,必須要定義global_step變量,否則會報錯誤。
以上這篇tensorflow模型的save與restore,及checkpoint中讀取變量方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
用map函數(shù)來完成Python并行任務(wù)的簡單示例
這篇文章主要介紹了用map函數(shù)來完成Python并行任務(wù)的簡單示例,多線程和多進程編程的問題一直都是Python中的熱點和難點,需要的朋友可以參考下2015-04-04Pandas中Series和DataFrame的索引實現(xiàn)
這篇文章主要介紹了Pandas中Series和DataFrame的索引實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06