Framing the Pipeline
I'm solidifying the need for a Python script leveraging TensorFlow for automated image classification. Building a solid pipeline is key. I'm focusing on the modular aspects for easy adaptation to diverse image datasets.
Developing Core Functions
I've outlined the critical functions needed: data loading using image_dataset_from_directory, image preprocessing (rescaling/resizing), and the model itself. Focusing now on a custom CNN architecture, but I'll make sure to note Transfer Learning as a potent alternative. I'm aiming for modular code design. I'm also considering batch processing for greater throughput.
Outlining Script Structure
I'm now detailing the script's functions. I have the training workflow in mind: configure the model, then the optimizer and loss. Training will be driven by model.fit() with validation data. The crucial steps of evaluation and saving/loading are firmly in place. Testing with unseen images is a priority. I'm focusing on the structure of the functions to ensure seamless execution.
Constructing Key Modules
I'm now integrating the train_model() and predict_image() functions to improve code organization. Also, I'm separating "Training" and "Inference" as distinct modules for better modularity. I'm adding comments to explain key steps, like why autotune is used. I'm also planning to check if a pre-trained model exists, loading it if so or training a new one, to simulate a proper automated production workflow.
Refining the Workflow
As I'm writing, I realized I must add data augmentation (RandomFlip, RandomRotation). I'll also check if the output layer has no activation, and switch from_logits accordingly, for enhanced numerical stability.
Clarifying Script Usability
I am now focusing on the practical aspects of script execution for all users, especially beginners. I want to include an explicit guide on folder structure setup, which is often a source of initial failure. This will be the title of the response. The final code is complete. I also added a "prerequisites" section for the folder structure to eliminate all those errors. I checked the code for correctness. I added a "Pro Tip" for Transfer Learning.
Choosing Data Loader
I recently pivoted from the outdated ImageDataGenerator towards image_dataset_from_directory. The speed advantage of the latter, along with its native integration with TensorFlow's tf.data.Dataset objects, makes it the clear winner for my current needs. This guarantees the highest possible throughput.
This script provides a complete, modular pipeline for automating image classification. It covers data loading, preprocessing, model training, saving, and running predictions on new images.
Prerequisites
-
Install Libraries:
pip install tensorflow numpy matplotlib
-
Directory Structure:
To automate the process, organize your training images into folders named after their class.
dataset/
├── cats/
│ ├── cat1.jpg
│ ├── cat2.jpg
├── dogs/
│ ├── dog1.jpg
│ └── dog2.jpg
The Python Script (classify.py)
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
# CONFIGURATION
DATA_DIR = 'dataset' # Folder name containing class subfolders
IMG_HEIGHT = 180
IMG_WIDTH = 180
BATCH_SIZE = 32
EPOCHS = 10
MODEL_PATH = 'my_image_classifier.keras'
def load_data():
"""
Loads images from directory and splits them into training and validation sets.
"""
if not os.path.exists(DATA_DIR):
raise FileNotFoundError(f"Directory '{DATA_DIR}' not found. Please create it.")
# Load Training Data
train_ds = tf.keras.utils.image_dataset_from_directory(
DATA_DIR,
validation_split=0.2,
subset="training",
seed=123,
image_size=(IMG_HEIGHT, IMG_WIDTH),
batch_size=BATCH_SIZE
)
# Load Validation Data
val_ds = tf.keras.utils.image_dataset_from_directory(
DATA_DIR,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(IMG_HEIGHT, IMG_WIDTH),
batch_size=BATCH_SIZE
)
class_names = train_ds.class_names
print(f"Classes found: {class_names}")
# Optimization: Cache and Prefetch to keep memory usage efficient
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
return train_ds, val_ds, class_names
def build_model(num_classes):
"""
Builds a Convolutional Neural Network (CNN).
Includes Data Augmentation and Normalization layers.
"""
data_augmentation = keras.Sequential(
[
layers.RandomFlip("horizontal", input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1),
]
)
model = Sequential([
data_augmentation,
layers.Rescaling(1./255), # Normalize pixel values to [0,1]
# Block 1
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# Block 2
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# Block 3
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# Flatten and Dense
layers.Dropout(0.2), # Prevent overfitting
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes) # No activation here, we use from_logits=True in loss
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
return model
def train_and_save():
"""
Orchestrates the loading, training, and saving process.
"""
print("--- Starting Training Pipeline ---")
train_ds, val_ds, class_names = load_data()
num_classes = len(class_names)
model = build_model(num_classes)
model.summary()
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=EPOCHS
)
# Save the model and the class names (as a customized metadata file or separate)
model.save(MODEL_PATH)
# Save class names to a text file for easy loading later
with open('class_names.txt', 'w') as f:
for name in class_names:
f.write(f"{name}\n")
print(f"--- Model saved to {MODEL_PATH} ---")
# Plot training results
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(range(EPOCHS), acc, label='Training Accuracy')
plt.plot(range(EPOCHS), val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(range(EPOCHS), loss, label='Training Loss')
plt.plot(range(EPOCHS), val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
def predict_image(image_path):
"""
Loads a saved model and predicts the class of a single image.
"""
if not os.path.exists(MODEL_PATH):
print("Model not found! Please train the model first.")
return
# Re-load class names
if os.path.exists('class_names.txt'):
with open('class_names.txt', 'r') as f:
class_names = [line.strip() for line in f.readlines()]
else:
print("Class names file missing.")
return
print(f"--- Predicting for: {image_path} ---")
model = tf.keras.models.load_model(MODEL_PATH)
# Load and preprocess image
img = tf.keras.utils.load_img(
image_path, target_size=(IMG_HEIGHT, IMG_WIDTH)
)
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
predicted_class = class_names[np.argmax(score)]
confidence = 100 * np.max(score)
print(f"Result: It is a {predicted_class} ({confidence:.2f}% confidence)")
return predicted_class, confidence
if __name__ == "__main__":
import sys
# Simple CLI argument handling
if len(sys.argv) > 1:
if sys.argv[1] == "train":
train_and_save()
elif sys.argv[1] == "predict" and len(sys.argv) > 2:
predict_image(sys.argv[2])
else:
print("Usage:")
print(" Train: python classify.py train")
print(" Predict: python classify.py predict <path_to_image>")
else:
# Default behavior if no args provided: Train
train_and_save()
How to use this script
1. Training the Model
Place your images in the dataset folder as described in the prerequisites. Run the script to train the neural network:
python classify.py train
This will load images, handle resizing/normalization, train a CNN, show a performance graph, and save the model to my_image_classifier.keras.
2. Predicting (Inference)
Once training is complete, use the script to classify a new image:
python classify.py predict "path/to/new_image.jpg"
Key Features of this Script
image_dataset_from_directory: This helps the script automatically detect labels based on folder names. It handles converting images to tensors automatically.
- Performance Optimization (
AUTOTUNE): Uses caching and prefetching. This allows the CPU to prepare the next batch of data while the GPU is training on the current batch, significantly speeding up training.
- Data Augmentation: Inside
build_model, we added random flips and rotations. This prevents the model from memorizing specific images (overfitting) and helps it generalize better to new data.
- Normalization Layer: We added
layers.Rescaling(1./255) inside the model. This ensures that when you use the model for prediction later, you don't have to remember to manually divide pixel math by 255; the model handles it internally.
- Modular Design: Separting
train and predict logic makes this script easy to integrate into a larger application (e.g., a Flask/Django web server).