'Putting the percentage (confidence score) of the predicted class in CNN using torch

I'm trying to show the percentage of the predicted class of the image. Example: 95% that the input image is Dog.

Can someone help me to figure out the process and explain it to me, because I do not completely understand how the code below works.

class ConvNet(nn.Module):
   def __init__(self, num_classes):
       super(ConvNet, self).__init__()

    self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=3, stride=1, padding=1)

    self.bn1 = nn.BatchNorm2d(num_features=12)
    self.relu1 = nn.ReLU()
    self.pool1 = nn.MaxPool2d(kernel_size=2)

    self.conv2 = nn.Conv2d(in_channels=12, out_channels=20, kernel_size=3, stride=1, padding=1)
    self.relu2 = nn.ReLU()

    self.conv3 = nn.Conv2d(in_channels=20, out_channels=32, kernel_size=3, stride=1, padding=1)
    self.bn3 = nn.BatchNorm2d(num_features=32)
    self.relu3 = nn.ReLU()

    self.conv4 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)
    self.bn4 = nn.BatchNorm2d(num_features=64)
    self.relu4 = nn.ReLU()
    self.pool2 = nn.MaxPool2d(kernel_size=2)
    self.flat = nn.Flatten()
    self.drp = nn.Dropout(p=0.3)
    self.fc = nn.Linear(in_features=64 * 39 * 39, out_features=num_classes)

# feed forward function
def forward(self, input):
    output = self.conv1(input)
    output = self.bn1(output)
    output = self.relu1(output)

    output = self.pool1(output)

    output = self.conv2(output)
    output = self.relu2(output)

    output = self.conv3(output)
    output = self.bn3(output)
    output = self.relu3(output)
    # output = self.pool2(output)

    output = self.conv4(output)
    output = self.bn4(output)
    output = self.relu4(output)
    output = self.pool2(output)

    output = self.flat(output)

    output = output.view(-1, 64 * 39 * 39)
    output = self.drp(output)

    output = self.fc(output)

    return output

Prediction Function In this part i already able to get the prediction but i want to add the part where I can get the percentage (confidence score) of the prediction.

def prediction(img_path, transformer):
        image = Image.open(img_path)
        image_tensor = transformer(image).float()
        image_tensor = image_tensor.unsqueeze_(0)

        if torch.cuda.is_available():
            image_tensor.cuda()

        input = Variable(image_tensor)
        output = model(input)
        
        probs = nnf.softmax(output, dim=1)
        conf, classess = torch.max(probs, 1) 
        
        index = output.data.numpy().argmax()
        pred = classes[index]

        return pred, conf

    pred_dict, probability = prediction(img, transformer)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source