msmloss.py 2.7 KB
Newer Older
B
Bin Lu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
from .comfunc import rerange_index

W
weishengyu 已提交
21

B
Bin Lu 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34
class MSMLoss(paddle.nn.Layer):
    """
    MSMLoss Loss, based on triplet loss. USE P * K samples.
    the batch size is fixed. Batch_size = P * K;  but the K may vary between batches.
    same label gather together
    
            supported_metrics = [
            'euclidean',
            'sqeuclidean',
            'cityblock',
        ]
    only consider samples_each_class = 2
    """
W
weishengyu 已提交
35 36

    def __init__(self, batch_size=120, samples_each_class=2, margin=0.1):
B
Bin Lu 已提交
37 38 39
        super(MSMLoss, self).__init__()
        self.margin = margin
        self.samples_each_class = samples_each_class
W
weishengyu 已提交
40 41
        self.batch_size = batch_size
        self.rerange_index = rerange_index(batch_size, samples_each_class)
B
Bin Lu 已提交
42 43 44 45 46 47

    def forward(self, input, target=None):
        #normalization 
        features = input["features"]
        features = self._nomalize(features)
        samples_each_class = self.samples_each_class
W
weishengyu 已提交
48
        rerange_index = paddle.to_tensor(self.rerange_index)
B
Bin Lu 已提交
49 50

        #calc sm
W
weishengyu 已提交
51 52 53 54 55
        diffs = paddle.unsqueeze(
            features, axis=1) - paddle.unsqueeze(
                features, axis=0)
        similary_matrix = paddle.sum(paddle.square(diffs), axis=-1)

B
Bin Lu 已提交
56
        #rerange 
W
weishengyu 已提交
57 58 59 60
        tmp = paddle.reshape(similary_matrix, shape=[-1, 1])
        tmp = paddle.gather(tmp, index=rerange_index)
        similary_matrix = paddle.reshape(tmp, shape=[-1, self.batch_size])

B
Bin Lu 已提交
61
        #split
W
weishengyu 已提交
62 63 64 65 66
        ignore, pos, neg = paddle.split(
            similary_matrix,
            num_or_sections=[1, samples_each_class - 1, -1],
            axis=1)
        ignore.stop_gradient = True
B
Bin Lu 已提交
67

W
weishengyu 已提交
68
        hard_pos = paddle.max(pos)
B
Bin Lu 已提交
69 70 71
        hard_neg = paddle.min(neg)

        loss = hard_pos + self.margin - hard_neg
W
weishengyu 已提交
72
        loss = paddle.nn.ReLU()(loss)
B
Bin Lu 已提交
73 74 75
        return {"msmloss": loss}

    def _nomalize(self, input):
W
weishengyu 已提交
76 77
        input_norm = paddle.sqrt(
            paddle.sum(paddle.square(input), axis=1, keepdim=True))
B
Bin Lu 已提交
78
        return paddle.divide(input, input_norm)