Search code examples
pythonmachine-learningkeraspre-trained-modelimagenet

Keras: get labels name of pre-trained models on imagenet


I am using Keras Inception_v3 pre-trained on Imagenet:

base_model = InceptionV3(weights='imagenet', include_top=True)

And when I predict from generated images, I get the output vector which has a shape (n,1000) with n being the number of images given. So now if I want to interpret the result, I need the name of the 1000 output classes used to train the model... But I can't find it!

Any idea ?


Solution

  • You can use decode_predictions method:

    from keras.applications.inception_v3 import decode_predictions
    
    preds = model.predict(x)
    print('Predicted:', decode_predictions(preds, top=10))
    
    # Predicted: [(u'n02504013', u'Indian_elephant', 0.0042589349), ...]
    

    From source code:

    def decode_predictions(preds, top=5, **kwargs):
        """Decodes the prediction of an ImageNet model.
        # Arguments
            preds: Numpy tensor encoding a batch of predictions.
            top: Integer, how many top-guesses to return.
        # Returns
            A list of lists of top class prediction tuples
            `(class_name, class_description, score)`.
            One list of tuples per sample in batch input.
        # Raises
            ValueError: In case of invalid shape of the `pred` array
                (must be 2D).
        """
    

    Obviously it is not specific to Inception_V3. You can import it and use it for any pre-trained model on Imagenet. Alternatively, you can import it using:

    from keras.applications.imagenet_utils import decode_predictions