tensorflow 恢复指定层与不同层指定不同学习率的方法

yipeiwu_com7年前Python基础

如下所示:

#tensorflow 中从ckpt文件中恢复指定的层或将指定的层不进行恢复:
#tensorflow 中不同的layer指定不同的学习率
 
with tf.Graph().as_default():
		#存放的是需要恢复的层参数
	 variables_to_restore = []
	 #存放的是需要训练的层参数名,这里是没恢复的需要进行重新训练,实际上恢复了的参数也可以训练
  variables_to_train = []
  for var in slim.get_model_variables():
   excluded = False
   for exclusion in fine_tune_layers:
   #比如fine tune layer中包含logits,bottleneck
    if var.op.name.startswith(exclusion):
     excluded = True
     break
   if not excluded:
    variables_to_restore.append(var)
    #print('var to restore :',var)
   else:
    variables_to_train.append(var)
    #print('var to train: ',var)
 
 
  #这里省略掉一些步骤,进入训练步骤:
  #将variables_to_train,需要训练的参数给optimizer 的compute_gradients函数
  grads = opt.compute_gradients(total_loss, variables_to_train)
  #这个函数将只计算variables_to_train中的梯度
  #然后将梯度进行应用:
  apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)
  #也可以直接调用opt.minimize(total_loss,variables_to_train)
  #minimize只是将compute_gradients与apply_gradients封装成了一个函数,实际上还是调用的这两个函数
  #如果在梯度里面不同的参数需要不同的学习率,那么可以:
 
  capped_grads_and_vars = []#[(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]
  #update_gradient_vars是需要更新的参数,使用的是全局学习率
  #对于不是update_gradient_vars的参数,将其梯度更新乘以0.0001,使用基本上不动
 	for grad in grads:
 		for update_vars in update_gradient_vars:
 			if grad[1]==update_vars:
 				capped_grads_and_vars.append((grad[0],grad[1]))
 			else:
 				capped_grads_and_vars.append((0.0001*grad[0],grad[1]))
 
 	apply_gradient_op = opt.apply_gradients(capped_grads_and_vars, global_step=global_step)
 
 	#在恢复模型时:
 
  with sess.as_default():
 
   if pretrained_model:
    print('Restoring pretrained model: %s' % pretrained_model)
    init_fn = slim.assign_from_checkpoint_fn(
    pretrained_model,
    variables_to_restore)
    init_fn(sess)
   #这样就将指定的层参数没有恢复

以上这篇tensorflow 恢复指定层与不同层指定不同学习率的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中with及contextlib的用法详解

Python中with及contextlib的用法详解

本文实例讲述了Python中with及contextlib的用法。分享给大家供大家参考,具体如下: 平常Coding过程中,经常使用到的with场景是(打开文件进行文件处理,然后隐式地执...

python 读取文件并替换字段的实例

python 读取文件并替换字段的实例

如下所示: fp = open(''test2.txt','w') #打开你要写得文件test2.txt lines = open('test1.txt').readlines()...

Django框架中方法的访问和查找

在 Django 模板中遍历复杂数据结构的关键是句点字符 (.)。 最好是用几个例子来说明一下。 比如,假设你要向模板传递一个 Python 字典。 要通过字典键访问该字典的值,可使用一...

python MySQLdb Windows下安装教程及问题解决方法

使用python访问mysql,需要一系列安装 linux下MySQLdb安装见  Python MySQLdb在Linux下的快速安装 /post/65743.htm --...

使用PyTorch实现MNIST手写体识别代码

实验环境 win10 + anaconda + jupyter notebook Pytorch1.1.0 Python3.7 gpu环境(可选) MNIST数据集介绍 MNIST 包...