tensorflow - 如何从 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]]
我做错了什么,还是我只是不正确地处理数据?
非常感谢。
解决方案
编辑:仅适用于 Imagenet。
您应该使用decode_predictions
onpredict
来获得更多人类可读的结果。
为了说明,调用后的输出可能如下所示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
推荐阅读
- sql - T-SQL 完全外连接(提供示例)
- c# - 需要将离线和触控 ID 添加到 Microsoft 身份验证层
- dataweave - Dataweave 日期格式为 GMT 时区,夏令时
- crash - 在远程 X11 中:xclock 有效,但 gitk 或 git gui 无效
- flutter - 找不到消费者提供者的祖先或找不到提供者
- r - 如何在同一数据集中(可能使用 stringr)合并具有相同名称的数据?
- javascript - 每次用户单击元素时,Django 管理员都会添加一个自定义 js
- sql-server - SQL 合并语句,你应该使用它们吗
- javascript - 如何使用 C# 方法从 ASP.Net Javascript AJAX 请求返回布尔值?
- node.js - 通过 Promise Request 在 Dialogflow 中设置上下文