Building an Image Classification Model using TensorFlow & Keras
Building an Image Classification Model using TensorFlow & Keras
Author: Affan Shah
Introduction
Image Classification is one of the most popular problems in Computer Vision.
The objective of this project is to train a Convolutional Neural Network (CNN) capable of distinguishing between cats and dogs using TensorFlow and Keras.
By the end of this project we will learn:
- Loading image datasets
- Creating training & validation datasets
- Building CNNs
- Preventing overfitting
- Data Augmentation
- Model Evaluation
- Exporting the trained model into TensorFlow Lite
Project Structure
dataset/
│
├── cat/
│ cat1.png
│ cat2.png
│ ...
│
└── dog/
dog1.png
dog2.png
...
TensorFlow automatically assigns labels based on folder names.
cat -> 0
dog -> 1
Step 1 — Importing Required Libraries
Every Machine Learning project starts by importing the required dependencies.
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import pathlib
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
Why these libraries?
- TensorFlow → Deep Learning Framework
- Keras → High-Level API for TensorFlow
- Matplotlib → Visualization
- NumPy → Numerical Operations
- Pathlib → File Handling
Step 2 — Loading the Dataset
dataset = pathlib.Path("dataset")
This points TensorFlow towards our dataset directory.
We can verify the number of images inside each class.
cat_image_count = len(list(dataset.glob("cat/*.png")))
dog_image_count = len(list(dataset.glob("dog/*.png")))
Output
Cats : 1240
Dogs : 1198
Knowing the dataset size helps understand whether the model has enough training data.
Step 3 — Creating Training and Validation Sets
Instead of manually splitting the dataset, TensorFlow provides a utility function.
train_ds = tf.keras.utils.image_dataset_from_directory(
dataset,
validation_split=0.2,
subset="training",
seed=123,
image_size=(180,180),
batch_size=32
)
Similarly, we create the validation dataset.
val_ds = tf.keras.utils.image_dataset_from_directory(
dataset,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(180,180),
batch_size=32
)
Why Validation?
A validation set helps measure how well our model performs on unseen images.
Without validation, we only know how well it memorized the training images.
Step 4 — Performance Optimization
TensorFlow datasets can become slow because images are continuously read from disk.
We improve performance using:
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
What each method does
cache()
Stores images in memory after the first epoch.
shuffle()
Randomizes the dataset.
prefetch()
Loads the next batch while the GPU trains on the current batch.
This significantly speeds up training.
Step 5 — Image Normalization
Images contain RGB values between 0 and 255.
Neural Networks perform better when values are between 0 and 1.
normalization_layer = layers.Rescaling(1./255)
This simple layer normalizes every pixel.
Step 6 — Understanding CNNs
Our model uses a Convolutional Neural Network (CNN).
A CNN learns:
- Edges
- Shapes
- Patterns
- Textures
- Objects
Unlike traditional Machine Learning, CNNs automatically extract features.
Step 7 — Preventing Overfitting
Initially the model performed well on training data but struggled on unseen images.
This is called Overfitting.
To solve this we use Data Augmentation.
data_augmentation = keras.Sequential([
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1),
])
Each image is randomly modified during training.
Examples include:
- Horizontal Flip
- Rotation
- Zoom
This increases dataset diversity.
Step 8 — Building the CNN
model = Sequential([
data_augmentation,
layers.Rescaling(1./255),
layers.Conv2D(16,3,padding="same",activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(32,3,padding="same",activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(64,3,padding="same",activation="relu"),
layers.MaxPooling2D(),
layers.Dropout(0.2),
layers.Flatten(),
layers.Dense(128,activation="relu"),
layers.Dense(1,name="outputs")
])
Understanding Each Layer
Conv2D
Extracts visual features.
Example:
- Edges
- Curves
- Textures
MaxPooling
Reduces image dimensions while preserving important information.
Benefits
- Faster Training
- Less Memory
- Reduced Overfitting
Dropout
layers.Dropout(0.2)
Randomly disables 20% of neurons.
This prevents the model from memorizing the training data.
Flatten
Converts
64 × 64 × 32
into
131072
which can be passed into Dense Layers.
Dense Layer
Acts as the decision maker.
layers.Dense(128,activation="relu")
Step 9 — Compiling the Model
model.compile(
optimizer="adam",
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=["accuracy"]
)
Components:
- Adam Optimizer → Updates weights efficiently
- BinaryCrossEntropy → Suitable for binary classification
- Accuracy → Measures prediction correctness
Step 10 — Training the Model
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=15
)
During training TensorFlow displays:
- Training Loss
- Validation Loss
- Training Accuracy
- Validation Accuracy
Step 11 — Exporting the Model
After training we convert the model into TensorFlow Lite.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open("model.tflite","wb") as f:
f.write(tflite_model)
TensorFlow Lite models are optimized for:
- Android
- Raspberry Pi
- Embedded Devices
- Edge AI
Step 12 — Making Predictions
We download an image.
cat_img_url = "https://upload.wikimedia.org/wikipedia/commons/0/0b/Cat_poster_1.jpg"
Load the image.
img = tf.keras.utils.load_img(
cat_img,
target_size=(180,180)
)
Convert it into a tensor.
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array,0)
Run inference.
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
Finally display the prediction.
print(
"This image most likely belongs to {} with a {:.2f}% confidence."
.format(class_names[np.argmax(score)],
100*np.max(score))
)
Results
The model successfully classifies images into:
- 🐱 Cat
- 🐶 Dog
The trained model is also exported as a TensorFlow Lite model for deployment on mobile and edge devices.
Key Takeaways
Throughout this project we learned:
- TensorFlow Dataset API
- Image Preprocessing
- CNN Architecture
- Data Augmentation
- Preventing Overfitting
- Binary Image Classification
- TensorFlow Lite Conversion
- Model Inference
Future Improvements
Possible enhancements include:
- Transfer Learning using ResNet50
- MobileNetV3
- EfficientNet
- Data Augmentation Pipelines
- Learning Rate Scheduling
- Early Stopping
- Model Checkpointing
These techniques can significantly improve accuracy and reduce training time.
Conclusion
This project demonstrates an end-to-end Deep Learning workflow—from loading image datasets to training a Convolutional Neural Network, reducing overfitting through data augmentation, and finally deploying the model as a TensorFlow Lite application.
While this is a relatively simple binary classification problem, the same workflow forms the foundation for solving more advanced computer vision tasks such as multi-class classification, object detection, and image segmentation.
Author
Affan Shah
Aspiring AI Systems Engineer passionate about Machine Learning, Deep Learning, Computer Vision, Large Language Models, and AI Infrastructure.