轉載自:https://blog.csdn.net/huachao1001/article/details/78501928
使用tensorflow過程中,訓練結束后我們需要用到模型文件。有時候,我們可能也需要用到別人訓練好的模型,並在這個基礎上再次訓練。這時候我們需要掌握如何操作這些模型數據。
1 Tensorflow模型文件
我們在checkpoint_dir目錄下保存的文件結構如下:
|--checkpoint_dir | |--checkpoint | |--MyModel.meta | |--MyModel.data-00000-of-00001 | |--MyModel.index
1.1 meta文件
MyModel.meta文件保存的是圖結構,meta文件是pb(protocol buffer)格式文件,包含變量、op、集合等。
1.2 ckpt文件
ckpt文件是二進制文件,保存了所有的weights、biases、gradients等變量。在tensorflow 0.11之前,保存在.ckpt文件中。0.11后,通過兩個文件保存,如:
MyModel.data-00000-of-00001
MyModel.index
1.3 checkpoint文件
我們還可以看,checkpoint_dir目錄下還有checkpoint文件,該文件是個文本文件,里面記錄了保存的最新的checkpoint文件以及其它checkpoint文件列表。在inference時,可以通過修改這個文件,指定使用哪個model
2 保存Tensorflow模型
tensorflow 提供了tf.train.Saver
類來保存模型,值得注意的是,在tensorflow中,變量是存在於Session環境中,也就是說,只有在Session環境下才會存有變量值,因此,保存模型時需要傳入session:
saver = tf.train.Saver() saver.save(sess,"./checkpoint_dir/MyModel")
看一個簡單例子:
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, './checkpoint_dir/MyModel')
執行后,在checkpoint_dir目錄下創建模型文件如下:
checkpoint MyModel.data-00000-of-00001 MyModel.index MyModel.meta
另外,如果想要在1000次迭代后,再保存模型,只需設置global_step
參數即可
保存的模型文件名稱會在后面加-1000
,如下:
checkpoint MyModel-1000.data-00000-of-00001 MyModel-1000.index MyModel-1000.meta
在實際訓練中,我們可能會在每1000次迭代中保存一次模型數據,但是由於圖是不變的,沒必要每次都去保存,可以通過如下方式指定不保存圖:
saver.save(sess, './checkpoint_dir/MyModel',global_step=step,write_meta_graph=False)
另一種比較實用的是,如果你希望每2小時保存一次模型,並且只保存最近的5個模型文件:
tf.train.Saver(max_to_keep=5, keep_checkpoint_every_n_hours=2)
注意:tensorflow默認只會保存最近的5個模型文件,如果你希望保存更多,可以通過
max_to_keep
來指定
如果我們不對tf.train.Saver
指定任何參數,默認會保存所有變量。如果你不想保存所有變量,而只保存一部分變量,可以通過指定variables/collections。在創建tf.train.Saver
實例時,通過將需要保存的變量構造list或者dictionary,傳入到Saver中:
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, './checkpoint_dir/MyModel',global_step=1000)
3 導入訓練好的模型
在第1小節中我們介紹過,tensorflow將圖和變量數據分開保存為不同的文件。因此,在導入模型時,也要分為2步:構造網絡圖和加載參數
3.1 構造網絡圖
一個比較笨的方法是,手敲代碼,實現跟模型一模一樣的圖結構。其實,我們既然已經保存了圖,那就沒必要在去手寫一次圖結構代碼。
saver=tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta')
上面一行代碼,就把圖加載進來了
3.2 加載參數
僅僅有圖並沒有用,更重要的是,我們需要前面訓練好的模型參數(即weights、biases等),本文第2節提到過,變量值需要依賴於Session,因此在加載參數時,先要構造好Session:
import tensorflow as tf with tf.Session() as sess: new_saver = tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta') new_saver.restore(sess, tf.train.latest_checkpoint('./checkpoint_dir'))
此時,W1和W2加載進了圖,並且可以被訪問:
import tensorflow as tf with tf.Session() as sess: saver = tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta') saver.restore(sess,tf.train.latest_checkpoint('./checkpoint_dir')) print(sess.run('w1:0')) ##Model has been restored. Above statement will print the saved value
執行后,打印如下:
[ 0.51480412 -0.56989086]
或者:
import tensorflow as tf import numpy as np with tf.Session() as sess: # restore graph saver = tf.train.import_meta_graph('my_net/save_net.ckpt.meta') #restore ckpt saver.restore(sess, "my_net/save_net.ckpt") # check variable W and b, like weight or bias print("weights:", sess.run('weights:0')) print("biases:", sess.run('biases:0'))
4 使用恢復的模型
前面我們理解了如何保存和恢復模型,很多時候,我們希望使用一些已經訓練好的模型,如prediction、fine-tuning以及進一步訓練等。這時候,我們可能需要獲取訓練好的模型中的一些中間結果值,可以通過graph.get_tensor_by_name('w1:0')
來獲取,注意w1:0
是tensor的name。
假設我們有一個簡單的網絡模型,代碼如下:
import tensorflow as tf w1 = tf.placeholder("float", name="w1") w2 = tf.placeholder("float", name="w2") b1= tf.Variable(2.0,name="bias") #定義一個op,用於后面恢復 w3 = tf.add(w1,w2) w4 = tf.multiply(w3,b1,name="op_to_restore") sess = tf.Session() sess.run(tf.global_variables_initializer()) #創建一個Saver對象,用於保存所有變量 saver = tf.train.Saver() #通過傳入數據,執行op print(sess.run(w4,feed_dict ={w1:4,w2:8})) #打印 24.0 ==>(w1+w2)*b1 #現在保存模型 saver.save(sess, './checkpoint_dir/MyModel',global_step=1000)
接下來我們使用graph.get_tensor_by_name()
方法來操縱這個保存的模型。
import tensorflow as tf sess=tf.Session() #先加載圖和參數變量 saver = tf.train.import_meta_graph('./checkpoint_dir/MyModel-1000.meta') saver.restore(sess, tf.train.latest_checkpoint('./checkpoint_dir')) # 訪問placeholders變量,並且創建feed-dict來作為placeholders的新值 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} #接下來,訪問你想要執行的op op_to_restore = graph.get_tensor_by_name("op_to_restore:0") print(sess.run(op_to_restore,feed_dict)) #打印結果為60.0==>(13+17)*2
注意:保存模型時,只會保存變量的值,placeholder里面的值不會被保存
如果你不僅僅是用訓練好的模型,還要加入一些op,或者說加入一些layers並訓練新的模型,可以通過一個簡單例子來看如何操作:
import tensorflow as tf sess = tf.Session() # 先加載圖和變量 saver = tf.train.import_meta_graph('my_test_model-1000.meta') saver.restore(sess, tf.train.latest_checkpoint('./')) # 訪問placeholders變量,並且創建feed-dict來作為placeholders的新值 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} #接下來,訪問你想要執行的op op_to_restore = graph.get_tensor_by_name("op_to_restore:0") # 在當前圖中能夠加入op add_on_op = tf.multiply(op_to_restore, 2) print (sess.run(add_on_op, feed_dict)) # 打印120.0==>(13+17)*2*2
如果只想恢復圖的一部分,並且再加入其它的op用於fine-tuning。只需通過graph.get_tensor_by_name()
方法獲取需要的op,並且在此基礎上建立圖,看一個簡單例子,假設我們需要在訓練好的VGG網絡使用圖,並且修改最后一層,將輸出改為2,用於fine-tuning新數據:
-
......
-
......
-
saver = tf.train.import_meta_graph( 'vgg.meta')
-
# 訪問圖
-
graph = tf.get_default_graph()
-
-
#訪問用於fine-tuning的output
-
fc7= graph.get_tensor_by_name( 'fc7:0')
-
-
#如果你想修改最后一層梯度,需要如下
-
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()
-
import os
-
import re
-
import tensorflow as tf
-
from tensorflow.python import pywrap_tensorflow
-
model_exp = "20180402-114759"
-
-
def get_model_filenames(model_dir):
-
files = os.listdir(model_dir)
-
meta_files = [s for s in files if s.endswith('.meta')]
-
if len(meta_files)==0:
-
raise load_modelValueError('No meta file found in the model directory (%s)' % model_dir)
-
elif len(meta_files)>1:
-
raise ValueError('There should not be more than one meta file in the model directory (%s)' % model_dir)
-
meta_file = meta_files[ 0]
-
ckpt = tf.train.get_checkpoint_state(model_dir) # 通過checkpoint文件找到模型文件名
-
if ckpt and ckpt.model_checkpoint_path:
-
# ckpt.model_checkpoint_path表示模型存儲的位置,不需要提供模型的名字,它回去查看checkpoint文件
-
ckpt_file = os.path.basename(ckpt.model_checkpoint_path)
-
return meta_file, ckpt_file
-
-
meta_files = [s for s in files if '.ckpt' in s]
-
max_step = -1
-
for f in files:
-
step_str = re.match( r'(^model-[\w\- ]+.ckpt-(\d+))', f)
-
if step_str is not None and len(step_str.groups())>=2:
-
step = int(step_str.groups()[ 1])
-
if step > max_step:
-
max_step = step
-
ckpt_file = step_str.groups()[ 0]
-
return meta_file, ckpt_file
-
-
-
meta_file, ckpt_file = get_model_filenames(model_exp)
-
-
print( 'Metagraph file: %s' % meta_file)
-
print( 'Checkpoint file: %s' % ckpt_file)
-
reader = pywrap_tensorflow.NewCheckpointReader(os.path.join(model_exp, ckpt_file))
-
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))
-
-
with tf.Session() as sess:
-
saver = tf.train.import_meta_graph(os.path.join(model_exp, meta_file))
-
saver.restore(tf.get_default_session(),
-
os.path.join(model_exp, ckpt_file))
-
print(tf.get_default_graph().get_tensor_by_name( "Logits/weights:0"))
六、tensorflow從已經訓練好的模型中,恢復指定權重(構建新變量、網絡)並繼續訓練(finetuning)
該部分轉載自:https://blog.csdn.net/ying86615791/article/details/76215363
假如要保存或者恢復指定tensor,並且把保存的graph恢復(插入)到當前的graph中呢?
總的來說,目前我會的是兩種方法,命名都是很關鍵!
兩種方式保存模型,
1.保存所有tensor,即整張圖的所有變量,
2.只保存指定scope的變量
兩種方式恢復模型,
1.導入模型的graph,用該graph的saver來restore變量
2.在新的代碼段中寫好同樣的模型(變量名稱及scope的name要對應),用默認的graph的saver來restore指定scope的變量
兩種保存方式:
1.保存整張圖,所有變量
-
...
-
init = tf.global_variables_initializer()
-
saver = tf.train.Saver()
-
config = tf.ConfigProto()
-
config.gpu_options.allow_growth= True
-
with tf.Session(config=config) as sess:
-
sess.run(init)
-
...
-
writer.add_graph(sess.graph)
-
...
-
saved_path = saver.save(sess,saver_path)
-
...
2.保存圖中的部分變量
-
...
-
init = tf.global_variables_initializer()
-
vgg_ref_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope= 'vgg_feat_fc')#獲取指定scope的tensor
-
saver = tf.train.Saver(vgg_ref_vars) #初始化saver時,傳入一個var_list的參數
-
config = tf.ConfigProto()
-
config.gpu_options.allow_growth= True
-
with tf.Session(config=config) as sess:
-
sess.run(init)
-
...
-
writer.add_graph(sess.graph)
-
...
-
saved_path = saver.save(sess,saver_path)
-
...
兩種恢復方式:
1.導入graph來恢復
-
...
-
vgg_meta_path = params[ 'vgg_meta_path'] # 后綴是'.ckpt.meta'的文件
-
vgg_graph_weight = params[ 'vgg_graph_weight'] # 后綴是'.ckpt'的文件,里面是各個tensor的值
-
saver_vgg = tf.train.import_meta_graph(vgg_meta_path) # 導入graph到當前的默認graph中,返回導入graph的saver
-
x_vgg_feat = tf.get_collection( 'inputs_vgg')[0] #placeholder, [None, 4096],獲取輸入的placeholder
-
feat_decode = tf.get_collection( 'feat_encode')[0] #[None, 1024],獲取要使用的tensor
-
"""
-
以上兩個獲取tensor的方式也可以為:
-
graph = tf.get_default_graph()
-
centers = graph.get_tensor_by_name('loss/intra/center_loss/centers:0')
-
當然,前提是有tensor的名字
-
"""
-
...
-
init = tf.global_variables_initializer()
-
saver = tf.train.Saver() # 這個是當前新圖的saver
-
config = tf.ConfigProto()
-
config.gpu_options.allow_growth= True
-
with tf.Session(config=config) as sess:
-
sess.run(init)
-
...
-
saver_vgg.restore(sess, vgg_graph_weight) #使用導入圖的saver來恢復
-
...
2.重寫一樣的graph,然后恢復指定scope的變量
-
def re_build():#重建保存的那個graph
-
with tf.variable_scope('vgg_feat_fc'): #沒錯,這個scope要和需要恢復模型中的scope對應
-
...
-
return ...
-
-
...
-
vgg_ref_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope= 'vgg_feat_fc') # 既然有這個scope,其實第1個方法中,導入graph后,可以不用返回的vgg_saver,再新建一個指定var_list的vgg_saver就好了,恩,需要傳入一個var_list的參數
-
...
-
init = tf.global_variables_initializer()
-
saver_vgg = tf.train.Saver(vgg_ref_vars) # 這個是要恢復部分的saver
-
saver = tf.train.Saver() # 這個是當前新圖的saver
-
config = tf.ConfigProto()
-
config.gpu_options.allow_growth= True
-
with tf.Session(config=config) as sess:
-
sess.run(init)
-
...
-
saver_vgg.restore(sess, vgg_graph_weight) #使用導入圖的saver來恢復
-
...
總結一下,這里的要點就是,在restore的時候,saver要和模型對應,如果直接用當前graph的saver = tf.train.Saver(),來恢復保存模型的權重saver.restore(vgg_graph_weight),就會報錯,提示key/tensor ... not found之類的錯誤;
寫graph的時候,一定要注意寫好scope和tensor的name,合理插入variable_scope;
最方便的方式還是,用第1種方式來保存模型,這樣就不用重寫代碼段了,然后第1種方式恢復,不過為了穩妥,最好還是通過獲取var_list,指定saver的var_list,妥妥的!
最新發現,用第1種方式恢復時,要記得當前的graph和保存的模型中沒有重名的tensor,否則當前graph的tensor name可能不是那個name,可能在后面加了"_1"....-_-||
在恢復圖基礎上構建新的網絡(變量)並訓練(finetuning)
恢復模型graph和weights在上面已經說了,這里的關鍵點是怎樣只恢復原圖的權重 ,並且使optimizer只更新新構造變量(指定層、變量)。
(以下code與上面沒聯系)
-
"""1.Get input, output , saver and graph"""#從導入圖中獲取需要的東西
-
meta_path_restore = model_dir + '/model_'+model_version+'.ckpt.meta'
-
model_path_restore = model_dir + '/model_'+model_version+'.ckpt'
-
saver_restore = tf.train.import_meta_graph(meta_path_restore) #獲取導入圖的saver,便於后面恢復
-
graph_restore = tf.get_default_graph() #此時默認圖就是導入的圖
-
#從導入圖中獲取需要的tensor
-
#1. 用collection來獲取
-
input_x = tf.get_collection( 'inputs')[0]
-
input_is_training = tf.get_collection( 'is_training')[0]
-
output_feat_fused = tf.get_collection( 'feat_fused')[0]
-
#2. 用tensor的name來獲取
-
input_y = graph_restore.get_tensor_by_name( 'label_exp:0')
-
print( 'Get tensors...')
-
print( 'inputs shape: {}'.format(input_x.get_shape().as_list()))
-
print( 'input_is_training shape: {}'.format(input_is_training.get_shape().as_list()))
-
print( 'output_feat_fused shape: {}'.format(output_feat_fused.get_shape().as_list()))
-
-
-
"""2.Build new variable for fine tuning"""#構造新的variables用於后面的finetuning
-
graph_restore.clear_collection( 'feat_fused') #刪除以前的集合,假如finetuning后用新的代替原來的
-
graph_restore.clear_collection( 'prob')
-
#添加新的東西
-
if F_scale is not None and F_scale!=0:
-
print( 'F_scale is not None, value={}'.format(F_scale))
-
feat_fused = Net_normlize_scale(output_feat_fused, F_scale)
-
tf.add_to_collection( 'feat_fused',feat_fused)#重新添加到新集合
-
logits_fused = last_logits(feat_fused,input_is_training, 7) # scope name是"final_logits"
-
-
-
"""3.Get acc and loss"""#構造損失
-
with tf.variable_scope('accuracy'):
-
accuracy,prediction = ...
-
with tf.variable_scope('loss'):
-
loss = ...
-
-
"""4.Build op for fine tuning"""
-
global_step = tf.Variable( 0, trainable=False,name='global_step')
-
learning_rate = tf.train.exponential_decay(initial_lr,
-
global_step=global_step,
-
decay_steps=decay_steps,
-
staircase= True,
-
decay_rate= 0.1)
-
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
-
with tf.control_dependencies(update_ops):
-
var_list = tf.contrib.framework.get_variables( 'final_logits')#關鍵!獲取指定scope下的變量
-
train_op = tf.train.MomentumOptimizer(learning_rate=learning_rate,momentum= 0.9).minimize(loss,global_step=global_step,var_list=var_list) #只更新指定的variables
-
"""5.Begin training"""
-
init = tf.global_variables_initializer()
-
saver = tf.train.Saver()
-
config = tf.ConfigProto()
-
config.gpu_options.allow_growth= True
-
with tf.Session(config=config) as sess:
-
sess.run(init)
-
saver_restore.restore(sess, model_path_restore) #這里saver_restore對應導入圖的saver, 如果用上面新的saver的話會報錯 因為多出了一些新的變量 在保存的模型中是沒有那些權值的
-
sess.run(train_op, feed_dict)
-
.......
再說明下兩個關鍵點:
1. 如何在新圖的基礎上 只恢復 導入圖的權重 ?
用導入圖的saver: saver_restore
2. 如何只更新指定參數?
用var_list = tf.contrib.framework.get_variables(scope_name)獲取指定scope_name下的變量,
然后optimizer.minimize()時傳入指定var_list
附:如何知道tensor名字以及獲取指定變量?
1.獲取某個操作之后的輸出
用graph.get_operations()獲取所有op
比如<tf.Operation 'common_conv_xxx_net/common_conv_net/flatten/Reshape' type=Reshape>,
那么output_pool_flatten = graph_restore.get_tensor_by_name('common_conv_xxx_net/common_conv_net/flatten/Reshape:0')就是那個位置經過flatten后的輸出了
2.獲取指定的var的值
用GraphKeys獲取變量
tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)返回指定集合的變量
比如 <tf.Variable 'common_conv_xxx_net/final_logits/logits/biases:0' shape=(7,) dtype=float32_ref>
那么var_logits_biases = graph_restore.get_tensor_by_name('common_conv_xxx_net/final_logits/logits/biases:0')就是那個位置的biases了
3.獲取指定scope的collection
tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES,scope='common_conv_xxx_net.final_logits')
注意后面的scope是xxx.xxx不是xxx/xxx