pyannote-metrics 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 1.1
2
+ Name: pyannote.metrics
3
+ Version: 0.0.1
4
+ Summary: PyAnnote metrics
5
+ Home-page: http://herve.niderb.fr/
6
+ Author: Hervé Bredin
7
+ Author-email: bredin@limsi.fr
8
+ License: UNKNOWN
9
+ Description: UNKNOWN
10
+ Platform: UNKNOWN
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Natural Language :: English
15
+ Classifier: Programming Language :: Python :: 2.7
16
+ Classifier: Topic :: Scientific/Engineering
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+
4
+ # The MIT License (MIT)
5
+
6
+ # Copyright (c) 2014 CNRS (Hervé BREDIN - http://herve.niderb.fr)
7
+
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ __import__('pkg_resources').declare_namespace(__name__)
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+
4
+ # The MIT License (MIT)
5
+
6
+ # Copyright (c) 2012-2014 CNRS (Hervé BREDIN - http://herve.niderb.fr)
7
+
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ from __future__ import unicode_literals
27
+
28
+ from ._version import get_versions
29
+ __version__ = get_versions()['version']
30
+ del get_versions
31
+
32
+ from base import f_measure
@@ -0,0 +1,11 @@
1
+
2
+ # This file was generated by 'versioneer.py' (0.10) from
3
+ # revision-control system data, or from the parent directory name of an
4
+ # unpacked source archive. Distribution tarballs contain a pre-generated copy
5
+ # of this file.
6
+
7
+ version_version = '0.0.1'
8
+ version_full = '84a937337738be9ec5da202bfef6a4702aa5d1d3'
9
+ def get_versions(default={}, verbose=False):
10
+ return {'version': version_version, 'full': version_full}
11
+
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+
4
+ # The MIT License (MIT)
5
+
6
+ # Copyright (c) 2012-2014 CNRS (Hervé BREDIN - http://herve.niderb.fr)
7
+
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ from __future__ import unicode_literals
27
+
28
+ import scipy.stats
29
+ import numpy as np
30
+ from pyannote.algorithms.tagging import DirectTagger
31
+
32
+
33
+ class BaseMetric(object):
34
+ """
35
+ :class:`BaseMetric` is the base class for most PyAnnote evaluation metrics.
36
+
37
+ Parameters
38
+ ----------
39
+ name : str
40
+ Human-readable name of the metric (eg. 'diarization error rate')
41
+ components : list, set or tuple
42
+ Human-readable names of the components of the metric
43
+ (eg. ['correct', 'false alarm', 'miss', 'confusion'])
44
+
45
+ """
46
+
47
+ @classmethod
48
+ def metric_name(cls):
49
+ raise NotImplementedError("Missing class method 'metric_name'.")
50
+
51
+ @classmethod
52
+ def metric_components(cls):
53
+ raise NotImplementedError("Missing class method 'metric_components'")
54
+
55
+ def __init__(self, **kwargs):
56
+ super(BaseMetric, self).__init__()
57
+ self.__name = self.__class__.metric_name()
58
+ self.__values = set(self.__class__.metric_components())
59
+ self.reset()
60
+ self._tagger = DirectTagger()
61
+
62
+ def __get_name(self):
63
+ return self.__class__.metric_name()
64
+ name = property(fget=__get_name, doc="Metric name.")
65
+
66
+ def __accumulate(self, components):
67
+ """Accumulate metric components
68
+
69
+ Parameters
70
+ ----------
71
+ components : dict
72
+ Dictionary where keys are component names and values are component
73
+ values
74
+
75
+ """
76
+ for name in self.__values:
77
+ self.__details[name] += components[name]
78
+
79
+ def __compute(self, components, accumulate=True, detailed=False):
80
+ """Compute metric value from computed `components`
81
+
82
+ Parameters
83
+ ----------
84
+ components : dict
85
+ Dictionary where keys are components names and values are component
86
+ values
87
+ accumulate : bool, optional
88
+ If True, components are accumulated. Defaults to True.
89
+ detailed : bool, optional
90
+ By default (False), return metric value only.
91
+ Set `detailed` to True to return `components` updated with metric
92
+ value (for key `self.name`).
93
+
94
+ Returns
95
+ -------
96
+ value (if `detailed` is False) : float
97
+ Metric value
98
+ components (if `detailed` is True) : dict
99
+ `components` updated with metric value
100
+ """
101
+ if accumulate:
102
+ self.__accumulate(components)
103
+ rate = self._get_rate(components)
104
+ if detailed:
105
+ components = dict(components)
106
+ components.update({self.__name: rate})
107
+ return components
108
+ else:
109
+ return rate
110
+
111
+ def __call__(self, reference, hypothesis, detailed=False, **kwargs):
112
+ """Compute metric value and accumulate components
113
+
114
+ Parameters
115
+ ----------
116
+ reference : type depends on the metric
117
+ Manual `reference`
118
+ hypothesis : same as `reference`
119
+ Evaluated `hypothesis`
120
+ detailed : bool, optional
121
+ By default (False), return metric value only.
122
+
123
+ Set `detailed` to True to return dictionary where keys are
124
+ components names and values are component values
125
+
126
+
127
+ Returns
128
+ -------
129
+ value : float (if `detailed` is False)
130
+ Metric value
131
+ components : dict (if `detailed` is True)
132
+ `components` updated with metric value
133
+
134
+ """
135
+ detail = self._get_details(reference, hypothesis, **kwargs)
136
+ self.__rates.append((reference.uri, self._get_rate(detail)))
137
+ return self.__compute(detail, accumulate=True, detailed=detailed)
138
+
139
+ def __str__(self):
140
+ detail = self.__compute(self.__details,
141
+ accumulate=False,
142
+ detailed=True)
143
+ return self._pretty(detail)
144
+
145
+ def __abs__(self):
146
+ """Compute metric value from accumulated components"""
147
+ return self._get_rate(self.__details)
148
+
149
+ def __getitem__(self, component):
150
+ """Get value of accumulated `component`.
151
+
152
+ Parameters
153
+ ----------
154
+ component : str
155
+ Name of `component`
156
+
157
+ Returns
158
+ -------
159
+ value : type depends on the metric
160
+ Value of accumulated `component`
161
+
162
+ """
163
+ if component == slice(None, None, None):
164
+ return dict(self.__details)
165
+ else:
166
+ return self.__details[component]
167
+
168
+ def __iter__(self):
169
+ """Iterator over the accumulated (uri, value)"""
170
+ for v, r in self.__rates:
171
+ yield v, r
172
+
173
+ def _get_details(self, reference, hypothesis, **kwargs):
174
+ """Compute metric components
175
+
176
+ Parameters
177
+ ----------
178
+ reference : type depends on the metric
179
+ Manual `reference`
180
+ hypothesis : same as `reference`
181
+ Evaluated `hypothesis`
182
+
183
+ Returns
184
+ -------
185
+ components : dict
186
+ Dictionary where keys are component names and values are component
187
+ values
188
+
189
+ """
190
+ raise NotImplementedError("Missing method '_get_details'.")
191
+
192
+ def _get_rate(self, components):
193
+ """Compute metric value from computed `components`
194
+
195
+ Parameters
196
+ ----------
197
+ components : dict
198
+ Dictionary where keys are components names and values are component
199
+ values
200
+
201
+ Returns
202
+ -------
203
+ value : type depends on the metric
204
+ Metric value
205
+ """
206
+ raise NotImplementedError("Missing method '_get_rate'.")
207
+
208
+ def _pretty(self, components):
209
+ string = '%s: %g\n' % (self.name, components[self.name])
210
+ for name, value in components.iteritems():
211
+ if name == self.name:
212
+ continue
213
+ string += ' - %s: %g\n' % (name, value)
214
+ return string
215
+
216
+ def _init_details(self):
217
+ return {value: 0. for value in self.__values}
218
+
219
+ def reset(self):
220
+ """Reset accumulated components and metric values"""
221
+ self.__details = self._init_details()
222
+ self.__rates = []
223
+
224
+ def confidence_interval(self, alpha=0.9):
225
+ """Compute confidence interval on accumulated metric values
226
+
227
+ Parameters
228
+ ----------
229
+ alpha : float, optional
230
+ Probability that the returned confidence interval contains
231
+ the true metric value.
232
+
233
+ Returns
234
+ -------
235
+ (center, (lower, upper))
236
+ with center the mean of the conditional pdf of the metric value
237
+ and (lower, upper) is a confidence interval centered on the median,
238
+ containing the estimate to a probability alpha.
239
+
240
+ See Also:
241
+ ---------
242
+ scipy.stats.bayes_mvs
243
+
244
+ """
245
+ m, _, _ = scipy.stats.bayes_mvs([r for _, r in self.__rates], alpha=alpha)
246
+ return m
247
+
248
+
249
+ PRECISION_NAME = 'precision'
250
+ PRECISION_RETRIEVED = '# retrieved'
251
+ PRECISION_RELEVANT_RETRIEVED = '# relevant retrieved'
252
+
253
+
254
+ class Precision(BaseMetric):
255
+ """
256
+ :class:`Precision` is a base class for precision-like evaluation metrics.
257
+
258
+ It defines two components '# retrieved' and '# relevant retrieved' and the
259
+ _get_rate() method to compute the actual precision:
260
+
261
+ Precision = # retrieved / # relevant retrieved
262
+
263
+ Inheriting classes must implement _get_details().
264
+ """
265
+
266
+ @classmethod
267
+ def metric_name(cls):
268
+ return PRECISION_NAME
269
+
270
+ @classmethod
271
+ def metric_components(cls):
272
+ return [PRECISION_RETRIEVED, PRECISION_RELEVANT_RETRIEVED]
273
+
274
+ def _get_rate(self, components):
275
+ """Compute precision from `components`"""
276
+ numerator = components[PRECISION_RELEVANT_RETRIEVED]
277
+ denominator = components[PRECISION_RETRIEVED]
278
+ if denominator == 0.:
279
+ if numerator == 0:
280
+ return 1.
281
+ else:
282
+ raise ValueError('')
283
+ else:
284
+ return numerator/denominator
285
+
286
+ RECALL_NAME = 'recall'
287
+ RECALL_RELEVANT = '# relevant'
288
+ RECALL_RELEVANT_RETRIEVED = '# relevant retrieved'
289
+
290
+
291
+ class Recall(BaseMetric):
292
+ """
293
+ :class:`Recall` is a base class for recall-like evaluation metrics.
294
+
295
+ It defines two components '# relevant' and '# relevant retrieved' and the
296
+ _get_rate() method to compute the actual recall:
297
+
298
+ Recall = # relevant retrieved / # relevant
299
+
300
+ Inheriting classes must implement _get_details().
301
+ """
302
+
303
+ @classmethod
304
+ def metric_name(cls):
305
+ return RECALL_NAME
306
+
307
+ @classmethod
308
+ def metric_components(cls):
309
+ return [RECALL_RELEVANT, RECALL_RELEVANT_RETRIEVED]
310
+
311
+ def _get_rate(self, components):
312
+ """Compute recall from `components`"""
313
+ numerator = components[RECALL_RELEVANT_RETRIEVED]
314
+ denominator = components[RECALL_RELEVANT]
315
+ if denominator == 0.:
316
+ if numerator == 0:
317
+ return 1.
318
+ else:
319
+ raise ValueError('')
320
+ else:
321
+ return numerator/denominator
322
+
323
+
324
+ def f_measure(precision, recall, beta=1.):
325
+ """Compute f-measure
326
+
327
+ f-measure is defined as follows:
328
+ F(P, R, b) = (1+b²).P.R / (b².P + R)
329
+
330
+ where P is `precision`, R is `recall` and b is `beta`
331
+ """
332
+ return (1+beta*beta)*precision*recall / (beta*beta*precision+recall)
333
+
334
+
335
+ if __name__ == "__main__":
336
+ import doctest
337
+ doctest.testmod()
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+
4
+ # The MIT License (MIT)
5
+
6
+ # Copyright (c) 2012-2014 CNRS (Hervé BREDIN - http://herve.niderb.fr)
7
+
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ from __future__ import unicode_literals
27
+
28
+ from base import BaseMetric
29
+
30
+ DER_TOTAL = 'total'
31
+ DER_FALSE_ALARM = 'false alarm'
32
+ DER_MISS = 'miss'
33
+ DER_NAME = 'detection error rate'
34
+
35
+
36
+ class DetectionErrorRate(BaseMetric):
37
+
38
+ @classmethod
39
+ def metric_name(cls):
40
+ return DER_NAME
41
+
42
+ @classmethod
43
+ def metric_components(cls):
44
+ return [DER_FALSE_ALARM, DER_MISS, DER_TOTAL]
45
+
46
+ def _get_details(self, reference, hypothesis, **kwargs):
47
+
48
+ detail = self._init_details()
49
+
50
+ # common (up-sampled) timeline
51
+ common_timeline = reference.get_timeline().union(hypothesis.get_timeline())
52
+ common_timeline = common_timeline.segmentation()
53
+
54
+ # align reference on common timeline
55
+ R = self._tagger(reference, common_timeline)
56
+
57
+ # translate and align hypothesis on common timeline
58
+ H = self._tagger(hypothesis, common_timeline)
59
+
60
+ # loop on all segments
61
+ for segment in common_timeline:
62
+
63
+ # segment duration
64
+ duration = segment.duration
65
+
66
+ # set of IDs in reference segment
67
+ r = R.get_labels(segment)
68
+ Nr = len(r)
69
+ detail[DER_TOTAL] += duration * Nr
70
+
71
+ # set of IDs in hypothesis segment
72
+ h = H.get_labels(segment)
73
+ Nh = len(h)
74
+
75
+ # number of misses
76
+ N_miss = max(0, Nr - Nh)
77
+ detail[DER_MISS] += duration * N_miss
78
+
79
+ # number of false alarms
80
+ N_fa = max(0, Nh - Nr)
81
+ detail[DER_FALSE_ALARM] += duration * N_fa
82
+
83
+ return detail
84
+
85
+ def _get_rate(self, detail):
86
+ numerator = 1. * (detail[DER_FALSE_ALARM] + detail[DER_MISS])
87
+ denominator = 1. * detail[DER_TOTAL]
88
+ if denominator == 0.:
89
+ if numerator == 0:
90
+ return 0.
91
+ else:
92
+ return 1.
93
+ else:
94
+ return numerator/denominator
95
+
96
+ def _pretty(self, detail):
97
+ string = ""
98
+ string += " - duration: %.2f seconds\n" % (detail[DER_TOTAL])
99
+ string += " - miss: %.2f seconds\n" % (detail[DER_MISS])
100
+ string += " - false alarm: %.2f seconds\n" % (detail[DER_FALSE_ALARM])
101
+ string += " - %s: %.2f %%\n" % (self.name, 100*detail[self.name])
102
+ return string
103
+
104
+
105
+ if __name__ == "__main__":
106
+ import doctest
107
+ doctest.testmod()