我正在尝试使用实例方法来修改实例的属性之一,如下所示:
from torch.optim import SGD
from typing import Dict
class ChangeRateSgd(SGD):
def __init__(self, params, lr: float, lr_change_instructions: Dict):
super().__init__(params, lr)
self.lr_change_instructions = lr_change_instructions
def change_update_rate(self, input_epoch):
update_mapping = self.lr_change_instructions
if input_epoch in update_mapping.keys():
new_lr = self.lr_change_instructions[input_epoch]
self.lr = new_lr
但是,我的IDE将行self.lr = new_lr
标记为不是理想的编码实践,并带有警告Instance attribute lr defined outside __init__
。使用此实例方法执行尝试的最佳方法是什么?
尝试下面的代码,您需要在init方法中定义lr并访问其他任何方法。
from torch.optim import SGD
from typing import Dict
class ChangeRateSgd(SGD):
def __init__(self, params, lr: float, lr_change_instructions: Dict):
super().__init__(params, lr)
self.lr =None
self.lr_change_instructions = lr_change_instructions
def change_update_rate(self, input_epoch):
update_mapping = self.lr_change_instructions
if input_epoch in update_mapping.keys():
new_lr = self.lr_change_instructions[input_epoch]
self.lr = new_lr