How to do multi-class image classification in keras?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Multi-class image classification is a core computer vision task where you assign each image to one of several predefined categories. Keras, running on top of TensorFlow, gives you a high-level API that makes it straightforward to build, train, and evaluate convolutional neural networks (CNNs) for this purpose. This article walks you through the complete workflow, from loading data to evaluating your trained model.
Dataset Preparation
Keras provides a convenient utility for loading images from a directory structure where each subfolder name is the class label.
The directory layout should look like this:
Setting label_mode="categorical" produces one-hot encoded labels, which is required when you use categorical_crossentropy as the loss function.
Building a CNN Model
A typical CNN for multi-class classification stacks convolutional and pooling layers to extract features, then uses dense layers to produce class probabilities. The final layer must have as many units as there are classes and use a softmax activation.
The Rescaling layer normalizes pixel values from the 0-255 range down to 0-1, which helps the optimizer converge faster.
Compiling and Training
For multi-class classification, compile the model with categorical_crossentropy loss. Use an optimizer like Adam and track accuracy as the metric.
If your labels are integers rather than one-hot vectors, use sparse_categorical_crossentropy instead and set label_mode="int" when loading the dataset.
Data Augmentation
Small datasets benefit greatly from data augmentation, which generates varied versions of each training image to reduce overfitting. In Keras you can add augmentation layers directly inside the model so that augmentation happens on the GPU during training.
These augmentation layers are only active during training. At inference time they pass images through unchanged.
Evaluation
After training, evaluate the model on a held-out test set to measure generalization performance.
For a more detailed breakdown, use a confusion matrix to see which classes the model confuses most often:
Common Pitfalls
- Mismatching loss and label format. Using
categorical_crossentropywith integer labels (orsparse_categorical_crossentropywith one-hot labels) causes shape errors or silent incorrect training. - Forgetting to rescale pixel values. Raw pixel values in the 0-255 range produce very large activations. Always normalize inputs to 0-1 or use standardization.
- Setting the wrong number of output units. The final Dense layer must have exactly as many units as there are classes. A mismatch causes a shape error during training.
- Applying augmentation at test time. Data augmentation should only run during training. If you build augmentation outside the model and apply it to the test set, your evaluation metrics will be unreliable.
- Training on too few epochs or too many. Too few epochs means the model underfits; too many leads to overfitting. Monitor validation loss and use
EarlyStoppingto find the sweet spot automatically.
Summary
- Organize your images into subdirectories named by class, and use
image_dataset_from_directorywithlabel_mode="categorical"for one-hot labels. - Build a CNN that ends with a Dense layer of size
num_classesandsoftmaxactivation. - Compile with
categorical_crossentropy(orsparse_categorical_crossentropyfor integer labels) and the Adam optimizer. - Add augmentation layers inside the model to reduce overfitting on small datasets.
- Evaluate on a separate test set and use a confusion matrix or classification report to understand per-class performance.
Related reading
- How to do multi GPU training with Keras?
- How to do Multiclass classification with Keras?
- How to do point-wise categorical crossentropy loss in Keras?
- How to do transfer learning for MNIST dataset?
- How to do slice assignment in Tensorflow
- How to do the group-by operation in Tensorflow?
- How to extract and recognize the vehicle plate number with Python?
- How to find and crop words into individual images with Python OpenCV?
.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.