Multi label classification accuracy calculation

Hello, I have a dataset with images and a tensor of multi labels in one hot encoding. During the training I am not able to calculate the accuracy, when I print the predictions for the batch what I am getting is a single number with the id of the label (Ex: 54) but I am expecting to get a one hot tensor with more than one class activated. I am doing something very wrong.

This is my training loop:

for _ in range(cfg.num_rounds):
    round_count = round_count+1
    epoch_count = 0
    for _ in range(cfg.num_epochs):
        epoch_count = epoch_count+1
        train_metric = evaluate.load('roc_auc', 'multilabel')
        running_loss = 0.
        for batch in trainloader:
            optimizer.zero_grad()
            outputs = model(batch["image_name"].to(device))
            labels = batch["image_labels"].to(device)
            loss = criterion(outputs, labels)

            loss.backward()
            optimizer.step()

            total += labels.size(0)
            correct += (torch.max(outputs.data, 1)[1] == labels).sum().item()

        # loss and metric over 1 epoch
print("loss: ", loss.item(), "accuracy: ", correct / total)

And this is my NN:

class ResNet(nn.Module):
    """Model (simple CNN adapted from 'PyTorch: A 60 Minute Blitz')"""

    def __init__(self) -> None:
        super(ResNet, self).__init__()
        self.body = resnet34()
        self.head = nn.Sequential(
            BasicBlock(512, 512),
            nn.AdaptiveAvgPool2d((1, 1)),
            nn.Flatten(),
            nn.Linear(512, 179),
        )
        self.body = nn.Sequential(*list(self.body.children())[:-2])
        body_layer4 = list(self.body.children())[-1]
        self.body = nn.Sequential(*list(self.body.children())[:-1])
        self.body.layer4 = nn.Sequential(*list(body_layer4.children())[:-1])

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Forward inputs through the model."""
        x = self.body(x)
        return self.head(x)

“image_name” is the PIL image and the “image_labels” are the 179 classes in one hot.

Could you help me?

Thank you!

Hi,
I think the problem is mostly in

correct += (torch.max(outputs.data, 1)[1] == labels).sum().item()

your last layer outputs 1 number per label (between -inf and +inf), which corresponds to the score that your model assigns to each label. Then, your torch.max(outputs.data, 1)[1] computes which label has the highest score for each element of the batch. This is already not what you want, since you want to keep multiple labels per output.

There are several ways of deciding which labels are considered positive by your model. You could for example decide that every output > 0 is positive:

preds = (outputs > 0).long()
correct += (preds == labels).all(dim=1).sum().item()
total += labels.size(0)

This means that a prediction is considered correct only if all of its 179 labels are predicted correctly. So the accuracy will be the number of samples for which all 179 labels are correctly predicted (I would thus assume you’ll get an accuracy of 0 for a long time before your model starts to be good enough).

Maybe the accuracy will become a bit more informative if it’s computed at the label granularity:

correct += (preds == labels).sum().item()
total += labels.numel()

This will instead compute the number of correct labels divided by the total number of labels to predict.

Hi, Valerian,

That was it, thank you very much I was having a hard time understanding the issue.

Now I can go to the next issue hahaha.