如何在 Resnet 50 分类中输出置信度?
Posted
技术标签:
【中文标题】如何在 Resnet 50 分类中输出置信度?【英文标题】:How do I output confidence level in Resnet 50 classification? 【发布时间】:2020-10-14 21:37:42 【问题描述】:我训练了 Resnet-50 分类网络来对我的对象进行分类,并使用以下代码来评估网络。
from tensorflow.keras.models import load_model
import cv2
import numpy as np
import os
class_names = ["x", "y", "b","g", "xx", "yy", "bb","gg", "xyz","xzy","yy"]
model = load_model('transfer_resnet.h5')
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
imgg = cv2.imread('/path to image/a1.jpg')
img = cv2.resize(imgg,(224,224))
img = np.reshape(img,[1,224,224,3])
classes = np.argmax(model.predict(img), axis = -1)
print(classes)
for i in classes:
names = class_names[i]
print(names)
cv2.imshow("id",imgg)
key = cv2.waitKey(0)
处理后系统的输出只是对象的类别,没有显示任何置信度百分比,我的问题是我如何在测试过程中也显示置信度百分比?
【问题讨论】:
【参考方案1】:model.predict
为您提供每个班级的信心。在此基础上使用np.argmax
只会为您提供最有信心的班级。
因此,只需这样做:
confidences = np.squeeze(model.predict(img))
我添加了np.squeeze
以删除任何单一维度,因为我们只查看单个图像,因此批量大小为 1。因此,第一个维度的大小仅为 1,所以我输入np.squeeze
删除单件维度。
此外,您可以通过以下方式获得该图像的最佳类别以及置信度:
class = np.argmax(confidences)
name = class_names[class]
top_conf = confidences[class]
如果您想进一步显示预测中的前 5 个类别,您可以执行 np.argsort
,对预测进行排序,然后找到相应类别的索引并显示这些置信度。请注意,我将按负数排序,因此我们以降序获得置信度,因此排序的第一个索引对应于具有最高置信度的类。我还将概率按 100 缩放,以便按照您的要求为您提供百分比置信度:
k = 5
confidences = np.squeeze(model.predict(img))
inds = np.argsort(-confidences)
top_k = inds[:k]
top_confidences = confidences[inds]
for i, (conf, ind) in enumerate(zip(top_confidences, top_k)):
print(f'Class #i + 1 - class_names[ind] - Confidence: 100 * conf%')
您可以调整代码以显示您想要的数量。我已经让你玩起来很容易,所以如果你只想要最自信的班级,请设置k = 1
。
【讨论】:
以上是关于如何在 Resnet 50 分类中输出置信度?的主要内容,如果未能解决你的问题,请参考以下文章