The user wants a Python script to automate image classification using TensorFlow.
This is a broad request, so I need to narrow it down to a functional, understandable, and practical example.
A complete solution usually involves:
- Prerequisites: Installing necessary libraries (TensorFlow, NumPy, Matplotlib).
- Data Loading: Using a dataset. The 'cats vs dogs' or 'flowers' dataset are common, but
tf.keras.utils.image_dataset_from_directory is the modern, robust way to handle custom folders. For a standalone script that runs immediately without downloading external zip files manually, using a built-in dataset like cifar10 or mnist is safer. However, "image classification" usually implies colored images (like cats vs dogs). I will provide a structure that supports a custom directory structure but also provide a snippet to download a sample dataset (like the flowers dataset) to make it runnable out-of-the-box.
- Preprocessing: Resizing, rescaling, maybe augmentation.
- Model Building: A Convolutional Neural Network (CNN) is the standard. I should use the Keras Sequential API for simplicity.
- Training: Compiling and fitting the model.
- Evaluation: Checking accuracy/loss.
- Prediction/Inference: A function to classify a new image.
Plan:
- Setup: Imports.
- Data Preparation: I will write the code to expect a directory of images (e.g.,
data/class_a, data/class_b). To make the script actually runnable for the user immediately, I will include a helper function to download and unzip the "Flowers" dataset from Google storage (a common TensorFlow tutorial practice).
- Pipeline: Use
image_dataset_from_directory. It's efficient and handles batching/shuffling.
- Model: A simple CNN (Conv2D -> MaxPooling -> Flatten -> Dense).
- Training: Standard
model.fit.
- Saving: Save the model.
- Inference: A function that takes an image path and returns the class name.
Refining the code:
- Use
tf.keras.
- Include Data Augmentation layers inside the model (modern Keras best practice).
- Use
Adam optimizer and SparseCategoricalCrossentropy.
- Add comments explaining why we are doing things.
Self-Correction/Constraint Check:
- The user asked for "automation". This implies the script should run end-to-end.
- I should avoid over-engineering (like using Transfer Learning/ResNet) unless necessary, to keep the code readable. However, a simple CNN takes a long time to converge on complex data. I'll stick to a simple CNN for educational value but mention Transfer Learning.
- Decision: I will provide a complete script that downloads a sample dataset, trains on it, and then demonstrates how to predict.
Structure of the response:
- Prerequisites: What to install (
pip install...).
- The Directory Structure: Explain how the data should look.
- The Python Script: The full code.
- Explanation: Walkthrough of the steps.
- How to run: Instructions.
Let's write the code mental draft:
- Import tensorflow, pathlib, etc.
- Define constants (batch_size, img_height, img_width).
- Download dataset (tf.keras.utils.get_file).
- Split into train/val using
image_dataset_from_directory.
- Configure performance (
prefetch, cache).
- Define Model:
- Rescaling
- Conv2D(32) -> MaxPool
- Conv2D(64) -> MaxPool
- Conv2D(128) -> MaxPool
- Flatten
- Dense(128) -> Dense(num_classes)
- Compile.
- Fit.
- Predict function: Load image ->
img_to_array -> expand_dims -> model.predict.
This looks solid. I will write the response based on this plan.
Here is a complete, step-by-step Python script to automate image classification.
This script uses TensorFlow and Keras. It is designed to work with a folder-based dataset (where images are sorted into subfolders by class name).
1. Prerequisites
You will need to install TensorFlow and Matplotlib:
pip install tensorflow matplotlib numpy
2. The Dataset Structure
For this script to work, organize your images on your hard drive like this:
dataset_directory/
├── class_a/
│ ├── image1.jpg
│ ├── image2.jpg
├── class_b/
│ ├── image1.jpg
│ ├── image2.jpg
(The script will automatically detect the class names based on the folder names).
3. The Python Script
Save the following code as 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
import pathlib
# --- CONFIGURATION ---
# Replace this with the path to your image folder
DATASET_PATH = "path/to/your/dataset_directory"
BATCH_SIZE = 32
IMG_HEIGHT = 180
IMG_WIDTH = 180
EPOCHS = 10
def build_dataset():
"""Loads and splits the data into training and validation sets."""
print("Loading dataset...")
# Use 80% of images for training
train_ds = tf.keras.utils.image_dataset_from_directory(
DATASET_PATH,
validation_split=0.2,
subset="training",
seed=123,
image_size=(IMG_HEIGHT, IMG_WIDTH),
batch_size=BATCH_SIZE
)
# Use 20% of images for validation
val_ds = tf.keras.utils.image_dataset_from_directory(
DATASET_PATH,
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}")
# Cache and prefetch data for performance
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 create_model(num_classes):
"""Creates a Convolutional Neural Network (CNN)."""
model = Sequential([
# Input Layer: Resizing is already done, but we need to normalize pixel values
layers.Rescaling(1./255, input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)),
# Convolutional Block 1
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# Convolutional Block 2
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# Convolutional Block 3
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# Flattening and Dense Layers
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes) # Output layer (no activation implies linear/logits)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
return model
def plot_history(history):
"""Visualizes training results."""
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(EPOCHS)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
def predict_image(model, class_names, img_path):
"""Predicts the class of a single new image."""
if not os.path.exists(img_path):
print(f"Image not found: {img_path}")
return
img = tf.keras.utils.load_img(
img_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])
print(
"This image most likely belongs to {} with a {:.2f} percent confidence."
.format(class_names[np.argmax(score)], 100 * np.max(score))
)
# --- MAIN EXECUTION FLOW ---
if __name__ == "__main__":
# 1. Prepare Data
train_data, val_data, classes = build_dataset()
num_classes = len(classes)
# 2. Build Model
model = create_model(num_classes)
model.summary()
# 3. Train Model
print("\nStarting training...")
history = model.fit(
train_data,
validation_data=val_data,
epochs=EPOCHS
)
# 4. Visualize Results
plot_history(history)
# 5. Save Model
model.save('image_classifier.keras')
print("Model saved as image_classifier.keras")
# 6. Example Prediction (Uncomment to test)
# predict_image(model, classes, "path/to/a/new_image.jpg")
Key Components Explained
image_dataset_from_directory: This is a powerful utility in TensorFlow. It reads images from your disk, converts them to tensors, resizes them, groups them into batches, and automatically assigns labels (0, 1, 2...) based on the folder names.
- Data Augmentation (Optional): The code above assumes you have enough data. If your dataset is small, you should add data augmentation layers immediately after the
Rescaling layer to generate variations of your images (flips, rotations) to prevent overfitting.
- CNN Architecture:
- Conv2D: "Scans" the image to find features (edges, textures).
- MaxPooling: Reduces the image size to make computation faster and focus on important features.
- Flatten/Dense: Takes the visual features and makes the final classification decision.
from_logits=True: The final layer does not have an activation function (it outputs raw numbers called logits). We handle the probability calculation inside the loss function for numerical stability.
How to Run It
- Create a folder named
dataset.
- Inside, create folders for your classes (e.g.,
cats and dogs). Put the images inside.
- Update the
DATASET_PATH variable in the script to point to your dataset folder.
- Run the script:
python classify.py.