Data format for BertForSequenceClassification with num_labels > 2
Hi,I have a multilabel task (num_labels=8) and I want to use BertForSequenceClassification using Trainer to train the model.But I get the following error:ValueError: Expected input batch_size (8) to match target batch_size (64).I assume that the problem is the data format of the labels. Currently, my label is a 8-dim list (e.g., [1,0,0,0,0,1,0,0]).What is the right format for the label data?Here my code:class EmotionDataset(torch.utils.data.Dataset):definit(self, encodings, labels):self.encodings = encodingsself.labels = labelsdef __getitem__(self, idx):
    item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
    item['labels'] = torch.tensor(self.labels[idx])
    return item

def __len__(self):
    return len(self.labels)MODEL_NAME = ‘dbmdz/bert-base-german-uncased’tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = BertForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=8)tokenize datadataset_train = Dataset.from_pandas(df_train)train_encodings = tokenizer(dataset_train['text], truncation=True, padding=True)train_dataset = EmotionDataset(train_encodings, dataset_train['label])training_args = TrainingArguments(output_dir=‘./results’,          # output directorynum_train_epochs=1,              # total # of training epochsper_device_train_batch_size=8,  # batch size per device during trainingper_device_eval_batch_size=32,   # batch size for evaluationwarmup_steps=500,                # number of warmup steps for learning rate schedulerweight_decay=0.01,               # strength of weight decaylogging_dir=‘./logs’,            # directory for storing logs)trainer = Trainer(model=model,                         # the instantiatedTransformers model to be trainedargs=training_args,                  # training arguments, defined abovetrain_dataset=train_dataset,         # training dataseteval_dataset=test_dataset            # evaluation dataset)_ = trainer.train()trainer.evaluate()Thanks,Max
2021-03-04T17:29:12Z
Hi@maxpower, I think the format of your dataset is fine but I think you have to change the model’s loss function to use a sigmoid instead of a softmax on the logits (i.e.BCEWithLogitsLoss). You can see a skeleton + hacky Colab in this thread:Fine-Tune for MultiClass or MultiLabel-MultiClass - #8 by lewtun
2021-03-05T09:46:16Z
Perfect, it works. Thanks so much!
2021-03-05T10:13:01Z
FYI I just posted a more elegant solution in the thread that just subclassesTrainerand overrides thecompute_lossfunction (you can see it in action in the Colab notebook too)
2021-07-21T17:01:48Z
Hi lewtun,Thanks for your help so far.But I’m having issues getting it to work for multiclass classification.The custommetric in the notebook only works for multilabel classification.Is there anything I need to do please?
2021-08-02T18:14:35Z
hey@opeyfor ordinary multiclass classification you can follow the official tutorialhereor just run one of the scripts in the examplesherehope that helps!