如何在 Resnet 50 分类中输出置信度?

How do I output confidence level in Resnet 50 classification?

我训练了 Resnet-50 class化网络来 class 化我的对象,我使用以下代码来评估网络。

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)

系统处理后的输出只是对象的class,没有显示任何置信度,我的问题是如何在测试时也显示置信度?

model.predict 为您提供每个 class 的置信度。在此基础上使用 np.argmax 只会给您带来最高置信度的 class。

因此,只需执行:

confidences = np.squeeze(model.predict(img))

我添加了 np.squeeze 以删除任何单一维度,因为我们只查看单个图像,因此批量大小为 1。因此,第一个维度的大小仅为 1,因此我'放入 np.squeeze 以删除单例维度。 此外,您可以获得此图像的最佳 class 以及通过执行以下操作获得的信心:

cls = np.argmax(confidences)
name = class_names[cls]
top_conf = confidences[cls]

如果您想进一步显示预测中的前 5 个 class,您可以执行 np.argsort,对预测进行排序,然后找到相应 [=31] 的索引=]es 并显示这些信心。请注意,我将按负数排序,以便我们按降序获得置信度,因此排序的第一个索引对应于具有最高置信度的 class。我还会将概率按 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}%')

您可以调整代码以显示您想要的数量。我已经让你玩起来很容易,所以如果你只想要最自信的 class,设置 k = 1.