我正在尝试使用基于keras.optimizers.Optimiers的优化器类。当我试图定义学习率时。它返回错误消息,提示无法设置属性。
该属性看起来像是版本或名称问题,但我不知道它是什么。希望有人能帮忙。
class AccumOptimizer(keras.optimizers.Optimizer):
def __init__(self, optimizer, steps_per_update=1, **kwargs):
super(AccumOptimizer, self).__init__(**kwargs)
self.optimizer = optimizer
with K.name_scope(self.__class__.__name__):
self.steps_per_update = steps_per_update
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.cond = K.equal(self.iterations % self.steps_per_update, 0)
self.lr = self.optimizer.lr
self.optimizer.lr = K.switch(self.cond, self.optimizer.lr, 0.)
for attr in ['momentum', 'rho', 'beta_1', 'beta_2']:
if hasattr(self.optimizer, attr):
value = getattr(self.optimizer, attr)
setattr(self, attr, value)
setattr(self.optimizer, attr, K.switch(self.cond, value, 1 - 1e-7))
for attr in self.optimizer.get_config():
if not hasattr(self, attr):
value = getattr(self.optimizer, attr)
setattr(self, attr, value)
但是当我尝试将其编译到模型中时,出现以下错误:
2 model.compile(optimizer=AccumOptimizer(Adam(2e-3), 4), loss=bce_dice_loss, metrics=[dice_coef])
3 #model.compile(optimizer=Adam(), loss=bce_dice_loss, metrics=[dice_coef])
4 model.summary()
<ipython-input-46-066c2d3c22de> in __init__(self, optimizer, steps_per_update, **kwargs)
24 self.iterations = K.variable(0, dtype='int64', name='iterations')
25 self.cond = K.equal(self.iterations % self.steps_per_update, 0)
---> 26 self.lr = self.optimizer.lr
27 self.optimizer.lr = K.switch(self.cond, self.optimizer.lr, 0.)
28 for attr in ['momentum', 'rho', 'beta_1', 'beta_2']:
AttributeError: can't set attribute