tugce
tugce

Reputation: 71

How to get probability of each image belonging to a class

I am new to Pytorch. I trained and tested a linear classifier (nn.Linear) with an image data set that has 8 categories with the batch_size = 35. While testing, I wanted to see what is the probability of the given image belonging to any of these 8 classes. That is why I printed output.data variable. But these numbers are above 1 and they are not summing into 1. (I attached the testing code) So, my question is what does those numbers mean?

Thanks!

correct = 0
total = 0
with torch.no_grad():
    for data in dataloaders['test']:
        images, labels = data[0].to(device), data[1].to(device)
        outputs = model(images)
        print(outputs.data)

        _, predicted = torch.max(outputs.data, 1)
        print(predicted)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 4000 test images: %d %%' % (
100 * correct / total))

Upvotes: 0

Views: 2238

Answers (1)

Szymon Maszke
Szymon Maszke

Reputation: 24681

You get logits as output of your neural network.

Use torch.nn.Softmax on output to squash the values into (0,1) range.

BTW. You network should output logits as pytorch's losses (torch.nn.CrossEntropyLoss in this case) are designed to work with them while being numerically stable.

Upvotes: 1

Related Questions