Keras Applications

1.0.8 · maintenance · verified Thu Apr 09

Keras Applications provides reference implementations of popular deep learning models alongside pre-trained weights. Currently at version 1.0.8, this standalone library historically served as the primary source for models like VGG, ResNet, and MobileNet. However, these models have since been fully integrated into the core Keras library and are now primarily accessed via `tf.keras.applications` within TensorFlow-based Keras environments.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a pre-trained `ResNet50` model, preprocess a sample image, and make predictions using the `tf.keras.applications` module. Weights are automatically downloaded upon first instantiation. The example includes creating a dummy image for immediate execution.

import numpy as np
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
import os

# Create a dummy image for demonstration
dummy_image_path = 'dummy_elephant.jpg'
if not os.path.exists(dummy_image_path):
    try:
        from PIL import Image
        img_data = np.random.randint(0, 255, size=(224, 224, 3), dtype=np.uint8)
        dummy_img = Image.fromarray(img_data)
        dummy_img.save(dummy_image_path)
        print(f"Created dummy image: {dummy_image_path}")
    except ImportError:
        print("Pillow not installed. Skipping dummy image creation.")
        print("Please provide a real image path to run the example.")
        dummy_image_path = None

if dummy_image_path:
    # Load the pre-trained ResNet50 model
    # weights='imagenet' downloads weights if not already present
    model = ResNet50(weights='imagenet')
    print("ResNet50 model loaded successfully.")

    # Load an image and resize it to the target size expected by ResNet50
    img = image.load_img(dummy_image_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0) # Add batch dimension

    # Preprocess the image for the model (e.g., channel reordering, mean subtraction)
    x = preprocess_input(x)

    # Make predictions
    preds = model.predict(x)

    # Decode the top 3 predictions
    decoded_preds = decode_predictions(preds, top=3)[0]
    print('Predicted:', decoded_preds)

    # Clean up dummy image
    os.remove(dummy_image_path)
else:
    print("Quickstart example requires Pillow to create a dummy image.")

view raw JSON →