Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras - model.predict return classes and not probabilities

I load a model I trained. This is the last layer from training:

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(3))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

After that I try to make a prediction to a random image. So I load the model:

#load the model we created
json_file = open('/path/to/model_3.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weight into model
loaded_model.load_weights("/path/to/model_3.h5")
print("\nModel successfully loaded from disk! ")


# Predicting images
img =image.load_img('/path/to/image.jpeg', target_size=(224, 224))
x = image.img_to_array(img)
x *= (255.0/x.max())
image = np.expand_dims(x, axis = 0)
image = preprocess(image)
preds = loaded_model.predict_proba(image)
pred_classes = np.argmax(preds)
print(preds)
print(pred_classes)

As an output I get this:

[[6.0599333e-26 0.0000000e+00 1.0000000e+00]]
2

Which basically it is like I get [0 0 1] like predict_classes. Though I would like to get probabilities. So I am searching for an output like [0.75 0.1 0.15]. Any ideas?

like image 897
Ioan Kats Avatar asked Feb 05 '18 14:02

Ioan Kats


People also ask

What does keras model predict return?

Model. predict passes the input vector through the model and returns the output tensor for each datapoint. Since the last layer in your model is a single Dense neuron, the output for any datapoint is a single value.

How do you predict a class in keras?

Predict Class from Multi-Class Classification In multi-classes classification last layer use “softmax” activation, which means it will return an array of 10 probability scores (summing to 1) for 10 class. Each score will be the probability that the current class belongs to one of our 10 classes.

What is Predict_classes?

predict_class will return the index of the class having maximum value. For example, if cat is 0.6 and dog is 0.4, it will return 0 if the class cat is at index 0)


1 Answers

If you want's probabilities as output of the network you just need to use softmax activation function instead of sigmoid

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(3))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
like image 167
WellDone2094 Avatar answered Oct 04 '22 16:10

WellDone2094