对于具有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])