# Fine-Tune for MultiClass or MultiLabel-MultiClass

**URL:** <https://discuss.huggingface.co/t/fine-tune-for-multiclass-or-multilabel-multiclass/4035>\
**Category:** Models\
**Created:** [February 27, 2021, 12:10am UTC](https://discuss.huggingface.co/t/fine-tune-for-multiclass-or-multilabel-multiclass/4035 "2021-02-27T00:10:34Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![lewtun](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/lewtun/32/30995_2.png) [@lewtun](https://discuss.huggingface.co/u/lewtun)\
**Post date:** [March 4, 2021, 12:56pm UTC](https://discuss.huggingface.co/t/fine-tune-for-multiclass-or-multilabel-multiclass/4035/8 "2021-03-04T12:56:23Z")

</div>

Hi @dikster99, I had a closer look at the multi-label example I linked to and see that it’s more complicated than it needs to be because:

- `transformers` now has a `Trainer` class that dramatically simplifies the training / evaluation loops.
- the `datasets` library is a much better way to prepare the data and works great with the `Trainer`

To implement multi-label classification, the main thing you need to do is override the `forward` method of `BertForSequenceClassification` to compute the loss with a sigmoid instead of softmax applied to the logits. In PyTorch it looks something like

```auto
class BertForMultilabelSequenceClassification(BertForSequenceClassification):
    def __init__ (self, config):
      super(). __init__ (config)

    def forward(self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,
        output_attentions=None,
        output_hidden_states=None,
        return_dict=None):
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        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,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict)

        pooled_output = outputs[1]
        pooled_output = self.dropout(pooled_output)
        logits = self.classifier(pooled_output)

        loss = None
        if labels is not None:
            loss_fct = torch.nn.BCEWithLogitsLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), 
                            labels.float().view(-1, self.num_labels))

        if not return_dict:
            output = (logits,) + outputs[2:]
            return ((loss,) + output) if loss is not None else output

        return SequenceClassifierOutput(loss=loss,
            logits=logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions)

```

where the only thing that I’ve really changed are these two lines

```auto
loss_fct = torch.nn.BCEWithLogitsLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.float().view(-1, self.num_labels))

```

You can probably adapt the TensorFlow code in a similar fashion (I haven’t used TF in years so can’t be much help there 🙂).

There are some other things needed (e.g. the metrics), so I put together a hacky notebook here that you can use as a template to get started: [https://colab.research.google.com/drive/1X7l8pM6t4VLqxQVJ23ssIxmrsc4Kpc5q?usp=sharing](https://colab.research.google.com/drive/1X7l8pM6t4VLqxQVJ23ssIxmrsc4Kpc5q?usp=sharing)

---

_[View the full topic](https://discuss.huggingface.co/t/fine-tune-for-multiclass-or-multilabel-multiclass/4035)._
