简体   繁体   中英

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?

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM