【问题标题】:How to get percentage prediction for each class from TensorFlow?如何从 TensorFlow 获取每个类的百分比预测?
【发布时间】:2021-08-01 12:43:15
【问题描述】:

我正在创建一个用于图像分类的神经网络,我有以下类: [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]]

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

非常感谢。

【问题讨论】:

  • 如果使用 softmax 激活,这些值的总和应该为 1,您确定这些值是由正确的模型生成的吗?

标签: tensorflow machine-learning computer-vision image-classification


【解决方案1】:

编辑:仅适用于 Imagenet。

您应该在predict 之上使用decode_predictions 以获得更多人类可读的结果。

为了说明,调用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 ...

请尝试以下 sn-p。

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

【讨论】:

  • 不,decode_predictions 只适用于 ImageNet 类,这里不是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 2018-12-08
  • 2021-12-10
  • 2020-10-28
相关资源
最近更新 更多