ML Zoomcamp 2023 – Deep Learning – Part 14

  1. Using the model
    1. Loading the model
    2. Evaluating the model
    3. Getting predictions

Using the model

In the last section we trained the final model – model on bigger images and saved the best one which we want to use now to test it on test dataset and make predictions. In this article we will cover:

  • Loading the model
  • Evaluating the model
  • Getting predictions

Loading the model

import tensorflow as tf
from tensorflow import keras

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.applications.xception import preprocess_input
test_gen = ImageDataGenerator(preprocessing_function=preprocess_input)

test_ds = test_gen.flow_from_directory(
    './clothing-dataset-small/test',
    target_size=(299, 299),
    batch_size=32,
    shuffle=False
)

# Output: Found 372 images belonging to 10 classes.
#model = keras.models.load_model('xception_v4_1_13_0.903.h5')
model = keras.models.load_model('xception_v1_09_0.839.h5')

Evaluating the model

The evaluation is done quite easily just use the evaluate function of the model and provide the test data. The output consists of two numbers. The first value is the loss value and the second one is the accuracy on test dataset. When the accuracy is almost the same like the model performance was before means that the model does not overfit and we trained a good model.

model.evaluate(test_ds)

# Output:
# 12/12 [==============================] - 57s 5s/step - loss: 0.7126 - accuracy: 0.8065
# [0.712611973285675, 0.8064516186714172]

Getting predictions

Because we have a good model now we can apply it to an image.

import numpy as np

path = 'clothing-dataset-small/test/pants/c8d21106-bbdb-4e8d-83e4-bf3d14e54c16.jpg'

img = load_img(path, target_size=(299, 299))

x = np.array(img)
X = np.array([x])
X.shape

# Output: (1, 299, 299, 3)

X = preprocess_input(X)
pred = model.predict(X)
classes = [
    'dress',
    'hat',
    'longsleeve',
    'outwear',
    'pants',
    'shirt',
    'shoes',
    'shorts',
    'skirt',
    't-shirt'
]

dict(zip(classes, pred[0]))

Here we don’t have probabilities but we have numbers up to 10, so this are the logits as mentioned before. This are the raw predictions. We can turn them into probabilities but we can treat them as relative likelyhood of belonging to this class. That means we see a large likelyhood belonging to the pants class. For getting the probability you can apply the softmax by your own.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.