在深度学习中,迁移学习经常被使用,在大数据集上预训练的模型迁移到特定的任务,往往需要保持模型参数不变,而微调与任务相关的模型层。本文主要介绍,使用tensorflow部分更新模型参数的方法。
1. 根据Variable scope剔除需要固定参数的变量
def get_variable_via_scope(scope_lst):
vars = []
for sc in scope_lst:
sc_variable = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,scope=scope)
vars.extend(sc_variable)
return vars
trainable_vars = tf.trainable_variables()
no_change_scope = ['your_unchange_scope_name']
no_change_vars = get_variable_via_scope(no_change_scope)
for v in no_change_vars:
trainable_vars.remove(v)
grads, _ = tf.gradients(loss, trainable_vars)
optimizer = tf.train.AdamOptimizer(lr)
train_op = optimizer.apply_gradient(zip(grads, trainable_vars), global_step=global_step)
2. 使用tf.stop_gradient()函数
在建立Graph过程中使用该函数,非常简洁地避免了使用scope获取参数