Delete bibert_multitask_classification.py
Browse files
bibert_multitask_classification.py
DELETED
|
@@ -1,53 +0,0 @@
|
|
| 1 |
-
from transformers import Pipeline
|
| 2 |
-
import numpy as np
|
| 3 |
-
import torch
|
| 4 |
-
|
| 5 |
-
def softmax(_outputs):
|
| 6 |
-
maxes = np.max(_outputs, axis=-1, keepdims=True)
|
| 7 |
-
shifted_exp = np.exp(_outputs - maxes)
|
| 8 |
-
return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
|
| 9 |
-
|
| 10 |
-
class BiBert_MultiTaskPipeline(Pipeline):
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def _sanitize_parameters(self, **kwargs):
|
| 14 |
-
|
| 15 |
-
preprocess_kwargs = {}
|
| 16 |
-
if "task_id" in kwargs:
|
| 17 |
-
preprocess_kwargs["task_id"] = kwargs["task_id"]
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
postprocess_kwargs = {}
|
| 21 |
-
if "top_k" in kwargs:
|
| 22 |
-
postprocess_kwargs["top_k"] = kwargs["top_k"]
|
| 23 |
-
postprocess_kwargs["_legacy"] = False
|
| 24 |
-
return preprocess_kwargs, {}, postprocess_kwargs
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def preprocess(self, inputs, task_id):
|
| 29 |
-
return_tensors = self.framework
|
| 30 |
-
feature = self.tokenizer(inputs, padding = True, return_tensors=return_tensors).to(self.device)
|
| 31 |
-
task_ids = np.full(shape=1,fill_value=task_id, dtype=int)
|
| 32 |
-
feature["task_ids"] = torch.IntTensor(task_ids)
|
| 33 |
-
return feature
|
| 34 |
-
|
| 35 |
-
def _forward(self, model_inputs):
|
| 36 |
-
return self.model(**model_inputs)
|
| 37 |
-
|
| 38 |
-
def postprocess(self, model_outputs, top_k=1, _legacy=True):
|
| 39 |
-
outputs = model_outputs["logits"][0]
|
| 40 |
-
outputs = outputs.numpy()
|
| 41 |
-
scores = softmax(outputs)
|
| 42 |
-
|
| 43 |
-
if top_k == 1 and _legacy:
|
| 44 |
-
return {"label": self.model.config.id2label[scores.argmax().item()], "probability": scores.max().item()}
|
| 45 |
-
|
| 46 |
-
dict_scores = [
|
| 47 |
-
{"label": self.model.config.id2label[i], "probability": score.item()} for i, score in enumerate(scores)
|
| 48 |
-
]
|
| 49 |
-
if not _legacy:
|
| 50 |
-
dict_scores.sort(key=lambda x: x["probability"], reverse=True)
|
| 51 |
-
if top_k is not None:
|
| 52 |
-
dict_scores = dict_scores[:top_k]
|
| 53 |
-
return dict_scores
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|