/
label_models.py
1083 lines (876 loc) · 42.1 KB
/
label_models.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2021-present, the Recognai S.L. team.
#
# 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.
import hashlib
import logging
from enum import Enum
from typing import Dict, List, Tuple, Union
import numpy as np
from rubrix import DatasetForTextClassification, TextClassificationRecord
from rubrix.client.datasets import Dataset
from rubrix.labeling.text_classification.weak_labels import WeakLabels, WeakMultiLabels
_LOGGER = logging.getLogger(__name__)
class TieBreakPolicy(Enum):
"""A tie break policy"""
ABSTAIN = "abstain"
RANDOM = "random"
TRUE_RANDOM = "true-random"
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
class LabelModel:
"""Abstract base class for a label model implementation.
Args:
weak_labels: Every label model implementation needs at least a `WeakLabels` instance.
"""
# When we break a tie, by how much shall we increase the probability of the winner?
_PROBABILITY_INCREASE_ON_TIE_BREAK = 0.0001
def __init__(self, weak_labels: WeakLabels):
self._weak_labels = weak_labels
@property
def weak_labels(self) -> WeakLabels:
"""The underlying `WeakLabels` object, containing the weak labels and records."""
return self._weak_labels
def fit(self, include_annotated_records: bool = False, *args, **kwargs):
"""Fits the label model.
Args:
include_annotated_records: Whether to include annotated records in the fitting.
"""
raise NotImplementedError
def score(self, *args, **kwargs) -> Dict:
"""Evaluates the label model."""
raise NotImplementedError
def predict(
self,
include_annotated_records: bool = False,
prediction_agent: str = "LabelModel",
**kwargs,
) -> DatasetForTextClassification:
"""Applies the label model.
Args:
include_annotated_records: Whether to include annotated records.
prediction_agent: String used for the ``prediction_agent`` in the returned records.
**kwargs: Specific to the label model implementations
Returns:
A dataset of records that include the predictions of the label model.
"""
raise NotImplementedError
class MajorityVoter(LabelModel):
"""A basic label model that computes the majority vote across all rules.
For single-label classification, it will predict the label with the most votes.
For multi-label classification, it will predict all labels that got at least one vote by the rules.
Args:
weak_labels: The weak labels object.
"""
def __init__(self, weak_labels: Union[WeakLabels, WeakMultiLabels]):
super().__init__(weak_labels=weak_labels)
def fit(self, *args, **kwargs):
"""Raises a NotImplementedError.
No need to call fit on the ``MajorityVoter``!
"""
raise NotImplementedError("No need to call fit on the 'MajorityVoter'!")
def predict(
self,
include_annotated_records: bool = False,
include_abstentions: bool = False,
prediction_agent: str = "MajorityVoter",
tie_break_policy: Union[TieBreakPolicy, str] = "abstain",
) -> DatasetForTextClassification:
"""Applies the label model.
Args:
include_annotated_records: Whether to include annotated records.
include_abstentions: Whether to include records in the output, for which the label model abstained.
prediction_agent: String used for the ``prediction_agent`` in the returned records.
tie_break_policy: Policy to break ties (IGNORED FOR MULTI-LABEL!). You can choose among two policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash
The last policy can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
Returns:
A dataset of records that include the predictions of the label model.
"""
wl_matrix = self._weak_labels.matrix(
has_annotation=None if include_annotated_records else False
)
records = self._weak_labels.records(
has_annotation=None if include_annotated_records else False
)
if isinstance(self._weak_labels, WeakMultiLabels):
records = self._make_multi_label_records(
probabilities=self._compute_multi_label_probs(wl_matrix),
records=records,
include_abstentions=include_abstentions,
prediction_agent=prediction_agent,
)
else:
if isinstance(tie_break_policy, str):
tie_break_policy = TieBreakPolicy(tie_break_policy)
records = self._make_single_label_records(
probabilities=self._compute_single_label_probs(wl_matrix),
records=records,
include_abstentions=include_abstentions,
prediction_agent=prediction_agent,
tie_break_policy=tie_break_policy,
)
return DatasetForTextClassification(records)
def _compute_single_label_probs(self, wl_matrix: np.ndarray) -> np.ndarray:
"""Helper methods that computes the probabilities.
Args:
wl_matrix: The weak label matrix.
Returns:
A matrix of "probabilities" with nr or records x nr of labels.
The label order matches the one from `self.weak_labels.labels`.
"""
counts = np.column_stack(
[
np.count_nonzero(
wl_matrix == self._weak_labels.label2int[label], axis=1
)
for label in self._weak_labels.labels
]
)
with np.errstate(invalid="ignore"):
probabilities = counts / counts.sum(axis=1).reshape(len(counts), -1)
# we treat abstentions as ties among all labels (see snorkel)
probabilities[np.isnan(probabilities)] = 1.0 / len(self._weak_labels.labels)
return probabilities
def _make_single_label_records(
self,
probabilities: np.ndarray,
records: List[TextClassificationRecord],
include_abstentions: bool,
prediction_agent: str,
tie_break_policy: TieBreakPolicy,
) -> List[TextClassificationRecord]:
"""Helper method to create records given predicted probabilities.
Args:
probabilities: The predicted probabilities.
records: The records associated with the probabilities.
include_abstentions: Whether to include records in the output, for which the label model abstained.
prediction_agent: String used for the ``prediction_agent`` in the returned records.
tie_break_policy: Policy to break ties. You can choose among two policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash
The last policy can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
Returns:
A list of records that include the predictions of the label model.
"""
records_with_prediction = []
for i, prob, rec in zip(range(len(records)), probabilities, records):
# Check if model abstains, that is if the highest probability is assigned to more than one label
# 1.e-8 is taken from the abs tolerance of np.isclose
equal_prob_idx = np.nonzero(np.abs(prob.max() - prob) < 1.0e-8)[0]
tie = False
if len(equal_prob_idx) > 1:
tie = True
# maybe skip record
if not include_abstentions and (
tie and tie_break_policy is TieBreakPolicy.ABSTAIN
):
continue
if not tie:
pred_for_rec = [
(self._weak_labels.labels[idx], prob[idx])
for idx in np.argsort(prob)[::-1]
]
# resolve ties following the tie break policy
elif tie_break_policy is TieBreakPolicy.ABSTAIN:
pred_for_rec = None
elif tie_break_policy is TieBreakPolicy.RANDOM:
random_idx = int(hashlib.sha1(f"{i}".encode()).hexdigest(), 16) % len(
equal_prob_idx
)
for idx in equal_prob_idx:
if idx == random_idx:
prob[idx] += self._PROBABILITY_INCREASE_ON_TIE_BREAK
else:
prob[idx] -= self._PROBABILITY_INCREASE_ON_TIE_BREAK / (
len(equal_prob_idx) - 1
)
pred_for_rec = [
(self._weak_labels.labels[idx], prob[idx])
for idx in np.argsort(prob)[::-1]
]
else:
raise NotImplementedError(
f"The tie break policy '{tie_break_policy.value}' is not implemented for {self.__class__.__name__}!"
)
records_with_prediction.append(rec.copy(deep=True))
records_with_prediction[-1].prediction = pred_for_rec
records_with_prediction[-1].prediction_agent = prediction_agent
return records_with_prediction
def _compute_multi_label_probs(self, wl_matrix: np.ndarray) -> np.ndarray:
"""Helper methods that computes the probabilities.
Args:
wl_matrix: The weak label matrix.
Returns:
A matrix of "probabilities" with nr or records x nr of labels.
The label order matches the one from `self.weak_labels.labels`.
"""
# turn abstentions (-1) into 0
counts = np.where(wl_matrix == -1, 0, wl_matrix).sum(axis=1)
# binary probability, predict all labels with at least one vote
probabilities = np.where(counts > 0, 1, 0).astype(np.float16)
all_rules_abstained = wl_matrix.sum(axis=1).sum(axis=1) == (
-1 * self._weak_labels.cardinality * len(self._weak_labels.rules)
)
probabilities[all_rules_abstained] = [np.nan] * len(self._weak_labels.labels)
# more "nuanced probability", not sure if useful though
# with np.errstate(invalid="ignore"):
# probabilities = counts / counts.sum(axis=1).reshape(len(counts), -1)
return probabilities
def _make_multi_label_records(
self,
probabilities: np.ndarray,
records: List[TextClassificationRecord],
include_abstentions: bool,
prediction_agent: str,
) -> List[TextClassificationRecord]:
"""Helper method to create records given predicted probabilities.
Args:
probabilities: The predicted probabilities.
records: The records associated with the probabilities.
include_abstentions: Whether to include records in the output, for which the label model abstained.
prediction_agent: String used for the ``prediction_agent`` in the returned records.
Returns:
A list of records that include the predictions of the label model.
"""
records_with_prediction = []
for prob, rec in zip(probabilities, records):
all_abstained = np.isnan(prob).all()
# maybe skip record
if not include_abstentions and all_abstained:
continue
pred_for_rec = None
if not all_abstained:
pred_for_rec = [
(self._weak_labels.labels[i], prob[i])
for i in np.argsort(prob)[::-1]
]
records_with_prediction.append(rec.copy(deep=True))
records_with_prediction[-1].prediction = pred_for_rec
records_with_prediction[-1].prediction_agent = prediction_agent
return records_with_prediction
def score(
self,
tie_break_policy: Union[TieBreakPolicy, str] = "abstain",
output_str: bool = False,
) -> Union[Dict[str, float], str]:
"""Returns some scores/metrics of the label model with respect to the annotated records.
The metrics are:
- accuracy
- micro/macro averages for precision, recall and f1
- precision, recall, f1 and support for each label
For more details about the metrics, check out the
`sklearn docs <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html#sklearn-metrics-precision-recall-fscore-support>`__.
.. note:: Metrics are only calculated over non-abstained predictions!
Args:
tie_break_policy: Policy to break ties (IGNORED FOR MULTI-LABEL). You can choose among two policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash
The last policy can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
output_str: If True, return output as nicely formatted string.
Returns:
The scores/metrics in a dictionary or as a nicely formatted str.
Raises:
MissingAnnotationError: If the ``weak_labels`` do not contain annotated records.
"""
try:
import sklearn
except ModuleNotFoundError:
raise ModuleNotFoundError(
"'sklearn' must be installed to compute the metrics! "
"You can install 'sklearn' with the command: `pip install scikit-learn`"
)
from sklearn.metrics import classification_report
wl_matrix = self._weak_labels.matrix(has_annotation=True)
if isinstance(self._weak_labels, WeakMultiLabels):
probabilities = self._compute_multi_label_probs(wl_matrix)
annotation, prediction = self._score_multi_label(probabilities)
target_names = self._weak_labels.labels
else:
if isinstance(tie_break_policy, str):
tie_break_policy = TieBreakPolicy(tie_break_policy)
probabilities = self._compute_single_label_probs(wl_matrix)
annotation, prediction = self._score_single_label(
probabilities, tie_break_policy
)
target_names = self._weak_labels.labels[: annotation.max() + 1]
return classification_report(
annotation,
prediction,
target_names=target_names,
output_dict=not output_str,
)
def _score_single_label(
self, probabilities: np.ndarray, tie_break_policy: TieBreakPolicy
) -> Tuple[np.ndarray, np.ndarray]:
"""Helper method to compute scores for single-label classifications.
Args:
probabilities: The probabilities.
tie_break_policy: Policy to break ties. You can choose among two policies:
- `abstain`: Exclude from scores.
- `random`: randomly choose among tied option using deterministic hash.
The last policy can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
Returns:
A tuple of the annotation and prediction array.
"""
# 1.e-8 is taken from the abs tolerance of np.isclose
is_max = (
np.abs(probabilities.max(axis=1, keepdims=True) - probabilities) < 1.0e-8
)
is_tie = is_max.sum(axis=1) > 1
prediction = np.argmax(is_max, axis=1)
# we need to transform the indexes!
annotation = np.array(
[
self._weak_labels.labels.index(self._weak_labels.int2label[i])
for i in self._weak_labels.annotation()
],
dtype=np.short,
)
if not is_tie.any():
pass
# resolve ties
elif tie_break_policy is TieBreakPolicy.ABSTAIN:
prediction, annotation = prediction[~is_tie], annotation[~is_tie]
elif tie_break_policy is TieBreakPolicy.RANDOM:
for i in np.nonzero(is_tie)[0]:
equal_prob_idx = np.nonzero(is_max[i])[0]
random_idx = int(hashlib.sha1(f"{i}".encode()).hexdigest(), 16) % len(
equal_prob_idx
)
prediction[i] = equal_prob_idx[random_idx]
else:
raise NotImplementedError(
f"The tie break policy '{tie_break_policy.value}' is not implemented for MajorityVoter!"
)
return annotation, prediction
def _score_multi_label(
self, probabilities: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""Helper method to compute scores for multi-label classifications.
Args:
probabilities: The probabilities.
Returns:
A tuple of the annotation and prediction array.
"""
prediction = np.where(probabilities > 0.5, 1, 0)
is_abstain = np.isnan(probabilities).all(axis=1)
prediction, annotation = (
prediction[~is_abstain],
self._weak_labels.annotation()[~is_abstain],
)
return annotation, prediction
class Snorkel(LabelModel):
"""The label model by `Snorkel <https://github.com/snorkel-team/snorkel/>`__.
.. note:: It is not suited for multi-label classification and does not support it!
Args:
weak_labels: A `WeakLabels` object containing the weak labels and records.
verbose: Whether to show print statements
device: What device to place the model on ('cpu' or 'cuda:0', for example).
Passed on to the `torch.Tensor.to()` calls.
Examples:
>>> from rubrix.labeling.text_classification import WeakLabels
>>> weak_labels = WeakLabels(dataset="my_dataset")
>>> label_model = Snorkel(weak_labels)
>>> label_model.fit()
>>> records = label_model.predict()
"""
def __init__(
self, weak_labels: WeakLabels, verbose: bool = True, device: str = "cpu"
):
try:
import snorkel
except ModuleNotFoundError:
raise ModuleNotFoundError(
"'snorkel' must be installed to use the `Snorkel` label model! "
"You can install 'snorkel' with the command: `pip install snorkel`"
)
else:
from snorkel.labeling.model import LabelModel as SnorkelLabelModel
super().__init__(weak_labels)
# Check if we need to remap the weak labels to int mapping
# Snorkel expects the abstain id to be -1 and the rest of the labels to be sequential
if self._weak_labels.label2int[None] != -1 or sorted(
self._weak_labels.int2label
) != list(range(-1, self._weak_labels.cardinality)):
self._need_remap = True
self._weaklabelsInt2snorkelInt = {
self._weak_labels.label2int[label]: i
for i, label in enumerate([None] + self._weak_labels.labels, -1)
}
else:
self._need_remap = False
self._weaklabelsInt2snorkelInt = {
i: i for i in range(-1, self._weak_labels.cardinality)
}
self._snorkelInt2weaklabelsInt = {
val: key for key, val in self._weaklabelsInt2snorkelInt.items()
}
# instantiate Snorkel's label model
self._model = SnorkelLabelModel(
cardinality=self._weak_labels.cardinality,
verbose=verbose,
device=device,
)
def fit(self, include_annotated_records: bool = False, **kwargs):
"""Fits the label model.
Args:
include_annotated_records: Whether to include annotated records in the fitting.
**kwargs: Additional kwargs are passed on to Snorkel's
`fit method <https://snorkel.readthedocs.io/en/latest/packages/_autosummary/labeling/snorkel.labeling.model.label_model.LabelModel.html#snorkel.labeling.model.label_model.LabelModel.fit>`__.
They must not contain ``L_train``, the label matrix is provided automatically.
"""
if "L_train" in kwargs:
raise ValueError(
"Your kwargs must not contain 'L_train', it is provided automatically."
)
l_train = self._weak_labels.matrix(
has_annotation=None if include_annotated_records else False
)
if self._need_remap:
l_train = self._copy_and_remap(l_train)
self._model.fit(L_train=l_train, **kwargs)
def _copy_and_remap(self, matrix_or_array: np.ndarray):
"""Helper function to copy and remap the weak label matrix or annotation array to be compatible with snorkel.
Snorkel expects the abstain id to be -1 and the rest of the labels to be sequential.
Args:
matrix_or_array: The original weak label matrix or annotation array
Returns:
A copy of the weak label matrix, remapped to match snorkel's requirements.
"""
matrix_or_array = matrix_or_array.copy()
# save masks for swapping
label_masks = {}
# compute masks
for idx in self._weaklabelsInt2snorkelInt:
label_masks[idx] = matrix_or_array == idx
# swap integers
for idx in self._weaklabelsInt2snorkelInt:
matrix_or_array[label_masks[idx]] = self._weaklabelsInt2snorkelInt[idx]
return matrix_or_array
def predict(
self,
include_annotated_records: bool = False,
include_abstentions: bool = False,
prediction_agent: str = "Snorkel",
tie_break_policy: Union[TieBreakPolicy, str] = "abstain",
) -> DatasetForTextClassification:
"""Returns a list of records that contain the predictions of the label model
Args:
include_annotated_records: Whether to include annotated records.
include_abstentions: Whether to include records in the output, for which the label model abstained.
prediction_agent: String used for the ``prediction_agent`` in the returned records.
tie_break_policy: Policy to break ties. You can choose among three policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash
- `true-random`: randomly choose among the tied options. NOTE: repeated runs may have slightly different results due to differences in broken ties
The last two policies can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
Returns:
A dataset of records that include the predictions of the label model.
"""
if isinstance(tie_break_policy, str):
tie_break_policy = TieBreakPolicy(tie_break_policy)
l_pred = self._weak_labels.matrix(
has_annotation=None if include_annotated_records else False
)
if self._need_remap:
l_pred = self._copy_and_remap(l_pred)
# get predictions and probabilities
predictions, probabilities = self._model.predict(
L=l_pred,
return_probs=True,
tie_break_policy=tie_break_policy.value,
)
# add predictions to records
records_with_prediction = []
for rec, pred, prob in zip(
self._weak_labels.records(
has_annotation=None if include_annotated_records else False
),
predictions,
probabilities,
):
if not include_abstentions and pred == -1:
continue
records_with_prediction.append(rec.copy(deep=True))
# set predictions to None if model abstained
pred_for_rec = None
if pred != -1:
# If we have a tie, increase a bit the probability of the random winner (see tie_break_policy)
# 1.e-8 is taken from the abs tolerance of np.isclose
equal_prob_idx = np.nonzero(np.abs(prob.max() - prob) < 1.0e-8)[0]
if len(equal_prob_idx) > 1:
for idx in equal_prob_idx:
if idx == pred:
prob[idx] += self._PROBABILITY_INCREASE_ON_TIE_BREAK
else:
prob[idx] -= self._PROBABILITY_INCREASE_ON_TIE_BREAK / (
len(equal_prob_idx) - 1
)
pred_for_rec = [
(
self._weak_labels.int2label[
self._snorkelInt2weaklabelsInt[snorkel_idx]
],
prob[snorkel_idx],
)
for snorkel_idx in np.argsort(prob)[::-1]
]
records_with_prediction[-1].prediction = pred_for_rec
records_with_prediction[-1].prediction_agent = prediction_agent
return DatasetForTextClassification(records_with_prediction)
def score(
self,
tie_break_policy: Union[TieBreakPolicy, str] = "abstain",
output_str: bool = False,
) -> Union[Dict[str, float], str]:
"""Returns some scores/metrics of the label model with respect to the annotated records.
The metrics are:
- accuracy
- micro/macro averages for precision, recall and f1
- precision, recall, f1 and support for each label
For more details about the metrics, check out the
`sklearn docs <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html#sklearn-metrics-precision-recall-fscore-support>`__.
.. note:: Metrics are only calculated over non-abstained predictions!
Args:
tie_break_policy: Policy to break ties. You can choose among three policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash
- `true-random`: randomly choose among the tied options. NOTE: repeated runs may have slightly different results due to differences in broken ties
The last two policies can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
output_str: If True, return output as nicely formatted string.
Returns:
The scores/metrics in a dictionary or as a nicely formatted str.
Raises:
MissingAnnotationError: If the ``weak_labels`` do not contain annotated records.
"""
from sklearn.metrics import classification_report
if isinstance(tie_break_policy, str):
tie_break_policy = TieBreakPolicy(tie_break_policy)
if self._weak_labels.annotation().size == 0:
raise MissingAnnotationError(
"You need annotated records to compute scores/metrics for your label model."
)
l_pred = self._weak_labels.matrix(has_annotation=True)
if self._need_remap:
l_pred = self._copy_and_remap(l_pred)
# get predictions and probabilities
predictions, probabilities = self._model.predict(
L=l_pred,
return_probs=True,
tie_break_policy=tie_break_policy.value,
)
# metrics are only calculated for non-abstained data points
idx = predictions != -1
annotation = self._weak_labels.annotation()[idx]
if self._need_remap:
annotation = self._copy_and_remap(annotation)
return classification_report(
annotation,
predictions[idx],
target_names=self._weak_labels.labels[: annotation.max() + 1],
output_dict=not output_str,
)
class FlyingSquid(LabelModel):
"""The label model by `FlyingSquid <https://github.com/HazyResearch/flyingsquid>`__.
.. note:: It is not suited for multi-label classification and does not support it!
Args:
weak_labels: A `WeakLabels` object containing the weak labels and records.
**kwargs: Passed on to the init of the FlyingSquid's
`LabelModel <https://github.com/HazyResearch/flyingsquid/blob/master/flyingsquid/label_model.py#L18>`__.
Examples:
>>> from rubrix.labeling.text_classification import WeakLabels
>>> weak_labels = WeakLabels(dataset="my_dataset")
>>> label_model = FlyingSquid(weak_labels)
>>> label_model.fit()
>>> records = label_model.predict()
"""
def __init__(self, weak_labels: WeakLabels, **kwargs):
try:
import flyingsquid
import pgmpy
except ModuleNotFoundError:
raise ModuleNotFoundError(
"'flyingsquid' must be installed to use the `FlyingSquid` label model! "
"You can install 'flyingsquid' with the command: `pip install pgmpy flyingsquid`"
)
else:
from flyingsquid.label_model import LabelModel as FlyingSquidLabelModel
self._FlyingSquidLabelModel = FlyingSquidLabelModel
super().__init__(weak_labels)
if len(self._weak_labels.rules) < 3:
raise TooFewRulesError(
"The FlyingSquid label model needs at least three (independent) rules!"
)
if "m" in kwargs:
raise ValueError(
"Your kwargs must not contain 'm', it is provided automatically."
)
self._init_kwargs = kwargs
self._models: List[FlyingSquidLabelModel] = []
def fit(self, include_annotated_records: bool = False, **kwargs):
"""Fits the label model.
Args:
include_annotated_records: Whether to include annotated records in the fitting.
**kwargs: Passed on to the FlyingSquid's
`LabelModel.fit() <https://github.com/HazyResearch/flyingsquid/blob/master/flyingsquid/label_model.py#L320>`__
method.
"""
wl_matrix = self._weak_labels.matrix(
has_annotation=None if include_annotated_records else False
)
models = []
# create a label model for each label (except for binary classification)
# much of the implementation is taken from wrench:
# https://github.com/JieyuZ2/wrench/blob/main/wrench/labelmodel/flyingsquid.py
# If binary, we only need one model
for i in range(
1 if self._weak_labels.cardinality == 2 else self._weak_labels.cardinality
):
model = self._FlyingSquidLabelModel(
m=len(self._weak_labels.rules), **self._init_kwargs
)
wl_matrix_i = self._copy_and_transform_wl_matrix(wl_matrix, i)
model.fit(L_train=wl_matrix_i, **kwargs)
models.append(model)
self._models = models
def _copy_and_transform_wl_matrix(self, weak_label_matrix: np.ndarray, i: int):
"""Helper function to copy and transform the weak label matrix with respect to a target label.
FlyingSquid expects the matrix to contain -1, 0 and 1, which are mapped the following way:
- target label: -1
- abstain label: 0
- other label: 1
Args:
weak_label_matrix: The original weak label matrix
i: Index of the target label
Returns:
A copy of the weak label matrix, transformed with respect to the target label.
"""
wl_matrix_i = weak_label_matrix.copy()
target_mask = (
wl_matrix_i == self._weak_labels.label2int[self._weak_labels.labels[i]]
)
abstain_mask = wl_matrix_i == self._weak_labels.label2int[None]
other_mask = (~target_mask) & (~abstain_mask)
wl_matrix_i[target_mask] = -1
wl_matrix_i[abstain_mask] = 0
wl_matrix_i[other_mask] = 1
return wl_matrix_i
def predict(
self,
include_annotated_records: bool = False,
include_abstentions: bool = False,
prediction_agent: str = "FlyingSquid",
verbose: bool = True,
tie_break_policy: Union[TieBreakPolicy, str] = "abstain",
) -> DatasetForTextClassification:
"""Applies the label model.
Args:
include_annotated_records: Whether to include annotated records.
include_abstentions: Whether to include records in the output, for which the label model abstained.
prediction_agent: String used for the ``prediction_agent`` in the returned records.
verbose: If True, print out messages of the progress to stderr.
tie_break_policy: Policy to break ties. You can choose among two policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash
The last policy can introduce quite a bit of noise, especially when the tie is among many labels,
as is the case when all the labeling functions (rules) abstained.
Returns:
A dataset of records that include the predictions of the label model.
Raises:
NotFittedError: If the label model was still not fitted.
"""
if isinstance(tie_break_policy, str):
tie_break_policy = TieBreakPolicy(tie_break_policy)
wl_matrix = self._weak_labels.matrix(
has_annotation=None if include_annotated_records else False
)
probabilities = self._predict(wl_matrix, verbose)
# add predictions to records
records_with_prediction = []
for i, prob, rec in zip(
range(len(probabilities)),
probabilities,
self._weak_labels.records(
has_annotation=None if include_annotated_records else False
),
):
# Check if model abstains, that is if the highest probability is assigned to more than one label
# 1.e-8 is taken from the abs tolerance of np.isclose
equal_prob_idx = np.nonzero(np.abs(prob.max() - prob) < 1.0e-8)[0]
tie = False
if len(equal_prob_idx) > 1:
tie = True
# maybe skip record
if not include_abstentions and (
tie and tie_break_policy is TieBreakPolicy.ABSTAIN
):
continue
if not tie:
pred_for_rec = [
(self._weak_labels.labels[i], prob[i])
for i in np.argsort(prob)[::-1]
]
# resolve ties following the tie break policy
elif tie_break_policy is TieBreakPolicy.ABSTAIN:
pred_for_rec = None
elif tie_break_policy is TieBreakPolicy.RANDOM:
random_idx = int(hashlib.sha1(f"{i}".encode()).hexdigest(), 16) % len(
equal_prob_idx
)
for idx in equal_prob_idx:
if idx == random_idx:
prob[idx] += self._PROBABILITY_INCREASE_ON_TIE_BREAK
else:
prob[idx] -= self._PROBABILITY_INCREASE_ON_TIE_BREAK / (
len(equal_prob_idx) - 1
)
pred_for_rec = [
(self._weak_labels.labels[i], prob[i])
for i in np.argsort(prob)[::-1]
]
else:
raise NotImplementedError(
f"The tie break policy '{tie_break_policy.value}' is not implemented for FlyingSquid!"
)
records_with_prediction.append(rec.copy(deep=True))
records_with_prediction[-1].prediction = pred_for_rec
records_with_prediction[-1].prediction_agent = prediction_agent
return DatasetForTextClassification(records_with_prediction)
def _predict(self, weak_label_matrix: np.ndarray, verbose: bool) -> np.ndarray:
"""Helper function that calls the ``predict_proba`` method of FlyingSquid's label model.
Much of the implementation is taken from wrench:
https://github.com/JieyuZ2/wrench/blob/main/wrench/labelmodel/flyingsquid.py
Args:
weak_label_matrix: The weak label matrix.
verbose: If True, print out messages of the progress to stderr.
Returns:
A matrix containing the probability for each label and record.
Raises:
NotFittedError: If the label model was still not fitted.
"""
if not self._models:
raise NotFittedError(
"This FlyingSquid instance is not fitted yet. Call `fit` before using this model."
)
# create predictions for each label
if self._weak_labels.cardinality > 2:
probas = np.zeros((len(weak_label_matrix), self._weak_labels.cardinality))
for i in range(self._weak_labels.cardinality):
wl_matrix_i = self._copy_and_transform_wl_matrix(weak_label_matrix, i)
probas[:, i] = self._models[i].predict_proba(
L_matrix=wl_matrix_i, verbose=verbose
)[:, 0]
probas = np.nan_to_num(probas, nan=-np.inf) # handle NaN
probas = np.exp(probas) / np.sum(np.exp(probas), axis=1, keepdims=True)
# if binary, we only have one model
else:
wl_matrix_i = self._copy_and_transform_wl_matrix(weak_label_matrix, 0)
probas = self._models[0].predict_proba(
L_matrix=wl_matrix_i, verbose=verbose
)
return probas
def score(
self,
tie_break_policy: Union[TieBreakPolicy, str] = "abstain",
verbose: bool = False,
output_str: bool = False,
) -> Union[Dict[str, float], str]:
"""Returns some scores/metrics of the label model with respect to the annotated records.
The metrics are:
- accuracy
- micro/macro averages for precision, recall and f1
- precision, recall, f1 and support for each label
For more details about the metrics, check out the
`sklearn docs <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html#sklearn-metrics-precision-recall-fscore-support>`__.
.. note:: Metrics are only calculated over non-abstained predictions!
Args:
tie_break_policy: Policy to break ties. You can choose among two policies:
- `abstain`: Do not provide any prediction
- `random`: randomly choose among tied option using deterministic hash