Retraining an Image Classifier

View on Run in Google Colab View on GitHub Download notebook See TF Hub models


Image classification models have millions of parameters. Training them from scratch requires a lot of labeled training data and a lot of computing power. Transfer learning is a technique that shortcuts much of this by taking a piece of a model that has already been trained on a related task and reusing it in a new model.

This Colab demonstrates how to build a Keras model for classifying five species of flowers by using a pre-trained TF2 SavedModel from TensorFlow Hub for image feature extraction, trained on the much larger and more general ImageNet dataset. Optionally, the feature extractor can be trained ("fine-tuned") alongside the newly added classifier.

Looking for a tool instead?

This is a TensorFlow coding tutorial. If you want a tool that just builds the TensorFlow or TFLite model for, take a look at the make_image_classifier command-line tool that gets installed by the PIP package tensorflow-hub[make_image_classifier], or at this TFLite colab.


import itertools
import os

import matplotlib.pylab as plt
import numpy as np

import tensorflow as tf
import tensorflow_hub as hub

print("TF version:", tf.__version__)
print("Hub version:", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")
2024-02-01 12:27:59.194808: E external/local_xla/xla/stream_executor/cuda/] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2024-02-01 12:27:59.194870: E external/local_xla/xla/stream_executor/cuda/] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2024-02-01 12:27:59.196384: E external/local_xla/xla/stream_executor/cuda/] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
TF version: 2.15.0
Hub version: 0.16.1
2024-02-01 12:28:01.642282: E external/local_xla/xla/stream_executor/cuda/] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected

Select the TF2 SavedModel module to use

For starters, use The same URL can be used in code to identify the SavedModel and in your browser to show its documentation. (Note that models in TF1 Hub format won't work here.)

You can find more TF2 models that generate image feature vectors here.

There are multiple possible models to try. All you need to do is select a different one on the cell below and follow up with the notebook.

Selected model: efficientnetv2-xl-21k :
Input size (512, 512)

Set up the Flowers dataset

Inputs are suitably resized for the selected module. Dataset augmentation (i.e., random distortions of an image each time it is read) improves training, esp. when fine-tuning.

data_dir = tf.keras.utils.get_file(
Downloading data from
228813984/228813984 [==============================] - 1s 0us/step

Found 3670 files belonging to 5 classes.
Using 2936 files for training.
Found 3670 files belonging to 5 classes.
Using 734 files for validation.

Defining the model

All it takes is to put a linear classifier on top of the feature_extractor_layer with the Hub module.

For speed, we start out with a non-trainable feature_extractor_layer, but you can also enable fine-tuning for greater accuracy.

do_fine_tuning = False
print("Building model with", model_handle)
model = tf.keras.Sequential([
    # Explicitly define the input shape so the model can be properly
    # loaded by the TFLiteConverter
    tf.keras.layers.InputLayer(input_shape=IMAGE_SIZE + (3,)),
    hub.KerasLayer(model_handle, trainable=do_fine_tuning),
Building model with
Model: "sequential_1"
 Layer (type)                Output Shape              Param #   
 keras_layer (KerasLayer)    (None, 1280)              207615832 
 dropout (Dropout)           (None, 1280)              0         
 dense (Dense)               (None, 5)                 6405      
Total params: 207622237 (792.02 MB)
Trainable params: 6405 (25.02 KB)
Non-trainable params: 207615832 (791.99 MB)

Training the model

  optimizer=tf.keras.optimizers.SGD(learning_rate=0.005, momentum=0.9), 
  loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True, label_smoothing=0.1),
steps_per_epoch = train_size // BATCH_SIZE
validation_steps = valid_size // BATCH_SIZE
hist =
    epochs=5, steps_per_epoch=steps_per_epoch,
Epoch 1/5
183/183 [==============================] - 1694s 9s/step - loss: 0.8988 - accuracy: 0.8921 - val_loss: 0.6911 - val_accuracy: 0.9569
Epoch 2/5
183/183 [==============================] - 1669s 9s/step - loss: 0.6569 - accuracy: 0.9445 - val_loss: 0.6412 - val_accuracy: 0.9667
Epoch 3/5
183/183 [==============================] - 1701s 9s/step - loss: 0.5966 - accuracy: 0.9610 - val_loss: 0.5688 - val_accuracy: 0.9681
Epoch 4/5
183/183 [==============================] - 1694s 9s/step - loss: 0.5512 - accuracy: 0.9719 - val_loss: 0.5821 - val_accuracy: 0.9556
Epoch 5/5
183/183 [==============================] - 1687s 9s/step - loss: 0.5211 - accuracy: 0.9764 - val_loss: 0.5550 - val_accuracy: 0.9611
plt.ylabel("Loss (training and validation)")
plt.xlabel("Training Steps")

plt.ylabel("Accuracy (training and validation)")
plt.xlabel("Training Steps")
[<matplotlib.lines.Line2D at 0x7ff004f5dd90>]



Try out the model on an image from the validation data:

x, y = next(iter(val_ds))
image = x[0, :, :, :]
true_index = np.argmax(y[0])

# Expand the validation image to (1, 224, 224, 3) before predicting the label
prediction_scores = model.predict(np.expand_dims(image, axis=0))
predicted_index = np.argmax(prediction_scores)
print("True label: " + class_names[true_index])
print("Predicted label: " + class_names[predicted_index])


1/1 [==============================] - 4s 4s/step
True label: sunflowers
Predicted label: sunflowers

Finally, the trained model can be saved for deployment to TF Serving or TFLite (on mobile) as follows.

saved_model_path = f"/tmp/saved_flowers_model_{model_name}", saved_model_path)
INFO:tensorflow:Assets written to: /tmp/saved_flowers_model_efficientnetv2-xl-21k/assets
INFO:tensorflow:Assets written to: /tmp/saved_flowers_model_efficientnetv2-xl-21k/assets

Optional: Deployment to TensorFlow Lite

TensorFlow Lite lets you deploy TensorFlow models to mobile and IoT devices. The code below shows how to convert the trained model to TFLite and apply post-training tools from the TensorFlow Model Optimization Toolkit. Finally, it runs it in the TFLite Interpreter to examine the resulting quality

  • Converting without optimization provides the same results as before (up to roundoff error).
  • Converting with optimization without any data quantizes the model weights to 8 bits, but inference still uses floating-point computation for the neural network activations. This reduces model size almost by a factor of 4 and improves CPU latency on mobile devices.
  • On top, computation of the neural network activations can be quantized to 8-bit integers as well if a small reference dataset is provided to calibrate the quantization range. On a mobile device, this accelerates inference further and makes it possible to run on accelerators like Edge TPU.

Optimization settings

2024-02-01 14:50:56.634843: W tensorflow/compiler/mlir/lite/python/] Ignored output_format.
2024-02-01 14:50:56.634902: W tensorflow/compiler/mlir/lite/python/] Ignored drop_control_dependency.
Summary on the non-converted ops:

 * Accepted dialects: tfl, builtin, func
 * Non-Converted Ops: 879, Total Ops 2180, % non-converted = 40.32 %
 * 879 ARITH ops

- arith.constant:  879 occurrences  (f32: 878, i32: 1)

  (f32: 94)
  (f32: 358)
  (f32: 80)
  (f32: 1)
  (f32: 342)
  (f32: 81)
  (f32: 342)
Wrote TFLite model of 826217852 bytes.
interpreter = tf.lite.Interpreter(model_content=lite_model_content)
# This little helper wraps the TFLite Interpreter as a numpy-to-numpy function.
def lite_model(images):
  interpreter.set_tensor(interpreter.get_input_details()[0]['index'], images)
  return interpreter.get_tensor(interpreter.get_output_details()[0]['index'])
num_eval_examples = 50 
eval_dataset = ((image, label)  # TFLite expects batch size 1.
                for batch in train_ds
                for (image, label) in zip(*batch))
count = 0
count_lite_tf_agree = 0
count_lite_correct = 0
for image, label in eval_dataset:
  probs_lite = lite_model(image[None, ...])[0]
  probs_tf = model(image[None, ...]).numpy()[0]
  y_lite = np.argmax(probs_lite)
  y_tf = np.argmax(probs_tf)
  y_true = np.argmax(label)
  count +=1
  if y_lite == y_tf: count_lite_tf_agree += 1
  if y_lite == y_true: count_lite_correct += 1
  if count >= num_eval_examples: break
print("TFLite model agrees with original model on %d of %d examples (%g%%)." %
      (count_lite_tf_agree, count, 100.0 * count_lite_tf_agree / count))
print("TFLite model is accurate on %d of %d examples (%g%%)." %
      (count_lite_correct, count, 100.0 * count_lite_correct / count))
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
TFLite model agrees with original model on 50 of 50 examples (100%).
TFLite model is accurate on 50 of 50 examples (100%).