Build a Python script to automate image classification using TensorFlow.
- User
Build a Python script to automate image classification using TensorFlow.
- Assistant
Clarifying Python automation script requirements
The user wants to build a Python script for automating image classification with TensorFlow, but the requirements are a bit unclear. They haven't specified details like the dataset, architecture, or how to handle training and inference. I'll need to create a concise yet content-rich script using tf.keras and ImageDataGenerator or tf.data. The script should include everything from loading the dataset to model training and saving the output. I’ll also consider necessary packages like TensorFlow, Pillow, and NumPy while keeping explanations brief.Designing the image classifier script
I'm working on designing a minimal, reproducible example for an image classification script that accommodates multi-class datasets. The structure should ideally have a single 'data_dir' with 'train', 'val', and 'test' subdirectories. The script outline starts with necessary imports, a clear argparse setup for parameters like image size and batch size, and a dataset creation method using
image_dataset_from_directory. I’ll also implement data augmentation and use TensorFlow's AUTOTUNE for efficiency. This approach sets a solid foundation for the user!Building the model for image classificationI'm setting up a model using MobileNetV2 as the base, starting with input dimensions and initial training settings. I'll include data augmentation and preprocessing, followed by global average pooling and dropout layers leading to a softmax output for multi-class classification. During training, I'll use callbacks like EarlyStopping and ModelCheckpoint, and I'll evaluate the model on a test dataset. Given the user's request for automation, I might add an optional
--predict_dirbut could also revise the structure to integrate training and prediction modes using subcommands.Finalizing the script designI'm thinking about how to structure the script to balance conciseness and clarity. I want to include both training and prediction modes with appropriate arguments. For the 'train' mode, I'll require
--data_dir, while 'predict' will need--model_pathand either--predict_diror--image_path. It’s clear that automation should cover inference, so I’ll implement a function for running inference on new images. I’ll also save class names directly in the model as a JSON file for simplicity, ensuring everything is neatly organized.Integrating training and prediction in one scriptI'm designing a script that efficiently combines both training and prediction features while keeping it user-friendly. The script will use argparse to set up parameters such as mode, directories, and image dimensions. For training, it will load datasets directly from the specified directory structure and employ data augmentation. In prediction mode, I'll load the trained model, read class names, and process images accordingly. It’s important to ensure that both functionalities are clearly defined, avoiding unnecessary complexity while providing clear usage instructions within the script. I’ll also include crucial imports and settings for reproducibility.Building model and data loading functions
I'm developing a data augmentation function that includes horizontal flipping, rotation, and zoom. Next, I will build the model using MobileNetV2 and set it up for training with a specific learning rate. For loading datasets, I'll ensure proper paths for training, validation, and test images, and shuffle only for training. Validations will be checked for directory structure, and class names will be saved. The training process will include early stopping and model checkpointing, keeping everything streamlined for both training and prediction functionalities within a single script.Finalizing the image classification script
I realize that the base model requires fixed input sizes, so if different-sized images are used, Keras will encounter mismatched dimensions. I’ll ensure users specify the same dimensions used during training. To enhance robustness, I’ll derive the image dimensions directly from the model. There's no need for command line inputs regarding image height and width for prediction.
I’ll include a clear explanation of the dataset structure and usage instructions at the top of the script. Keeping everything neat and precise! Below is a self‑contained Python script that:
- Trains an image classifier using TensorFlow/Keras (with MobileNetV2 transfer learning)
- Saves the model and class names
- Can later be used to classify new images or a folder of images
It assumes a standard directory layout for your dataset (shown below).
1. Expected dataset structure
Put your images into
train,val, and optionaltestsubfolders, with one subfolder per class:data/ train/ class_a/ img001.jpg img002.jpg ... class_b/ ... ... val/ class_a/ class_b/ ... test/ # optional class_a/ class_b/ ...Class names are taken from these subfolder names.
2. The script:
image_classifier.py#!/usr/bin/env python3 """ TensorFlow image classification trainer & predictor. Dataset directory structure (required for training): data_root/ train/ class_1/ img001.jpg ... class_2/ ... ... val/ class_1/ class_2/ ... test/ # optional class_1/ class_2/ ... Usage examples: # Train a model python image_classifier.py \ --mode train \ --data_dir ./data \ --epochs 10 \ --batch_size 32 \ --model_path ./image_classifier.h5 # Predict on a single image python image_classifier.py \ --mode predict \ --model_path ./image_classifier.h5 \ --image_path ./some_image.jpg # Predict on all images in a folder python image_classifier.py \ --mode predict \ --model_path ./image_classifier.h5 \ --predict_dir ./unseen_images """ import argparse import glob import os from pathlib import Path import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # ----------------------------- # Data loading # ----------------------------- def load_datasets(data_dir, img_height, img_width, batch_size): """Load train/val/(optional) test datasets from directory.""" AUTOTUNE = tf.data.AUTOTUNE train_dir = os.path.join(data_dir, "train") val_dir = os.path.join(data_dir, "val") test_dir = os.path.join(data_dir, "test") if not os.path.isdir(train_dir) or not os.path.isdir(val_dir): raise ValueError( f"`data_dir` must contain 'train' and 'val' subdirectories. " f"Got: {data_dir}" ) train_ds = tf.keras.utils.image_dataset_from_directory( train_dir, image_size=(img_height, img_width), batch_size=batch_size, label_mode="int", shuffle=True, ) val_ds = tf.keras.utils.image_dataset_from_directory( val_dir, image_size=(img_height, img_width), batch_size=batch_size, label_mode="int", shuffle=False, ) class_names = train_ds.class_names train_ds = train_ds.prefetch(AUTOTUNE) val_ds = val_ds.prefetch(AUTOTUNE) test_ds = None if os.path.isdir(test_dir): test_ds = tf.keras.utils.image_dataset_from_directory( test_dir, image_size=(img_height, img_width), batch_size=batch_size, label_mode="int", shuffle=False, ) test_ds = test_ds.prefetch(AUTOTUNE) return train_ds, val_ds, test_ds, class_names # ----------------------------- # Model building # ----------------------------- def build_data_augmentation(): return keras.Sequential( [ layers.RandomFlip("horizontal"), layers.RandomRotation(0.1), layers.RandomZoom(0.1), ], name="data_augmentation", ) def build_model(num_classes, img_height, img_width, learning_rate=1e-4): """Build a transfer-learning model using MobileNetV2.""" data_augmentation = build_data_augmentation() base_model = tf.keras.applications.MobileNetV2( input_shape=(img_height, img_width, 3), include_top=False, weights="imagenet", ) base_model.trainable = False # freeze base inputs = keras.Input(shape=(img_height, img_width, 3)) x = data_augmentation(inputs) x = tf.keras.applications.mobilenet_v2.preprocess_input(x) x = base_model(x, training=False) x = layers.GlobalAveragePooling2D()(x) x = layers.Dropout(0.2)(x) outputs = layers.Dense(num_classes, activation="softmax")(x) model = keras.Model(inputs, outputs) model.compile( optimizer=keras.optimizers.Adam(learning_rate=learning_rate), loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) return model # ----------------------------- # Utilities for class names # ----------------------------- def save_class_names(class_names, output_path): with open(output_path, "w", encoding="utf-8") as f: for name in class_names: f.write(name + "\n") def load_class_names(path): with open(path, "r", encoding="utf-8") as f: return [line.strip() for line in f if line.strip()] # ----------------------------- # Training # ----------------------------- def train(args): tf.random.set_seed(42) print(f"Loading data from {args.data_dir} ...") train_ds, val_ds, test_ds, class_names = load_datasets( args.data_dir, args.img_height, args.img_width, args.batch_size ) num_classes = len(class_names) print(f"Found {num_classes} classes: {class_names}") print("Building model...") model = build_model( num_classes, img_height=args.img_height, img_width=args.img_width, learning_rate=args.learning_rate, ) model.summary() callbacks = [ tf.keras.callbacks.EarlyStopping( monitor="val_loss", patience=args.patience, restore_best_weights=True, ), tf.keras.callbacks.ModelCheckpoint( filepath=args.model_path, monitor="val_loss", save_best_only=True, ), ] print("Starting training...") history = model.fit( train_ds, validation_data=val_ds, epochs=args.epochs, callbacks=callbacks, ) # Evaluate on test set if available if test_ds is not None: print("Evaluating on test set...") test_loss, test_acc = model.evaluate(test_ds, verbose=0) print(f"Test loss: {test_loss:.4f} | Test accuracy: {test_acc:.4f}") # Save the final model (best weights already saved by checkpoint) model.save(args.model_path) print(f"Model saved to {args.model_path}") # Save class names alongside the model class_names_path = ( args.class_names_path if args.class_names_path else os.path.splitext(args.model_path)[0] + "_classes.txt" ) save_class_names(class_names, class_names_path) print(f"Class names saved to {class_names_path}") # ----------------------------- # Prediction # ----------------------------- def collect_image_paths(image_path=None, predict_dir=None): paths = [] if image_path: paths.append(image_path) if predict_dir: exts = ("*.jpg", "*.jpeg", "*.png", "*.bmp") for ext in exts: paths.extend(glob.glob(os.path.join(predict_dir, ext))) paths = sorted(set(paths)) if not paths: raise ValueError( "No images found. Provide --image_path or --predict_dir with images." ) return paths def predict(args): if not os.path.isfile(args.model_path): raise FileNotFoundError(f"Model not found: {args.model_path}") print(f"Loading model from {args.model_path} ...") model = tf.keras.models.load_model(args.model_path) # Infer input size from the model itself input_shape = model.input_shape if isinstance(input_shape, list): # handle possible multiple inputs input_shape = input_shape[0] _, img_height, img_width, _ = input_shape # Load class names class_names_path = args.class_names_path if class_names_path is None: guessed = os.path.splitext(args.model_path)[0] + "_classes.txt" class_names_path = guessed if os.path.isfile(guessed) else None class_names = None if class_names_path and os.path.isfile(class_names_path): class_names = load_class_names(class_names_path) print(f"Loaded class names from {class_names_path}") else: print("No class names file found. Predictions will use numeric class IDs.") image_paths = collect_image_paths(args.image_path, args.predict_dir) print(f"Found {len(image_paths)} image(s) to classify.") for path in image_paths: img = tf.keras.utils.load_img(path, target_size=(img_height, img_width)) img_array = tf.keras.utils.img_to_array(img) img_array = np.expand_dims(img_array, axis=0) # (1, H, W, 3) preds = model.predict(img_array, verbose=0) probs = preds[0] class_id = int(np.argmax(probs)) confidence = float(probs[class_id]) if class_names and class_id < len(class_names): label = class_names[class_id] else: label = str(class_id) print(f"{path}: {label} ({confidence * 100:.2f}% confidence)") # ----------------------------- # Argument parsing & main # ----------------------------- def parse_args(): parser = argparse.ArgumentParser( description="Train and run an image classifier using TensorFlow/Keras." ) parser.add_argument( "--mode", choices=["train", "predict"], default="train", help="Mode: 'train' to train a model, 'predict' to classify images.", ) # Common parser.add_argument( "--model_path", type=str, default="image_classifier.h5", help="Path to save (train) or load (predict) the Keras model.", ) parser.add_argument( "--class_names_path", type=str, help="Path to save/load class names. " "Defaults to <model_path>_classes.txt.", ) # Training options parser.add_argument( "--data_dir", type=str, help="Root data directory containing train/val(/test) subfolders (for training).", ) parser.add_argument( "--img_height", type=int, default=224, help="Image height for training.", ) parser.add_argument( "--img_width", type=int, default=224, help="Image width for training.", ) parser.add_argument( "--batch_size", type=int, default=32, help="Batch size for training.", ) parser.add_argument( "--epochs", type=int, default=10, help="Number of training epochs.", ) parser.add_argument( "--learning_rate", type=float, default=1e-4, help="Learning rate for Adam optimizer.", ) parser.add_argument( "--patience", type=int, default=3, help="Early stopping patience (epochs).", ) # Prediction options parser.add_argument( "--image_path", type=str, help="Path to a single image to classify (for predict mode).", ) parser.add_argument( "--predict_dir", type=str, help="Directory of images to classify (for predict mode).", ) return parser.parse_args() def main(): args = parse_args() if args.mode == "train": if not args.data_dir: raise ValueError("--data_dir is required in train mode.") train(args) elif args.mode == "predict": if not args.image_path and not args.predict_dir: raise ValueError( "In predict mode, provide --image_path or --predict_dir." ) predict(args) if __name__ == "__main__": main()
3. How to use
- Install dependencies (CPU version shown; use
tensorflow-gpuif desired):
pip install tensorflow-
Put your data in the
train/,val/, and optionaltest/subfolders as described. -
Train:
python image_classifier.py \ --mode train \ --data_dir ./data \ --epochs 10 \ --batch_size 32 \ --model_path ./image_classifier.h5- Predict on a single image:
python image_classifier.py \ --mode predict \ --model_path ./image_classifier.h5 \ --image_path ./example.jpg- Predict on a folder of images:
python image_classifier.py \ --mode predict \ --model_path ./image_classifier.h5 \ --predict_dir ./unseen_imagesIf you want to tweak the architecture (e.g., different base network, more layers), modify
build_model()in the script.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.