Building an image classifier is one of the most rewarding first projects for anyone diving into deep learning. TensorFlow, Google’s open‑source machine‑learning library, makes the process surprisingly approachable, even if you’re not yet a seasoned data scientist. In this guide we’ll walk through every stage—from setting up your Python environment to training a model that can distinguish between cats and dogs (or any two categories you choose). By the end, you’ll have a working classifier, a saved model ready for deployment, and a solid grasp of the common pitfalls that trip up beginners.
What You’ll Need
- Python 3.8+ (preferably via
pyenvorconda) - TensorFlow 2.x (installed with
pip install tensorflow) - NumPy and pandas (for data handling)
- Matplotlib or Seaborn (optional, for visualisation)
- A modest dataset of images (e.g., the Kaggle Dogs vs Cats sample or your own folder structure)
- A GPU is helpful but not required; the guide works on CPU too.
Step 1: Set Up the Development Environment
First, create an isolated environment so your project’s dependencies don’t clash with other Python work. Using conda:
conda create -n tf-image python=3.10
conda activate tf-image
pip install --upgrade pip
pip install tensorflow numpy pandas matplotlib seaborn
If you prefer venv:
python -m venv tf-image
source tf-image/bin/activate # on Windows use `tf-imageScriptsactivate`
pip install --upgrade pip
pip install tensorflow numpy pandas matplotlib seaborn
Verify the installation:
python -c "import tensorflow as tf; print(tf.__version__)"
You should see a version number like 2.13.0. If TensorFlow fails to import, double‑check that your Python version matches the supported range and that you have the appropriate CPU/GPU drivers.
Step 2: Gather and Prepare the Dataset
For a beginner‑friendly project, a small, well‑structured dataset works best. Organise your images into subfolders named after their class labels:
dataset/
│
├── train/
│ ├── cats/
│ │ ├─ cat001.jpg
│ │ └─ ...
│ └── dogs/
│ ├─ dog001.jpg
│ └─ ...
└── validation/
├── cats/
└── dogs/
TensorFlow’s tf.keras.utils.image_dataset_from_directory can read this layout directly:
import tensorflow as tf
train_ds = tf.keras.utils.image_dataset_from_directory(
"dataset/train",
label_mode="int",
image_size=(224, 224),
batch_size=32,
shuffle=True,
seed=123)
val_ds = tf.keras.utils.image_dataset_from_directory(
"dataset/validation",
label_mode="int",
image_size=(224, 224),
batch_size=32,
shuffle=False)
Notice we resize every image to 224×224 pixels—this matches the input shape of many pretrained models and keeps training fast.
Step 3: Build the Model Architecture
There are two common routes: build a model from scratch or fine‑tune a pretrained network. For simplicity we’ll use a lightweight MobileNetV2 backbone, which already knows how to extract useful visual features.
base_model = tf.keras.applications.MobileNetV2(
input_shape=(224, 224, 3),
include_top=False,
weights="imagenet")
base_model.trainable = False # freeze the convolutional base
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(1, activation="sigmoid")
model = tf.keras.Sequential([
base_model,
global_average_layer,
prediction_layer
])
We freeze the base model so the initial training only updates the new dense layers. This speeds up convergence and reduces the risk of over‑fitting on a small dataset.
Step 4: Compile the Model
Compilation tells TensorFlow how to optimise the network. Because we have a binary classification problem (cats vs. dogs), we use binary cross‑entropy loss and the Adam optimiser.
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),
metrics=["accuracy"])
model.summary()
The summary output confirms the number of trainable parameters (just the top layers) and helps you spot accidental mismatches in shape.
Step 5: Train the Model
Now we let the model learn from the data. A typical training run lasts 5‑10 epochs for a small dataset.
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=10,
callbacks=[
tf.keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True),
tf.keras.callbacks.ModelCheckpoint("best_model.h5", save_best_only=True)
])
The EarlyStopping callback halts training if validation loss stops improving, while ModelCheckpoint saves the best model to disk.
Step 6: Evaluate, Fine‑Tune, and Save the Model
After the initial training, evaluate the final performance:
loss, acc = model.evaluate(val_ds)
print(f"Validation loss: {loss:.4f}, accuracy: {acc:.4%}")
If the accuracy plateaus around 80‑85 % you can try fine‑tuning: unfreeze a few top layers of the base model and train with a lower learning rate.
base_model.trainable = True
for layer in base_model.layers[:-20]: # keep early layers frozen
layer.trainable = False
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-5),
loss="binary_crossentropy",
metrics=["accuracy"])
model.fit(train_ds, validation_data=val_ds, epochs=5)
Finally, export the model for later inference:
model.save("tf_image_classifier") # SavedModel format
You can now load it in any TensorFlow‑compatible environment with tf.keras.models.load_model("tf_image_classifier").
Common Mistakes to Avoid
1. Forgetting to normalize pixel values. TensorFlow’s pretrained models expect inputs in the [0, 1] range. If you skip tf.keras.applications.mobilenet_v2.preprocess_input, training will be noisy.
2. Using too large a batch size on a CPU. Large batches can cause out‑of‑memory errors or dramatically slow down training. Stick to 16‑32 on a laptop.
3. Mixing up label modes. image_dataset_from_directory offers categorical, binary, and int. Choose the one that matches your loss function.
4. Over‑fitting on a tiny dataset. If validation loss diverges while training loss keeps dropping, add data augmentation or collect more images.
5. Not setting a seed. Without a fixed seed, shuffling will produce different splits each run, making results non‑reproducible.
Tips and Tricks
• Data augmentation can be added on the fly with tf.keras.layers.RandomFlip, RandomRotation, etc., to increase diversity.
• Use tf.data.experimental.AUTOTUNE to prefetch batches and keep the GPU fed.
• For multi‑class problems, replace the final Dense(1, activation="sigmoid") with Dense(num_classes, activation="softmax") and switch the loss to CategoricalCrossentropy.
• When deploying to mobile or edge devices, convert the SavedModel to TensorFlow Lite (tf.lite.TFLiteConverter) to shrink size and improve latency.
Frequently Asked Questions
Can I use a custom dataset without folder names?
Yes. You can create a tf.data.Dataset from a CSV that maps file paths to labels, then apply tf.io.read_file and tf.image.decode_image inside a mapping function.
Do I need a GPU for this tutorial?
A GPU speeds up training, especially with larger models or datasets, but the guide runs comfortably on a modern CPU. If you have a GPU, install tensorflow‑gpu (or the standard package on TF 2.x, which detects CUDA automatically).
How do I serve the model as a web API?
Wrap the SavedModel with TensorFlow Serving or a lightweight Flask/FastAPI app. Load the model once at startup and expose an endpoint that accepts base64‑encoded images, preprocesses them, and returns the predicted class.
Conclusion
Training a simple image classifier with TensorFlow is a practical way to cement core deep‑learning concepts—data pipelines, model architecture, training loops, and evaluation. By following the steps above, you’ll have a functional model, a saved artifact ready for deployment, and a toolbox of best practices to avoid common traps. Keep experimenting: swap in different pretrained backbones, expand to multi‑class datasets, or integrate the model into a mobile app. The skills you build here are the foundation for more advanced computer‑vision projects.





