tensorflow从已经训练好的模型中,恢复(指定)权重(构建新变量、网络)并继续训练(finetuning)
2017-07-27 18:18
726 查看
之前已经写了一篇《Tensorflow保存模型,恢复模型,使用训练好的模型进行预测和提取中间输出(特征)》,里面主要讲恢复模型然后使用该模型
假如要保存或者恢复指定tensor,并且把保存的graph恢复(插入)到当前的graph中呢?
总的来说,目前我会的是两种方法,命名都是很关键!
两种方式保存模型,
1.保存所有tensor,即整张图的所有变量,
2.只保存指定scope的变量
两种方式恢复模型,
1.导入模型的graph,用该graph的saver来restore变量
2.在新的代码段中写好同样的模型(变量名称及scope的name要对应),用默认的graph的saver来restore指定scope的变量
两种保存方式:
1.保存整张图,所有变量
2.保存图中的部分变量
两种恢复方式:
1.导入graph来恢复
2.重写一样的graph,然后恢复指定scope的变量
总结一下,这里的要点就是,在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)(2017.11.9更新)
恢复模型graph和weights在上面已经说了,这里的关键点是怎样只恢复原图的权重 ,并且使optimizer只更新新构造变量(指定层、变量)。
(以下code与上面没联系)
再说明下两个关键点:
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
假如要保存或者恢复指定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)(2017.11.9更新)
恢复模型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
相关文章推荐
- 【神经网络与深度学习】Caffe使用step by step:使用自己数据对已经训练好的模型进行finetuning
- TensorFlow 训练好模型参数的保存和恢复代码
- TensorFlow下构建高性能神经网络模型的最佳实践
- 使用Tensorflow训练神经网络模型---自定义损失函数
- tensorflow 保存训练模型ckpt 查看ckpt文件中的变量名和对应值
- 深入浅出Tensorflow(三):训练神经网络模型的常用方法
- tensorflow将训练好的模型freeze,即将权重固化到图里面,并使用该模型进行预测
- TensorFlow 深度学习框架(7)-- 变量管理及训练模型的保存与加载
- tensorflow将训练好的模型freeze,即将权重固化到图里面,并使用该模型进行预测
- tensorflow之inception_v3模型的部分加载及权重的部分恢复(23)---《深度学习》
- TensorFlow下构建高性能神经网络模型的最佳实践
- TensorFlow中对训练后的神经网络参数(权重、偏置)提取
- 利用TensorFlow训练简单的二分类神经网络模型
- 深入浅出Tensorflow(三):训练神经网络模型的常用方法
- TensorFlow 深度学习框架(7)-- 变量管理及训练模型的保存与加载
- Tensorflow学习笔记:模型训练数据的保存和恢复的简单实例
- 【深度学习】笔记7: CNN训练Cifar-10技巧 ---如何进行实验,如何进行构建自己的网络模型,提高精度
- 如何用Tensorflow训练模型成pb文件和和如何加载已经训练好的模型文件
- tensorflow构建网络模型
- TensorFlow 深度学习框架(7)-- 变量管理及训练模型的保存与加载