Search code examples
pythonclassificationdeep-learningkeras

Get order of class labels for Keras predict function


I have the same question as this question here in SO. However, when I tried using the probas_to_classes() utility function, **it is already missing in the current code:

"""Numpy-related utilities."""
from __future__ import absolute_import

import numpy as np


def to_categorical(y, num_classes=None):
    """Converts a class vector (integers) to binary class matrix.

    E.g. for use with categorical_crossentropy.

    # Arguments
        y: class vector to be converted into a matrix
            (integers from 0 to num_classes).
        num_classes: total number of classes.

    # Returns
        A binary matrix representation of the input.
    """
    y = np.array(y, dtype='int').ravel()
    if not num_classes:
        num_classes = np.max(y) + 1
    n = y.shape[0]
    categorical = np.zeros((n, num_classes))
    categorical[np.arange(n), y] = 1
    return categorical


def normalize(x, axis=-1, order=2):
    """Normalizes a Numpy array.

    # Arguments
        x: Numpy array to normalize.
        axis: axis along which to normalize.
        order: Normalization order (e.g. 2 for L2 norm).

    # Returns
        A normalized copy of the array.
    """
    l2 = np.atleast_1d(np.linalg.norm(x, order, axis))
    l2[l2 == 0] = 1
    return x / np.expand_dims(l2, axis)

Do you have any other alternatives in order to get the classes associated with the output of the model?


Solution

  • noobalert, to get the top 2 predictions, as you requested to the Matias Valdenegro 's question in the comments section, you can do the following code:

    prediction1 = model.predict(your_data)
    # sorting the predictions in descending order
    sorting = (-prediction1).argsort()
    
    # getting the top 2 predictions
    sorted_ = sorting[0][:2]
    
    for value in sorted_:
        # you can get your classes from the encoder(your_classes = encoder.classes_) 
        # or from a dictionary that you created before.
        # And then we access them with the predicted index.
        predicted_label = your_classes[value]
    
        # just some rounding steps
        prob = (prediction1[0][value]) * 100
        prob = "%.2f" % round(prob,2)
        print("I have %s%% sure that it belongs to %s." % (prob, predicted_label)