TensorFlow 微调指定的op层

    利用TensorFlow进行模型finetune时,想训练指定的op,则需要根据指定的op名进行提取,然后将其配置至tf.train.AdamOptimizer函数中的var_list参数。

    部分代码如下

def _get_variables_to_train(trainable_scopes = None):
  """Returns a list of variables to train.

  Returns:
    A list of variables to train by the optimizer.
  """
  if trainable_scopes is None:
    return tf.trainable_variables()
  else:
    scopes = [scope.strip() for scope in trainable_scopes.split(',')]

  variables_to_train = []
  for scope in scopes:
    variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
    variables_to_train.extend(variables)
  return variables_to_train

output_vars = _get_variables_to_train(Config.trainable_scopes)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
    train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss, global_step=global_step, var_list=output_vars)
trainable_scopes = 'HCnet/Bottle_neck5,HCnet/Bottle_neck5_1,HCnet/Bottle_neck6_2,HCnet/Conv7'

trainable_scopes是我需要训练的op,通过函数_get_variables_to_train获取需要的op参数,然后将获取到的参数output_vars传入tf.train.AdamOptimizer中的var_list中,通过该方法即可对指定的op训练。上述过程省略了模型预加载的过程。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值