You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
1.3 KiB

3 years ago
  1. from fastai.vision import *
  2. class FeatureLoss(nn.Module):
  3. def __init__(self, m_feat, layer_ids, layer_wgts):
  4. super().__init__()
  5. self.m_feat = m_feat
  6. self.loss_features = [self.m_feat[i] for i in layer_ids]
  7. self.hooks = hook_outputs(self.loss_features, detach=False)
  8. self.wgts = layer_wgts
  9. self.metric_names = ['pixel', ] + [f'feat_{i}' for i in range(len(layer_ids))
  10. ] + [f'gram_{i}' for i in range(len(layer_ids))]
  11. def make_features(self, x, clone=False):
  12. self.m_feat(x)
  13. return [(o.clone() if clone else o) for o in self.hooks.stored]
  14. def forward(self, input, target):
  15. out_feat = self.make_features(target, clone=True)
  16. in_feat = self.make_features(input)
  17. self.feat_losses = [base_loss(input, target)]
  18. self.feat_losses += [base_loss(f_in, f_out) * w
  19. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  20. self.feat_losses += [base_loss(gram_matrix(f_in), gram_matrix(f_out)) * w ** 2 * 5e3
  21. for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
  22. self.metrics = dict(zip(self.metric_names, self.feat_losses))
  23. return sum(self.feat_losses)
  24. def __del__(self): self.hooks.remove()