探索学习率设置技巧以提高Keras中模型性能 | 炼丹技巧

迁移学习

1. 差分学习（Differential learning)

“差分学习率” 是指在网络的不同部分使用不同的学习率，初始层的学习率较低，后几层的学习率逐渐提高。

在Keras中实现差分学习率

``````class Adam(Optimizer):

Default parameters follow those provided in the original paper.
# Arguments
lr: float >= 0. Learning rate.
beta_1: float, 0 < beta < 1. Generally close to 1.
beta_2: float, 0 < beta < 1. Generally close to 1.
epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
decay: float >= 0. Learning rate decay over each update.
algorithm from the paper "On the Convergence of Adam and
Beyond".
"""

def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999,
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.beta_1 = K.variable(beta_1, name='beta_1')
self.beta_2 = K.variable(beta_2, name='beta_2')
self.decay = K.variable(decay, name='decay')
if epsilon is None:
epsilon = K.epsilon()
self.epsilon = epsilon
self.initial_decay = decay

lr = self.lr
if self.initial_decay > 0:
lr = lr * (1. / (1. + self.decay * K.cast(self.iterations,
K.dtype(self.decay))))

t = K.cast(self.iterations, K.floatx()) + 1
lr_t = lr * (K.sqrt(1. - K.pow(self.beta_2, t)) /
(1. - K.pow(self.beta_1, t)))

ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
vhats = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
else:
vhats = [K.zeros(1) for _ in params]
self.weights = [self.iterations] + ms + vs + vhats

for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats):
m_t = (self.beta_1 * m) + (1. - self.beta_1) * g
v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g)
vhat_t = K.maximum(vhat, v_t)
p_t = p - lr_t * m_t / (K.sqrt(vhat_t) + self.epsilon)
else:
p_t = p - lr_t * m_t / (K.sqrt(v_t) + self.epsilon)

new_p = p_t

# Apply constraints.
if getattr(p, 'constraint', None) is not None:
new_p = p.constraint(new_p)

def get_config(self):
config = {'lr': float(K.get_value(self.lr)),
'beta_1': float(K.get_value(self.beta_1)),
'beta_2': float(K.get_value(self.beta_2)),
'decay': float(K.get_value(self.decay)),
'epsilon': self.epsilon,
return dict(list(base_config.items()) + list(config.items()))
``````

• init函数被修改为包含：

1. 拆分层：split_1split_2是分别进行第一次和第二次拆分的层名称。
2. 修改参数lr以应用学习率表 - 应用3个学习率表（因为差分学习结构中分为3个不同的阶段）
• 在更新每层的学习率时，初始代码遍历所有层并为其分配学习速率。我们改变这一点，以便为不同的层设置不同的学习率。

``````class Adam_dlr(optimizers.Optimizer):

Default parameters follow those provided in the original paper.
# Arguments
split_1: split layer 1
split_2: split layer 2
lr: float >= 0. List of Learning rates. [Early layers, Middle layers, Final Layers]
beta_1: float, 0 < beta < 1. Generally close to 1.
beta_2: float, 0 < beta < 1. Generally close to 1.
epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.
decay: float >= 0. Learning rate decay over each update.
algorithm from the paper "On the Convergence of Adam and
Beyond".
"""

def __init__(self, split_1, split_2, lr=[1e-7, 1e-4, 1e-2], beta_1=0.9, beta_2=0.999,
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.beta_1 = K.variable(beta_1, name='beta_1')
self.beta_2 = K.variable(beta_2, name='beta_2')
self.decay = K.variable(decay, name='decay')
# Extracting name of the split layers
self.split_1 = split_1.weights[0].name
self.split_2 = split_2.weights[0].name
if epsilon is None:
epsilon = K.epsilon()
self.epsilon = epsilon
self.initial_decay = decay

lr = self.lr
if self.initial_decay > 0:
lr = lr * (1. / (1. + self.decay * K.cast(self.iterations,
K.dtype(self.decay))))

t = K.cast(self.iterations, K.floatx()) + 1
lr_t = lr * (K.sqrt(1. - K.pow(self.beta_2, t)) /
(1. - K.pow(self.beta_1, t)))

ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
vhats = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
else:
vhats = [K.zeros(1) for _ in params]
self.weights = [self.iterations] + ms + vs + vhats

# Setting lr of the initial layers
lr_grp = lr_t[0]
for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats):

# Updating lr when the split layer is encountered
if p.name == self.split_1:
lr_grp = lr_t[1]
if p.name == self.split_2:
lr_grp = lr_t[2]

m_t = (self.beta_1 * m) + (1. - self.beta_1) * g
v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g)
vhat_t = K.maximum(vhat, v_t)
p_t = p - lr_grp * m_t / (K.sqrt(vhat_t) + self.epsilon) # 使用更新后的学习率
else:
p_t = p - lr_grp * m_t / (K.sqrt(v_t) + self.epsilon)

new_p = p_t

# Apply constraints.
if getattr(p, 'constraint', None) is not None:
new_p = p.constraint(new_p)

def get_config(self):
#         print('Optimizer LR: ', K.get_value(self.lr))
#         print()
config = {
'lr': (K.get_value(self.lr)),
'beta_1': float(K.get_value(self.beta_1)),
'beta_2': float(K.get_value(self.beta_2)),
'decay': float(K.get_value(self.decay)),
'epsilon': self.epsilon,
return dict(list(base_config.items()) + list(config.items()))
``````

2. 具有热启动的随机梯度下降（SGDR）

SGDR是学习速率退火的最新变体，由Loshchilov＆Hutter在他们的论文“Sgdr：Stochastic Gradient Descent with Warm Restarts”中引入。在这种技术中，我们不时的进行学习率突增。下面是使用余弦退火重置三个均匀间隔的学习速率的示例。

在Keras中实现SGDR

``````class LR_Updater(Callback):
'''This callback is utilized to log learning rates every iteration (batch cycle)
it is not meant to be directly used as a callback but extended by other callbacks
ie. LR_Cycle
'''

def __init__(self, iterations):
'''
iterations = dataset size / batch size
epochs = pass through full training dataset
'''
self.epoch_iterations = iterations
self.trn_iterations = 0.
self.history = {}

def on_train_begin(self, logs={}):
self.trn_iterations = 0.
logs = logs or {}

def on_batch_end(self, batch, logs=None):
logs = logs or {}
self.trn_iterations += 1
K.set_value(self.model.optimizer.lr, self.setRate())
self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))
self.history.setdefault('iterations', []).append(self.trn_iterations)
for k, v in logs.items():
self.history.setdefault(k, []).append(v)

def plot_lr(self):
plt.xlabel("iterations")
plt.ylabel("learning rate")
plt.plot(self.history['iterations'], self.history['lr'])

def plot(self, n_skip=10):
plt.xlabel("learning rate (log scale)")
plt.ylabel("loss")
plt.plot(self.history['lr'], self.history['loss'])
plt.xscale('log')

class LR_Cycle(LR_Updater):
'''This callback is utilized to implement cyclical learning rates
it is based on this pytorch implementation https://github.com/fastai/fastai/blob/master/fastai
and adopted from this keras implementation https://github.com/bckenstler/CLR
'''

def __init__(self, iterations, cycle_mult = 1):
'''
iterations = dataset size / batch size
iterations = number of iterations in one annealing cycle
cycle_mult = used to increase the cycle length cycle_mult times after every cycle
for example: cycle_mult = 2 doubles the length of the cycle at the end of each cy\$
'''
self.min_lr = 0
self.cycle_mult = cycle_mult
self.cycle_iterations = 0.
super().__init__(iterations)

def setRate(self):
self.cycle_iterations += 1
if self.cycle_iterations == self.epoch_iterations:
self.cycle_iterations = 0.
self.epoch_iterations *= self.cycle_mult
cos_out = np.cos(np.pi*(self.cycle_iterations)/self.epoch_iterations) + 1
return self.max_lr / 2 * cos_out

def on_train_begin(self, logs={}):
super().on_train_begin(logs={}) #changed to {} to fix plots after going from 1 to mult. lr
self.cycle_iterations = 0.
self.max_lr = K.get_value(self.model.optimizer.lr)
``````

GitGub地址