dl-workshop-2022

Using Xception network to predict an image’s class

The goal here is to load predict a class for an image of your choice using Xception network, a pre-trained deep learning model by Google. Please re-order the blocks of code below, copy-paste the code blocks in appropriate order in a new Colab notebook, run them, and analyze the outputs.

Block A: Inspect the model

Inspect the number of paramaters, number of layers, input shape, and number of output classes using the two approaches below:

print(model.summary())
from tensorflow.keras.utils import plot_model
plot_model(model, show_layer_names=True, show_shapes=True)

Block B: Upload a test image

Upload the image elephant.jpg to Colab Files.

Block C: Load the image and preprocess it

Option 1: Existing random image

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

Option 2: An image from your dataset

from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rescale=1./255)

train_ds = datagen.flow_from_directory(
  './face-expression-kaggle/images/train/',
  target_size=(299, 299),
  shuffle=True,
  batch_size=32)

images, labels = train_ds[0] # # Take one batch full of images

import matplotlib.pyplot as plt

plt.imshow(images[0])
plt.title(labels[0])
plt.axis("off")

x = images[0]
plt.imshow(x)

x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

Block D: Check what models can be used

Check the list of several state-of-the-art deep learning models for computer vision at https://keras.io/api/applications/.

Block E: Import the libraries needed

from tensorflow.keras.applications.xception import Xception
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.xception import preprocess_input, decode_predictions
import numpy as np

Block F: Instantiate a model trained on ImageNet.

model = Xception(weights='imagenet')

Block G: Decode the results into a list of tuples (class, description, probability).

print('Predicted:', decode_predictions(preds, top=3)[0])

Block H: Predict the class for the image

preds = model.predict(x)
print(preds)
print(preds.shape)