首页 > 解决方案 > 如何从 TensorFlow 获取每个类的百分比预测?

问题描述

我正在为图像分类创建一个神经网络,我有以下类: [class1, class2, class3]

我有一个基于 VGG 的模型,模型的最后一层修改如下:

predictions = layers.Dense(int(len(['class1', 'class2', 'class3'])), activation='softmax')(x)

然后我编译模型如下:

model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])

然后我根据输入图像预测类:

img = load_img(input_path, target_size=(224, 224))
img = np.asarray(img) / 255.
img = cv2.resize(img, (224, 224))
img = img.reshape(1, 224, 224, 3)

prediction = model.predict(img)

然而,它确实作为一种预测回到我身边:

[[5.7733614e-29 2.5203591e-28 3.1751932e-38]]

我想了解这些数据的含义以及如何将其解释为百分比,这样我就可以说 class1 是 59%,class2 是 20%,class3 是 21%。

我的意思是,我希望输出是这样的:

[[0.59 0.20 0.21]]

我做错了什么,还是我只是不正确地处理数据?

非常感谢。

标签: tensorflowmachine-learningcomputer-visionimage-classification

解决方案


编辑:仅适用于 Imagenet。

您应该使用decode_predictionsonpredict来获得更多人类可读的结果。

为了说明,调用后的输出可能如下所示predict

3.60479535e-05 2.34715412e-06 9.06522095e-04 1.34255132e-03

之后decode_predictions

[[('n01944390', 'snail', 0.24689779), ('n01943899', 'conch', 0.2438357), ('n03944341', 'pinwhe ...

请尝试以下代码段。

from tensorflow.keras.applications.vgg16 import decode_predictions

prediction = model.predict(img)

# You can use the one below.
# print( 'Predicted:', decode_predictions( prediction, top=5 )[0] )
# or...
results = decode_predictions(prediction)
for result in results[0]:
    print( result[2] ) # prints the accuracy levels of each class

推荐阅读