python - 打印 vgg、keras 中的所有分类类。索引错误

标签 python printing keras index-error pre-trained-model

我正在尝试打印所有已知类别及其概率值。第一个值是概率最高的类别。

这是迄今为止我的代码:

from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
from keras.applications.vgg16 import decode_predictions

model = VGG16()

print(model.summary())


# load an image from file
image = load_img('./pictures/door.jpg', target_size=(224, 224))
image = img_to_array(image)  #output Numpy-array

#4-dimensional: samples, rows, columns, and channels.
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))


# prepare the image for the VGG model. 
image = preprocess_input(image)


# predict the probability across all output classes. 
yhat = model.predict(image)


# convert the probabilities to class labels
label = decode_predictions(yhat)
# retrieve the most likely result, e.g. highest probability
for i in range(0,5):
    label = label[i][i]
    print('%s (%.2f%%)' % (label[1], label[2] * 100))

我收到以下错误:

Traceback (most recent call last):
  File path, line 38, in <module>
    print('%s (%.2f%%)' % (label[1], label[2] * 100))
IndexError: string index out of range

你知道如何处理吗? 提前致谢^^

最佳答案

您的代码有错误。试试这个:

labels = decode_predictions(yhat)[0]
# retrieve the most likely result, e.g. highest probability
for i in range(0,5):
    label = labels[i]
    #print('%s (%.2f%%)' % (label[1], label[2] * 100)) 
    print('%s (%.2f%%)' % (label[1], float(label[2]) * 100))

关于python - 打印 vgg、keras 中的所有分类类。索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451919/

相关文章:

python - 在 Python 中,如何检查 2 个不同的链接是否实际指向同一页面?

python - 从与 TypeVar 关联的具体类型中获取内部类型

python - pip freeze 实际导入的包

python - flask -socket.error : [Errno 10053] An established connection was aborted by the software in your host machine

css - 为什么 chrome 打印/预览中 div 的 100% 高度不起作用?

Python打印函数

for-loop - tweepy 中的循环错误

python - 属性错误 : 'NoneType' object has no attribute '_inbound_nodes' in Keras

python - 将千层面转换为 Keras 代码(CNN -> LSTM)

python - 预期 input_1 的形状为 (224, 224, 3),但得到的数组的形状为 (400, 401, 3)