Import the libraries

In [1]:
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import PIL

Load the image

In [2]:
image_path = 'images/frog.jpg'
In [3]:
image = PIL.Image.open(image_path)
image = image.resize((224, 224))
image = np.array(image)
In [4]:
plt.figure()
plt.imshow(image)
plt.show()

Download the neural network model

In [5]:
model = tf.keras.applications.mobilenet_v2.MobileNetV2(include_top=True, weights='imagenet')

Preprocess the input

In [6]:
image = tf.keras.applications.mobilenet_v2.preprocess_input(image)
In [7]:
plt.figure()
plt.imshow(image)
plt.show()
WARNING: Logging before flag parsing goes to stderr.
W0709 18:35:30.211381 140508670097216 image.py:700] Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).

Create a input batch

In [8]:
image = image[tf.newaxis, :]
In [9]:
print(image.shape)
(1, 224, 224, 3)

Input the image to the neural network

In [10]:
predictions = model.predict(image)

Decode the predictions

In [11]:
top5 = tf.keras.applications.mobilenet_v2.decode_predictions(predictions)[0]

Print the predictions

In [12]:
for num, name, score in top5:
    print(name, ":", score*100)
tree_frog : 96.91776037216187
tailed_frog : 1.5988821163773537
bullfrog : 0.06190281710587442
European_fire_salamander : 0.028770850622095168
green_lizard : 0.020235931151546538