Thanks for tuning in to Google I/O. View all sessions on demandWatch on demand

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")
TF version: 2.12.0-rc1
Hub version: 0.12.0
GPU is available

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
WARNING:tensorflow:Please fix your imports. Module has been moved to tensorflow.python.trackable.data_structures. The old module will be deleted in version 2.11.
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: 207,622,237
Trainable params: 6,405
Non-trainable params: 207,615,832

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 [==============================] - 183s 835ms/step - loss: 0.8701 - accuracy: 0.8969 - val_loss: 0.6868 - val_accuracy: 0.9569
Epoch 2/5
183/183 [==============================] - 150s 816ms/step - loss: 0.6439 - accuracy: 0.9473 - val_loss: 0.6004 - val_accuracy: 0.9667
Epoch 3/5
183/183 [==============================] - 149s 814ms/step - loss: 0.5846 - accuracy: 0.9616 - val_loss: 0.5520 - val_accuracy: 0.9625
Epoch 4/5
183/183 [==============================] - 149s 814ms/step - loss: 0.5546 - accuracy: 0.9705 - val_loss: 0.5363 - val_accuracy: 0.9681
Epoch 5/5
183/183 [==============================] - 149s 813ms/step - loss: 0.5147 - accuracy: 0.9815 - val_loss: 0.5271 - val_accuracy: 0.9681
plt.ylabel("Loss (training and validation)")
plt.xlabel("Training Steps")

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



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)
WARNING:absl:Found untraced functions such as restored_function_body, restored_function_body, restored_function_body, restored_function_body, restored_function_body while saving (showing 5 of 1594). These functions will not be directly callable after loading.
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

2023-03-08 14:18:26.280656: W tensorflow/compiler/mlir/lite/python/] Ignored output_format.
2023-03-08 14:18:26.280701: W tensorflow/compiler/mlir/lite/python/] Ignored drop_control_dependency.
Wrote TFLite model of 826217856 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%).