Issue
I implemented an image classifier in Keras using the TensorFlow backend. For a dataset with two output classes I checked predicted labels:
if result[0][0] == 1:
prediction ='adathodai'
else:
prediction ='thamarathtai'
Full code. With three classes I get [[0. 0. 1.]]
. How can I check predicted labels for more than two classes in if else format?
Solution
For a multi-class classification problem with k labels, you can retrieve the index of the predicted classes by using model.predict_classes()
. Toy example:
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])
If you have the labels in a list, you can use the predicted classes to get the predicted labels:
labels = ['label1', 'label2', 'label3']
[labels[i] for i in model.predict_classes(x)]
> ['label2', 'label2', 'label3', 'label2', 'label3', 'label2', 'label3', 'label2', 'label2', 'label2']
Under the hood, model.predict_classes
return the index of the maximum predicted class probability for each row in the predictions:
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])
Answered By - sdcbr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.