Edit tensorflow inceptionV3 retraining-example.py for multiple classificiations
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Transfer learning with TensorFlow's InceptionV3 lets you adapt a powerful image classifier to your own categories without training from scratch. The standard retrain.py example script handles single-label multi-class classification out of the box, where each image belongs to exactly one category. This article explains how to modify that script for both multi-class (many categories, one label per image) and multi-label (many categories, multiple labels per image) classification.
Prerequisites
Before modifying the retraining script, make sure you have the following in place.
You also need a labeled dataset. For multi-class classification, organize images into subdirectories where each directory name is the class label.
Loading InceptionV3 as a Feature Extractor
The core idea of transfer learning is to freeze the convolutional layers of a pretrained model and replace only the final classification head.
The feature extractor outputs a 2048-dimensional vector for each 299x299 input image. This vector captures high-level visual features learned from ImageNet.
Building a Multi-Class Classification Head
For standard multi-class classification (one label per image), add a dense layer with softmax activation.
Softmax ensures the output probabilities sum to 1.0, so the model always picks exactly one class. Use categorical_crossentropy when labels are one-hot encoded, or sparse_categorical_crossentropy when labels are integers.
Preparing the Data Pipeline
TensorFlow's image_dataset_from_directory automates loading and label assignment.
Prefetching and caching improve training throughput.
Training the Multi-Class Model
With the data pipeline ready, training is straightforward.
Early stopping prevents overfitting by reverting to the best weights if validation accuracy stalls for three consecutive epochs.
Modifying for Multi-Label Classification
The key modification for multi-label classification is changing the final activation from softmax to sigmoid and the loss from categorical crossentropy to binary crossentropy. Sigmoid treats each output neuron independently, so multiple classes can be active simultaneously.
For multi-label data, you cannot use image_dataset_from_directory because a single image may belong to multiple categories. Instead, load labels from a CSV file.
Running Inference
After training, run predictions on new images.
For multi-label inference, apply a threshold to each sigmoid output.
Fine-Tuning for Better Accuracy
After the classification head converges, you can unfreeze some InceptionV3 layers for fine-tuning.
Use a much lower learning rate during fine-tuning (1e-5 instead of 1e-3) to avoid destroying the pretrained features. Fine-tuning typically improves accuracy by 2-5 percentage points.
Common Pitfalls
- Using softmax for multi-label tasks: Softmax forces outputs to sum to 1.0, which prevents multiple labels from being active. Always use sigmoid activation with binary crossentropy for multi-label classification.
- Forgetting to normalize input images: InceptionV3 expects pixel values in the [0, 1] range. Feeding raw [0, 255] values produces poor accuracy and unstable training.
- Setting learning rate too high during fine-tuning: A high learning rate destroys the pretrained weights. Use 1e-5 or lower when unfreezing convolutional layers.
- Insufficient training data per class: Transfer learning reduces data requirements but each class still needs at least 100-200 images for reasonable accuracy. Classes with fewer than 50 images often overfit.
- Not using data augmentation: For small datasets, add random flips, rotations, and brightness adjustments to reduce overfitting and improve generalization.
Summary
- Transfer learning with InceptionV3 replaces only the final classification head while keeping pretrained convolutional features frozen.
- For multi-class (one label per image), use softmax activation with categorical crossentropy loss.
- For multi-label (multiple labels per image), switch to sigmoid activation with binary crossentropy loss.
- Normalize images to [0, 1] and resize to 299x299 to match InceptionV3's expected input format.
- Fine-tune the last few convolutional layers with a low learning rate after the head converges for an additional accuracy boost.
- Use early stopping and data augmentation to prevent overfitting on small datasets.
Related reading
- Efficient element-wise multiplication of a matrix and a vector in TensorFlow
- Efficiently Finding Closest Word In TensorFlow Embedding
- Efficiently grab gradients from TensorFlow?
- Eigenvectors of a large sparse matrix in Tensorflow
- Effective queries in machine learning
- Effects of randomizing the order of inputs to a neural network
- Enqueue and increment variable in Tensor Flow
- Epoch counter with TensorFlow Dataset API
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.