如何从训练有素的 pytorch 模型中获得置信度分数

How to get confidence score from a trained pytorch model

我有一个经过训练的 PyTorch 模型,我想获得 (0-100)(0-1) 范围内的预测置信度分数。下面的代码给我一个分数,但它的范围是不确定的。我希望分数在 (0-1)(0-100) 的定义范围内。知道如何获得这个吗?

conf, classes = torch.max(output, 1)

我的代码:

model = torch.load(r'best.pt')
model.eval()
def preprocess(imgs):
    im = torch.from_numpy(imgs)
    im = im.float()  # uint8 to fp16/32
    im /= 255.0
    return im

img_path = cv2.imread("/content/634282.jpg",0)
cropped = cv2.resize(img_path,(28,28))
imgs = preprocess(np.array([[cropped]]))
def predict_allCharacters(imgs):
    output = model(imgs)
    conf, classes = torch.max(output, 1)
    class_names = '0123456789'
    return conf, class_names[classes.item()]

模型定义:

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(         
            nn.Conv2d(
                in_channels=1,              
                out_channels=16,            
                kernel_size=5,              
                stride=1,                   
                padding=2,                  
            ),                              
            nn.ReLU(),                      
            nn.MaxPool2d(kernel_size=2),    
        )
        self.conv2 = nn.Sequential(         
            nn.Conv2d(16, 32, 5, 1, 2),     
            nn.ReLU(),                      
            nn.MaxPool2d(2),                
        )
        # fully connected layer, output 10 classes
        self.out = nn.Linear(32 * 7 * 7, 37)
    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
        x = x.view(x.size(0), -1)       
        output = self.out(x)
        return output    # return x for visualization

在您的例子中,output 代表对数。从中获取概率的一种方法是使用 Softmax 函数。似乎 output 包含批处理的输出,而不是单个样本,您可以这样做:

probs = torch.nn.functional.softmax(output, dim=1)

然后,在 probs 中,每一行将具有给定样本的每个 class 的概率(即在范围 [0, 1]sum=1 内)。

因此,您的 predict_allCharacters 可以修改为:

def predict_allCharacters(imgs):
    output = model(imgs)
    probs = torch.nn.functional.softmax(output, dim=1)
    conf, classes = torch.max(probs, 1)
    class_names = '0123456789'
    return conf, class_names[classes.item()]