Machine Learning Python Tensorflow Keras

Comparing Pre-trained ResNet and MobileNet

Resnet and Mobilenet are the popular pre-trained models for computer visions. Renet is more accurate, while Mobilenet is much smaller in size.

In this blog, we will compare the prediction of Resnet and Mobilenet using Keras. Their codes are shown below

# Resnet Pre-trained Model

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

model = ResNet50(weights='imagenet')

img_path = '/content/guess3.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])
# MobileNet Pre-trained Model

from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
import numpy as np

model = MobileNetV2(weights='imagenet')

img_path = '/content/guess3.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])

We use a difficult image below to compare the two models.

Resnet prediction is below

# Prediction from Resnet
Predicted: [('n03724870', 'mask', 0.50113374), ('n01514668', 'cock', 0.13875785), ('n03884397', 'panpipe', 0.06103888)]
# Prediction from Mobilenet
Predicted: [('n03804744', 'nail', 0.052739527), ('n03729826', 'matchstick', 0.047129802), ('n03207941', 'dishwasher', 0.034721375)]

Interestingly, the result shows that Resnet predicts the image ws mask or cock, while the Mobilenet predicted the image was nail and matchstick. Resnet’s result is slightly making more sense than MobileNet, even though it shows that machine image recognition is still not robust.

References:

Relevant Courses

May 2, 2021