trihardloss.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright (c) 2018 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. from .comfunc import rerange_index
  19. class TriHardLoss(paddle.nn.Layer):
  20. """
  21. TriHard Loss, based on triplet loss. USE P * K samples.
  22. the batch size is fixed. Batch_size = P * K; but the K may vary between batches.
  23. same label gather together
  24. supported_metrics = [
  25. 'euclidean',
  26. 'sqeuclidean',
  27. 'cityblock',
  28. ]
  29. only consider samples_each_class = 2
  30. """
  31. def __init__(self, batch_size=120, samples_each_class=2, margin=0.1):
  32. super(TriHardLoss, self).__init__()
  33. self.margin = margin
  34. self.samples_each_class = samples_each_class
  35. self.batch_size = batch_size
  36. self.rerange_index = rerange_index(batch_size, samples_each_class)
  37. def forward(self, input, target=None):
  38. features = input["features"]
  39. assert (self.batch_size == features.shape[0])
  40. #normalization
  41. features = self._nomalize(features)
  42. samples_each_class = self.samples_each_class
  43. rerange_index = paddle.to_tensor(self.rerange_index)
  44. #calc sm
  45. diffs = paddle.unsqueeze(
  46. features, axis=1) - paddle.unsqueeze(
  47. features, axis=0)
  48. similary_matrix = paddle.sum(paddle.square(diffs), axis=-1)
  49. #rerange
  50. tmp = paddle.reshape(similary_matrix, shape=[-1, 1])
  51. tmp = paddle.gather(tmp, index=rerange_index)
  52. similary_matrix = paddle.reshape(tmp, shape=[-1, self.batch_size])
  53. #split
  54. ignore, pos, neg = paddle.split(
  55. similary_matrix,
  56. num_or_sections=[1, samples_each_class - 1, -1],
  57. axis=1)
  58. ignore.stop_gradient = True
  59. hard_pos = paddle.max(pos, axis=1)
  60. hard_neg = paddle.min(neg, axis=1)
  61. loss = hard_pos + self.margin - hard_neg
  62. loss = paddle.nn.ReLU()(loss)
  63. loss = paddle.mean(loss)
  64. return {"trihardloss": loss}
  65. def _nomalize(self, input):
  66. input_norm = paddle.sqrt(
  67. paddle.sum(paddle.square(input), axis=1, keepdim=True))
  68. return paddle.divide(input, input_norm)