这段代码给了我前一名的预测,但我想要前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())发布于 2022-03-12 14:52:33
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的概率分布。最后一个维度的讨论将给出:
preds.argmax(1)产出:
tensor([1, 2, 0, 1, 0])而最后一个维度的争论会给出:
preds.argsort(1)产出:
tensor([[0, 2, 1],
[1, 0, 2],
[2, 1, 0],
[0, 2, 1],
[1, 2, 0]])如您所见,上面输出的最后一列是概率最高的预测,第二列是第二大概率的预测,依此类推。
https://stackoverflow.com/questions/71450451
复制相似问题