File size: 3,934 Bytes
c870f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11842f0
c870f2c
 
 
3da12f4
11842f0
 
 
 
c870f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
e45a326
639df4a
c870f2c
 
 
639df4a
c870f2c
639df4a
e45a326
c870f2c
639df4a
c870f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3cc6a6
 
 
c870f2c
 
 
 
 
 
cd29486
 
6c1fbd2
 
 
 
 
910988a
c870f2c
cd29486
 
c870f2c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# Copyright 2020 The HuggingFace Datasets Authors.
#
# 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.
"""Triplet Margin Loss metric."""

import datasets
import evaluate
import numpy as np


_DESCRIPTION = """
Triplet margin loss is a loss function that measures a relative similarity between the samples.
A triplet is comprised of reference input 'anchor (a)', matching input 'positive examples (p)' and non-matching input 'negative examples (n)'.
The loss function for each triplet is given by:\n
L(a, p, n) = max{d(a,p) - d(a,n) + margin, 0}\n
where d(x, y) is the 2nd order (Euclidean) pairwise distance between x and y.
"""


_KWARGS_DESCRIPTION = """
Args:
    anchor (`list` of `float`): Reference inputs.
    positive (`list` of `float`): Matching inputs.
    negative (`list` of `float`): Non-matching inputs.
    margin (`float`): Margin, default:`1.0`

Returns:
    triplet_margin_loss (`float`): Total loss.
Examples:
    Example 1-A simple example
        >>> triplet_margin_loss = evaluate.load("theAIguy/triplet_margin_loss")
        >>> loss = triplet_margin_loss.compute(
            anchor=[-0.4765, 1.7133, 1.3971, -1.0121, 0.0732], 
            positive=[0.9218, 0.6305, 0.3381, 0.1412, 0.2607], 
            negative=[0.1971, 0.7246, 0.6729, 0.0941, 0.1011])
        >>> print(loss)
        {'triplet_margin_loss': 1.59}
    Example 2-The same as Example 1, except `margin` set to `2.0`.
        >>> triplet_margin_loss = evaluate.load("theAIguy/triplet_margin_loss")
        >>> results = triplet_margin_loss.compute(
            anchor=[-0.4765, 1.7133, 1.3971, -1.0121, 0.0732],
            positive=[0.9218, 0.6305, 0.3381, 0.1412, 0.2607], 
            negative=[0.1971, 0.7246, 0.6729, 0.0941, 0.1011]), 
            margin=2.0)
        >>> print(results)
        {'triplet_margin_loss': 2.59}
"""


_CITATION = """
@article{schultz2003learning,
  title={Learning a distance metric from relative comparisons},
  author={Schultz, Matthew and Joachims, Thorsten},
  journal={Advances in neural information processing systems},
  volume={16},
  year={2003}
}
"""


@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class TripletMarginLoss(evaluate.EvaluationModule):
    def _info(self):
        return evaluate.EvaluationModuleInfo(
            description=_DESCRIPTION,
            citation=_CITATION,
            inputs_description=_KWARGS_DESCRIPTION,
            features=datasets.Features(
                {
                    "anchor": datasets.Sequence(datasets.Value("float")),
                    "positive": datasets.Sequence(datasets.Value("float")),
                    "negative": datasets.Sequence(datasets.Value("float"))
                }
            ),
            reference_urls=["https://proceedings.neurips.cc/paper/2003/hash/d3b1fb02964aa64e257f9f26a31f72cf-Abstract.html"],
        )

    def _compute(self, anchor, positive, negative, margin=1.0):
        if not (len(anchor) == len(positive) == len(negative)):
            raise ValueError("Anchor, Positive and Negative examples must be of same length.")
        d_a_p_sum = 0.0
        d_a_n_sum = 0.0
        for a, p, n in zip(anchor, positive, negative):
            d_a_p_sum += (a - p)**2
            d_a_n_sum += (a - n)**2
        loss = max(np.sqrt(d_a_p_sum) - np.sqrt(d_a_n_sum) + margin, 0)
        return {
            "triplet_margin_loss": float(
                loss
            )
        }