-
Notifications
You must be signed in to change notification settings - Fork 317
/
metrics.py
433 lines (351 loc) · 14.5 KB
/
metrics.py
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
from enum import Enum
from typing import Optional, Union
from rubrix.client import api
from rubrix.metrics import helpers
from rubrix.metrics.models import MetricSummary
def tokens_length(
name: str, query: Optional[str] = None, interval: int = 1
) -> MetricSummary:
"""Computes the text length distribution measured in number of tokens.
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
interval: The bins or bucket for result histogram
Returns:
The summary for token distribution
Examples:
>>> from rubrix.metrics.token_classification import tokens_length
>>> summary = tokens_length(name="example-dataset", interval=5)
>>> summary.visualize() # will plot a histogram with results
>>> summary.data # the raw histogram data with bins of size 5
"""
metric = api.active_api().compute_metric(
name, metric="tokens_length", query=query, interval=interval
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.histogram(
metric.results,
title=metric.description,
x_legend="# tokens",
),
)
def token_frequency(
name: str, query: Optional[str] = None, tokens: int = 1000
) -> MetricSummary:
"""Computes the token frequency distribution for a numbe of tokens.
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
tokens: The top-k number of tokens to retrieve
Returns:
The summary for token frequency distribution
Examples:
>>> from rubrix.metrics.token_classification import token_frequency
>>> summary = token_frequency(name="example-dataset", token=50)
>>> summary.visualize() # will plot a histogram with results
>>> summary.data # the top-50 tokens frequency
"""
metric = api.active_api().compute_metric(
name, metric="token_frequency", query=query, size=tokens
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.bar(
metric.results,
title=metric.description,
),
)
def token_length(name: str, query: Optional[str] = None) -> MetricSummary:
"""Computes the token size distribution in terms of number of characters
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
Returns:
The summary for token length distribution
Examples:
>>> from rubrix.metrics.token_classification import token_length
>>> summary = token_length(name="example-dataset")
>>> summary.visualize() # will plot a histogram with results
>>> summary.data # The token length distribution
"""
metric = api.active_api().compute_metric(name, metric="token_length", query=query)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.histogram(
metric.results,
title=metric.description,
x_legend="# chars",
),
)
def token_capitalness(name: str, query: Optional[str] = None) -> MetricSummary:
"""Computes the token capitalness distribution
``UPPER``: All characters in the token are upper case.
``LOWER``: All characters in the token are lower case.
``FIRST``: The first character in the token is upper case.
``MIDDLE``: First character in the token is lower case and at least one other character is upper case.
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
Returns:
The summary for token length distribution
Examples:
>>> from rubrix.metrics.token_classification import token_capitalness
>>> summary = token_capitalness(name="example-dataset")
>>> summary.visualize() # will plot a histogram with results
>>> summary.data # The token capitalness distribution
"""
metric = api.active_api().compute_metric(
name, metric="token_capitalness", query=query
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.bar(
metric.results,
title=metric.description,
),
)
class ComputeFor(Enum):
ANNOTATIONS = "annotations"
PREDICTIONS = "predictions"
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
Annotations = ComputeFor.ANNOTATIONS
Predictions = ComputeFor.PREDICTIONS
_ACCEPTED_COMPUTE_FOR_VALUES = {
Annotations: "annotated",
Predictions: "predicted",
}
def _check_compute_for(compute_for: Union[str, ComputeFor]) -> str:
if not compute_for:
compute_for = Predictions
if isinstance(compute_for, str):
compute_for = compute_for.lower().strip()
compute_for = ComputeFor(compute_for)
return _ACCEPTED_COMPUTE_FOR_VALUES[compute_for]
def mention_length(
name: str,
query: Optional[str] = None,
level: str = "token",
compute_for: Union[str, ComputeFor] = Predictions,
interval: int = 1,
) -> MetricSummary:
"""Computes mentions length distribution (in number of tokens).
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
level: The mention length level. Accepted values are "token" and "char"
compute_for: Metric can be computed for annotations or predictions. Accepted values are
``Annotations`` and ``Predictions``. Defaults to ``Predictions``.
interval: The bins or bucket for result histogram
Returns:
The summary for mention token distribution
Examples:
>>> from rubrix.metrics.token_classification import mention_length
>>> summary = mention_length(name="example-dataset", interval=2)
>>> summary.visualize() # will plot a histogram chart with results
>>> summary.data # the raw histogram data with bins of size 2
"""
level = (level or "token").lower().strip()
accepted_levels = ["token", "char"]
assert (
level in accepted_levels
), f"Unexpected value for level. Accepted values are {accepted_levels}"
metric = api.active_api().compute_metric(
name,
metric=f"{_check_compute_for(compute_for)}_mention_{level}_length",
query=query,
interval=interval,
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.histogram(
metric.results,
title=metric.description,
x_legend=f"# {level}",
),
)
def entity_labels(
name: str,
query: Optional[str] = None,
compute_for: Union[str, ComputeFor] = Predictions,
labels: int = 50,
) -> MetricSummary:
"""Computes the entity labels distribution
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
compute_for: Metric can be computed for annotations or predictions. Accepted values are
``Annotations`` and ``Predictions``. Default to ``Predictions``
labels: The number of top entities to retrieve. Lower numbers will be better performants
Returns:
The summary for entity tags distribution
Examples:
>>> from rubrix.metrics.token_classification import entity_labels
>>> summary = entity_labels(name="example-dataset", labels=20)
>>> summary.visualize() # will plot a bar chart with results
>>> summary.data # The top-20 entity tags
"""
metric = api.active_api().compute_metric(
name,
metric=f"{_check_compute_for(compute_for)}_entity_labels",
query=query,
size=labels,
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.bar(
metric.results,
title=metric.description,
),
)
def entity_density(
name: str,
query: Optional[str] = None,
compute_for: Union[str, ComputeFor] = Predictions,
interval: float = 0.005,
) -> MetricSummary:
"""Computes the entity density distribution. Then entity density is calculated at
record level for each mention as ``mention_length/tokens_length``
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
compute_for: Metric can be computed for annotations or predictions. Accepted values are
``Annotations`` and ``Predictions``. Default to ``Predictions``.
interval: The interval for histogram. The entity density is defined in the range 0-1.
Returns:
The summary entity density distribution
Examples:
>>> from rubrix.metrics.token_classification import entity_density
>>> summary = entity_density(name="example-dataset")
>>> summary.visualize()
"""
metric = api.active_api().compute_metric(
name,
metric=f"{_check_compute_for(compute_for)}_entity_density",
query=query,
interval=interval,
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.histogram(
metric.results,
title=metric.description,
),
)
def entity_capitalness(
name: str,
query: Optional[str] = None,
compute_for: Union[str, ComputeFor] = Predictions,
) -> MetricSummary:
"""Computes the entity capitalness. The entity capitalness splits the entity mention shape in 4 groups:
``UPPER``: All characters in entity mention are upper case.
``LOWER``: All characters in entity mention are lower case.
``FIRST``: The first character in the mention is upper case.
``MIDDLE``: First character in the mention is lower case and at least one other character is upper case.
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
compute_for: Metric can be computed for annotations or predictions. Accepted values are
``Annotations`` and ``Predictions``. Default to ``Predictions``.
Returns:
The summary entity capitalness distribution
Examples:
>>> from rubrix.metrics.token_classification import entity_capitalness
>>> summary = entity_capitalness(name="example-dataset")
>>> summary.visualize()
"""
metric = api.active_api().compute_metric(
name,
metric=f"{_check_compute_for(compute_for)}_entity_capitalness",
query=query,
)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.bar(
metric.results,
title=metric.description,
),
)
def entity_consistency(
name: str,
query: Optional[str] = None,
compute_for: Union[str, ComputeFor] = Predictions,
mentions: int = 100,
threshold: int = 2,
):
"""Computes the consistency for top entity mentions in the dataset.
Entity consistency defines the label variability for a given mention. For example, a mention `first` identified
in the whole dataset as `Cardinal`, `Person` and `Time` is less consistent than a mention `Peter` identified as
`Person` in the dataset.
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
compute_for: Metric can be computed for annotations or predictions. Accepted values are
``Annotations`` and ``Predictions``. Default to ``Predictions``
mentions: The number of top mentions to retrieve.
threshold: The entity variability threshold (must be greater or equal to 2).
Returns:
The summary entity capitalness distribution
Examples:
>>> from rubrix.metrics.token_classification import entity_consistency
>>> summary = entity_consistency(name="example-dataset")
>>> summary.visualize()
"""
if threshold < 2:
# TODO: Warning???
threshold = 2
metric = api.active_api().compute_metric(
name,
metric=f"{_check_compute_for(compute_for)}_entity_consistency",
query=query,
size=mentions,
interval=threshold,
)
mentions = [mention["mention"] for mention in metric.results["mentions"]]
entities = {}
for mention in metric.results["mentions"]:
for entity in mention["entities"]:
mentions_for_label = entities.get(entity["label"], [0] * len(mentions))
mentions_for_label[mentions.index(mention["mention"])] = entity["count"]
entities[entity["label"]] = mentions_for_label
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.stacked_bar(
x=mentions, y_s=entities, title=metric.description
),
)
def f1(name: str, query: Optional[str] = None) -> MetricSummary:
"""Computes F1 metrics for a dataset based on entity-level.
Args:
name: The dataset name.
query: An ElasticSearch query with the
`query string syntax <https://rubrix.readthedocs.io/en/stable/guides/queries.html>`_
Returns:
The F1 metric summary containing precision, recall and the F1 score (averaged and per label).
Examples:
>>> from rubrix.metrics.token_classification import f1
>>> summary = f1(name="example-dataset")
>>> summary.visualize() # will plot three bar charts with the results
>>> summary.data # returns the raw result data
To display the results as a table:
>>> import pandas as pd
>>> pd.DataFrame(summary.data.values(), index=summary.data.keys())
"""
metric = api.active_api().compute_metric(name, metric="F1", query=query)
return MetricSummary.new_summary(
data=metric.results,
visualization=lambda: helpers.f1(metric.results, metric.description),
)