trihardloss.py 2.9 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 21
#   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 已提交
22

B
Bin Lu 已提交
23 24
class TriHardLoss(paddle.nn.Layer):
    """
25 26
    paper: In Defense of the Triplet Loss for Person Re-Identification
    code reference: https://github.com/VisualComputingInstitute/triplet-reid/blob/master/loss.py
B
Bin Lu 已提交
27 28 29
    TriHard 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
30

B
Bin Lu 已提交
31 32 33 34 35 36 37
            supported_metrics = [
            'euclidean',
            'sqeuclidean',
            'cityblock',
        ]
    only consider samples_each_class = 2
    """
W
weishengyu 已提交
38 39

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

    def forward(self, input, target=None):
        features = input["features"]
        assert (self.batch_size == features.shape[0])
W
weishengyu 已提交
49

50
        #normalization
B
Bin Lu 已提交
51 52
        features = self._nomalize(features)
        samples_each_class = self.samples_each_class
W
weishengyu 已提交
53
        rerange_index = paddle.to_tensor(self.rerange_index)
B
Bin Lu 已提交
54 55

        #calc sm
W
weishengyu 已提交
56 57 58 59 60
        diffs = paddle.unsqueeze(
            features, axis=1) - paddle.unsqueeze(
                features, axis=0)
        similary_matrix = paddle.sum(paddle.square(diffs), axis=-1)

61
        #rerange
W
weishengyu 已提交
62 63 64 65
        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 已提交
66
        #split
W
weishengyu 已提交
67 68 69 70 71 72 73
        ignore, pos, neg = paddle.split(
            similary_matrix,
            num_or_sections=[1, samples_each_class - 1, -1],
            axis=1)

        ignore.stop_gradient = True
        hard_pos = paddle.max(pos, axis=1)
B
Bin Lu 已提交
74 75 76
        hard_neg = paddle.min(neg, axis=1)

        loss = hard_pos + self.margin - hard_neg
W
weishengyu 已提交
77
        loss = paddle.nn.ReLU()(loss)
B
Bin Lu 已提交
78 79 80 81
        loss = paddle.mean(loss)
        return {"trihardloss": loss}

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