2

我使用 TensorFlow 后端在 Keras 中实现了一个图像分类器。使用具有两个输出类的数据集,我检查了预测标签如下:

if  result[0][0] == 1:
    prediction ='adathodai'
else:
    prediction ='thamarathtai'

完整代码链接: 这里

有了三个类,我得到[[0. 0. 1.]]了结果输出。如何以 if else 格式检查两个以上类别的预测标签?

4

1 回答 1

5

对于具有 k 个标签的多类分类问题,您可以使用 检索预测类的索引model.predict_classes()。玩具示例:

import keras
import numpy as np

# Simpel model, 3 output nodes
model = keras.Sequential()
model.add(keras.layers.Dense(3, input_shape=(10,), activation='softmax'))

# 10 random input data points
x = np.random.rand(10, 10)
model.predict_classes(x)
> array([1, 1, 2, 1, 2, 1, 2, 1, 1, 1])

如果列表中有标签,则可以使用预测的类来获取预测的标签:

labels = ['label1', 'label2', 'label3']
[labels[i] for i in model.predict_classes(x)]
> ['label2', 'label2', 'label3', 'label2', 'label3', 'label2', 'label3', 'label2', 'label2', 'label2']

在后台,model.predict_classes返回预测中每一行的最大预测类概率的索引:

model.predict_classes(x)
> array([1, 1, 2, 1, 2, 1, 2, 1, 1, 1])
model.predict(x).argmax(axis=-1) # same thing
> array([1, 1, 2, 1, 2, 1, 2, 1, 1, 1])
于 2019-02-02T17:15:38.773 回答