'TFCamemBERT model trains but no results in test
Currently I am working on Named Entity Recognition in the medical domain using Camembert, precisely using the model: TFCamembert.
However I have some problems with the fine-tuning of the model for my task as I am using a private dataset not available on Hugging Face.
The data is divided into text files and annotation files. The text file contains for example:
Le cas présenté concerne un homme âgé de 61 ans (71 kg, 172 cm, soit un indice de masse corporelle de 23,9 kg/m²) admissible à une transplantation pulmonaire en raison d’une insuffisance respiratoire chronique terminale sur emphysème post-tabagique, sous oxygénothérapie continue (1 L/min) et ventilation non invasive nocturne. Il présente, comme principaux antécédents, une dyslipidémie, une hypertension artérielle et un tabagisme sevré estimé à 21 paquets-années (facteurs de risque cardiovasculaires). Le bilan préopératoire a révélé une hypertension artérielle pulmonaire essentiellement postcapillaire conduisant à l’ajout du périndopril (2 mg par jour) et du furosémide (40 mg par jour). La mise en évidence d’un Elispot (enzyme-linked immunospot) positif pour la tuberculose a motivé l’introduction d’un traitement prophylactique par l’association rifampicine-isoniazide (600-300 mg par jour) pour une durée de trois mois.
Deux mois après le bilan préopératoire, le patient a bénéficié d’une transplantation mono-pulmonaire gauche sans dysfonction primaire du greffon5,6. Le donneur et le receveur présentaient tous deux un statut sérologique positif pour cytomegalovirus (CMV) et Epstein Barr Virus (EBV). Une sérologie positive de la toxoplasmose a été mise en évidence uniquement chez le receveur. Le traitement immunosuppresseur d’induction associait la méthylprednisolone (500 mg à jour 0 et 375 mg à jour +1 post-transplantation) et le basiliximab, anticorps monoclonal dirigé contre l’interleukine-2 (20 mg à jour 0 et jour +4 posttransplantation). À partir de jour +2 post-transplantation, l’immunosuppression a été maintenue par une trithérapie par voie orale comprenant le tacrolimus à une posologie initiale de 5 mg par jour, le mofétil mycophénolate (MMF) 2000 mg par jour et la prednisone 20 mg par jour. Les traitements associés sont présentés dans le tableau I.
L’évolution est marquée par la survenue, au jour +5 posttransplantation, d’une dégradation respiratoire sur œdème pulmonaire gauche de reperfusion, avec possible participation cardiogénique. Le rejet aigu de grade III, évoqué par la présence d’infiltrats lymphocytaires aux biopsies transbronchiques, a été confirmé par l’anatomopathologie.
While the annotation file looks like:
T1 genre 28 33 homme
T2 age 41 47 61 ans
A1 genre T1 masculin
T3 origine 127 326 une transplantation pulmonaire en raison d’une insuffisance respiratoire chronique terminale sur emphysème post-tabagique, sous oxygénothérapie continue (1 L/min) et ventilation non invasive nocturne
T4 issue 1962 2104 une dégradation respiratoire sur œdème pulmonaire gauche de reperfusion, avec possible participation cardiogénique. Le rejet aigu de grade III
A2 issue T4 détérioration
More details about the prepossessing of the data can be found in this notebook.
The thing is that once I finish the training, I try to run the model on test data it doesn't work at all. I can't figure out where is the problem as the train and test data have the same format.
from datasets import load_metric
import numpy as np
metric = load_metric("seqeval")
def evaluate(model, dataset, ner_labels):
all_predictions = []
all_labels = []
for batch in dataset:
logits = model.predict(batch)["logits"]
labels = batch["labels"]
predictions = np.argmax(logits, axis = -1)
for prediction, label in zip(predictions, labels):
for predicted_idx, label_idx in zip(prediction, label):
if label_idx == -100:
continue
all_predictions.append(ner_labels[predicted_idx])
all_labels.append(ner_labels[label_idx])
return metric.compute(predictions=[all_predictions], references=[all_labels])
results = evaluate(model, test_dataset, ner_labels=list(model.config.id2label.values()))
results
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-40-d7e10156347b> in <module>()
31 return metric.compute(predictions=[all_predictions], references=[all_labels])
32
---> 33 results = evaluate(model, test_dataset, ner_labels=list(model.config.id2label.values()))
2 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
1127 except Exception as e: # pylint:disable=broad-except
1128 if hasattr(e, "ag_error_metadata"):
-> 1129 raise e.ag_error_metadata.to_exception(e)
1130 else:
1131 raise
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1621, in predict_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1611, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1604, in run_step **
outputs = model.predict_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1572, in predict_step
return self(x, training=False)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
ValueError: Exception encountered when calling layer "tf_camembert_for_token_classification" (type TFCamembertForTokenClassification).
in user code:
File "/usr/local/lib/python3.7/dist-packages/transformers/models/roberta/modeling_tf_roberta.py", line 1681, in call *
outputs = self.roberta(
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler **
raise e.with_traceback(filtered_tb) from None
ValueError: Exception encountered when calling layer "roberta" (type TFRobertaMainLayer).
in user code:
File "/usr/local/lib/python3.7/dist-packages/transformers/models/roberta/modeling_tf_roberta.py", line 660, in call *
batch_size, seq_length = input_shape
ValueError: not enough values to unpack (expected 2, got 1)
Call arguments received:
• input_ids=tf.Tensor(shape=(32,), dtype=int32)
• attention_mask=tf.Tensor(shape=(32,), dtype=int32)
• token_type_ids=None
• position_ids=None
• head_mask=None
• inputs_embeds=None
• encoder_hidden_states=None
• encoder_attention_mask=None
• past_key_values=None
• use_cache=None
• output_attentions=False
• output_hidden_states=False
• return_dict=True
• training=False
• kwargs=<class 'inspect._empty'>
Call arguments received:
• input_ids={'input_ids': 'tf.Tensor(shape=(32,), dtype=int32)', 'attention_mask': 'tf.Tensor(shape=(32,), dtype=int32)', 'labels': 'tf.Tensor(shape=(32,), dtype=int32)'}
• attention_mask=None
• token_type_ids=None
• position_ids=None
• head_mask=None
• inputs_embeds=None
• output_attentions=None
• output_hidden_states=None
• return_dict=None
• labels=None
• training=False
• kwargs=<class 'inspect._empty'>
When the test used to work, model.predict() accepted data batches normally, but the results were all 0 even though the internal loss in the training phase was deacreasing.
{'age': {'f1': 0.0, 'number': 145, 'precision': 0.0, 'recall': 0.0},
'anatomie': {'f1': 0.0, 'number': 952, 'precision': 0.0, 'recall': 0.0},
'date': {'f1': 0.0, 'number': 15, 'precision': 0.0, 'recall': 0.0},
'dose': {'f1': 0.0, 'number': 27, 'precision': 0.0, 'recall': 0.0},
'duree': {'f1': 0.0, 'number': 2, 'precision': 0.0, 'recall': 0.0},
'examen': {'f1': 0.0, 'number': 553, 'precision': 0.0, 'recall': 0.0},
'frequence': {'f1': 0.0, 'number': 8, 'precision': 0.0, 'recall': 0.0},
'genre': {'f1': 0.0, 'number': 146, 'precision': 0.0, 'recall': 0.0},
'mode': {'f1': 0.0, 'number': 79, 'precision': 0.0, 'recall': 0.0},
'moment': {'f1': 0.0, 'number': 23, 'precision': 0.0, 'recall': 0.0},
'origine': {'f1': 0.0, 'number': 11, 'precision': 0.0, 'recall': 0.0},
'overall_accuracy': 0.9089205003328545,
'overall_f1': 0.0,
'overall_precision': 0.0,
'overall_recall': 0.0,
'pathologie': {'f1': 0.0, 'number': 162, 'precision': 0.0, 'recall': 0.0},
'sosy': {'f1': 0.0, 'number': 439, 'precision': 0.0, 'recall': 0.0},
'substance': {'f1': 0.0, 'number': 633, 'precision': 0.0, 'recall': 0.0},
'traitement': {'f1': 0.0, 'number': 205, 'precision': 0.0, 'recall': 0.0},
'valeur': {'f1': 0.0, 'number': 192, 'precision': 0.0, 'recall': 0.0}}
Any clues to solve this gradient issue? Thanks in advance!
Solution 1:[1]
I would first verify on a single sentence whether the model gives reasonable predictions after training, as follows:
from transformers import BertTokenizer, TFBertForTokenClassification
import numpy as np
tokenizer = BertTokenizer.from_pretrained("jplu/tf-camembert-base")
model = TFBertForTokenClassification.from_pretrained("path_to_your_model_weights_and_config_json")
inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
input_ids = inputs["input_ids"]
outputs = model(inputs)
logits = outputs.logits
predictions = np.argmax(logits, axis=-1).squeeze()
predicted_labels = [model.config.id2label[id] for id in predictions if id != -100]
print(predicted_labels)
Here I assume you have set the id2label attribute of the model's configuration.
You can also print the tokens along with the predictions:
import tensorflow as tf
for id, label in zip(tf.squeeze(input_ids), predicted_labels):
print(tokenizer.decode([id]), label)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
