如何获得图像分类器中的前 5 个预测?
这段代码给了我前 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
softmax 给出了各个类别的概率分布。
argmax
只取概率最高的类的索引。您也许可以使用 argsort 它将返回排序位置的所有索引。示例:
输出:
这可能是具有 3 个目标、大小为 5 的批次的概率分布。沿着最后一个维度的 argmax 将给出:
输出:
而沿着最后一个维度的 argsort 将给出:
输出:
如您所见,上面输出中的最后一列是概率最高的预测,第二列是具有最高概率的预测第二高的概率,依此类推。
The softmax gives an probability distribution over the classes.
argmax
only takes the index of the class with the highest probability. You could perhaps useargsort
which will return all indices in their sorted position.An example:
output:
This is might be the probability distribution for a batch of size 5 with 3 targets. An argmax along the last dimension will give:
output:
Whilst an argsort along the last dimension will give:
output:
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.