如何获得图像分类器中的前 5 个预测?

发布于 2025-01-13 18:50:47 字数 520 浏览 1 评论 0原文

这段代码给了我前 1 个预测,但我想要前 5 个。我该怎么做?

   # Get top 1 prediction for all images
    
    predictions = []
    confidences = []
    
    with torch.inference_mode():
      for _, (data, target) in enumerate(tqdm(test_loader)):
        data = data.cuda()
        target = target.cuda()
        output = model(data)
        pred = output.data.max(1)[1]
        probs = F.softmax(output, dim=1)
        predictions.extend(pred.data.cpu().numpy())
        confidences.extend(probs.data.cpu().numpy())

this code gives me top 1 prediction but i want top 5. how can i do that?

   # Get top 1 prediction for all images
    
    predictions = []
    confidences = []
    
    with torch.inference_mode():
      for _, (data, target) in enumerate(tqdm(test_loader)):
        data = data.cuda()
        target = target.cuda()
        output = model(data)
        pred = output.data.max(1)[1]
        probs = F.softmax(output, dim=1)
        predictions.extend(pred.data.cpu().numpy())
        confidences.extend(probs.data.cpu().numpy())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海的爱人是光 2025-01-20 18:50:47

softmax 给出了各个类别的概率分布。 argmax 只取概率最高的类的索引。您也许可以使用 argsort 它将返回排序位置的所有索引。

示例:

a = torch.randn(5, 3)
preds = a.softmax(1); preds

输出:

tensor([[0.1623, 0.6653, 0.1724],
        [0.4107, 0.1660, 0.4234],
        [0.6520, 0.2354, 0.1126],
        [0.1911, 0.4600, 0.3489],
        [0.4797, 0.0843, 0.4360]])

这可能是具有 3 个目标、大小为 5 的批次的概率分布。沿着最后一个维度的 argmax 将给出:

preds.argmax(1)

输出:

tensor([1, 2, 0, 1, 0])

而沿着最后一个维度的 argsort 将给出:

preds.argsort(1)

输出:

tensor([[0, 2, 1],
        [1, 0, 2],
        [2, 1, 0],
        [0, 2, 1],
        [1, 2, 0]])

如您所见,上面输出中的最后一列是概率最高的预测,第二列是具有最高概率的预测第二高的概率,依此类推。

The softmax gives an probability distribution over the classes. argmax only takes the index of the class with the highest probability. You could perhaps use argsort which will return all indices in their sorted position.

An example:

a = torch.randn(5, 3)
preds = a.softmax(1); preds

output:

tensor([[0.1623, 0.6653, 0.1724],
        [0.4107, 0.1660, 0.4234],
        [0.6520, 0.2354, 0.1126],
        [0.1911, 0.4600, 0.3489],
        [0.4797, 0.0843, 0.4360]])

This is might be the probability distribution for a batch of size 5 with 3 targets. An argmax along the last dimension will give:

preds.argmax(1)

output:

tensor([1, 2, 0, 1, 0])

Whilst an argsort along the last dimension will give:

preds.argsort(1)

output:

tensor([[0, 2, 1],
        [1, 0, 2],
        [2, 1, 0],
        [0, 2, 1],
        [1, 2, 0]])

As you can see, the last column in the output above is the prediction with highest probability and the second column is the prediction with the second highest probability, and so on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文