msmloss.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 MSMLoss(paddle.nn.Layer):
  20. """
  21. MSMLoss 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(MSMLoss, 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. #normalization
  39. features = input["features"]
  40. features = self._nomalize(features)
  41. samples_each_class = self.samples_each_class
  42. rerange_index = paddle.to_tensor(self.rerange_index)
  43. #calc sm
  44. diffs = paddle.unsqueeze(
  45. features, axis=1) - paddle.unsqueeze(
  46. features, axis=0)
  47. similary_matrix = paddle.sum(paddle.square(diffs), axis=-1)
  48. #rerange
  49. tmp = paddle.reshape(similary_matrix, shape=[-1, 1])
  50. tmp = paddle.gather(tmp, index=rerange_index)
  51. similary_matrix = paddle.reshape(tmp, shape=[-1, self.batch_size])
  52. #split
  53. ignore, pos, neg = paddle.split(
  54. similary_matrix,
  55. num_or_sections=[1, samples_each_class - 1, -1],
  56. axis=1)
  57. ignore.stop_gradient = True
  58. hard_pos = paddle.max(pos)
  59. hard_neg = paddle.min(neg)
  60. loss = hard_pos + self.margin - hard_neg
  61. loss = paddle.nn.ReLU()(loss)
  62. return {"msmloss": loss}
  63. def _nomalize(self, input):
  64. input_norm = paddle.sqrt(
  65. paddle.sum(paddle.square(input), axis=1, keepdim=True))
  66. return paddle.divide(input, input_norm)