-
Notifications
You must be signed in to change notification settings - Fork 0
/
multilabel.py
98 lines (82 loc) · 3.05 KB
/
multilabel.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
#########################################
# CS769 Course Project Update
# To support multi-class classification in Goemotions classification task
#########################################
import torch.nn as nn
import numpy as np
from typing import Union, Optional
from transformers import BertPreTrainedModel, BertModel
from transformers.pipelines import ArgumentHandler
from transformers import Pipeline, PreTrainedTokenizer, ModelCard
class BertForMultiLabelClassification(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.loss_fct = nn.BCEWithLogitsLoss()
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
):
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
if labels is not None:
loss = self.loss_fct(logits, labels)
outputs = (loss,) + outputs
return outputs # (loss), logits, (hidden_states), (attentions)
class MultiLabelPipeline(Pipeline):
def __init__(
self,
model: Union["PreTrainedModel", "TFPreTrainedModel"],
tokenizer: PreTrainedTokenizer,
modelcard: Optional[ModelCard] = None,
framework: Optional[str] = None,
task: str = "",
args_parser: ArgumentHandler = None,
device: int = -1,
binary_output: bool = False,
threshold: float = 0.3
):
super().__init__(
model=model,
tokenizer=tokenizer,
modelcard=modelcard,
framework=framework,
args_parser=args_parser,
device=device,
binary_output=binary_output,
task=task
)
self.threshold = threshold
def __call__(self, *args, **kwargs):
outputs = super().__call__(*args, **kwargs)
scores = 1 / (1 + np.exp(-outputs)) # Sigmoid
results = []
for item in scores:
labels = []
scores = []
for idx, s in enumerate(item):
if s > self.threshold:
labels.append(self.model.config.id2label[idx])
scores.append(s)
results.append({"labels": labels, "scores": scores})
return results