circlemargin.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import math
  15. import paddle
  16. import paddle.nn as nn
  17. import paddle.nn.functional as F
  18. class CircleMargin(nn.Layer):
  19. def __init__(self, embedding_size, class_num, margin, scale):
  20. super(CircleMargin, self).__init__()
  21. self.scale = scale
  22. self.margin = margin
  23. self.embedding_size = embedding_size
  24. self.class_num = class_num
  25. self.weight = self.create_parameter(
  26. shape=[self.embedding_size, self.class_num],
  27. is_bias=False,
  28. default_initializer=paddle.nn.initializer.XavierNormal())
  29. def forward(self, input, label):
  30. feat_norm = paddle.sqrt(
  31. paddle.sum(paddle.square(input), axis=1, keepdim=True))
  32. input = paddle.divide(input, feat_norm)
  33. weight_norm = paddle.sqrt(
  34. paddle.sum(paddle.square(self.weight), axis=0, keepdim=True))
  35. weight = paddle.divide(self.weight, weight_norm)
  36. logits = paddle.matmul(input, weight)
  37. if not self.training or label is None:
  38. return logits
  39. alpha_p = paddle.clip(-logits.detach() + 1 + self.margin, min=0.)
  40. alpha_n = paddle.clip(logits.detach() + self.margin, min=0.)
  41. delta_p = 1 - self.margin
  42. delta_n = self.margin
  43. m_hot = F.one_hot(label.reshape([-1]), num_classes=logits.shape[1])
  44. logits_p = alpha_p * (logits - delta_p)
  45. logits_n = alpha_n * (logits - delta_n)
  46. pre_logits = logits_p * m_hot + logits_n * (1 - m_hot)
  47. pre_logits = self.scale * pre_logits
  48. return pre_logits