Image classification is a fundamental task in computer vision, where the goal is to assign a label (class) to an input image. In this tutorial, we’ll explore how to build an image classification model using TensorFlow and Keras. You can either use a pre-trained model or create your own custom convolutional neural network (CNN).
++
Pre-requisites
+Before we dive into the implementation, make sure you have the following installed:
+-
+
- Python (preferably Python 3.6 or later) +
- TensorFlow (install using pip install tensorflow) +
- Keras (included with TensorFlow) +
Workflow Overview
+-
+
- Data Preparation +
- Collect a labeled dataset of images. For example, you can use the Flower Photos dataset. +
- Organize the data into subdirectories, each representing a different class (e.g., roses, tulips, dandelions). +
- Load and Preprocess Data: +
- Use
tf.keras.utils.image_dataset_from_directory
to efficiently load images from disk.
+ - Resize images to a consistent size (e.g., 180x180 pixels). +
- Normalize pixel values to the range [0, 1]. +
- Model Building: +
- Choose between using a pre-trained model (transfer learning) or building your own CNN from scratch. +
- For transfer learning, load a pre-trained model (e.g., MobileNetV2, ResNet50) and fine-tune it for your specific task. +
- For custom CNN, design your architecture with convolutional layers, pooling layers, and fully connected layers. +
- Compile and Train the Model: +
- Compile the model with an appropriate optimizer, loss function, and evaluation metric. +
- Train the model on your labeled dataset. +
- Monitor training progress and adjust hyperparameters as needed. +
- Evaluate and Improve: +
- Evaluate the model’s performance on a validation set. +
- Address overfitting by using techniques like data augmentation and dropout. +
- Fine-tune the model based on evaluation results. +
- Prediction and Deployment: +
- Use the trained model to predict labels for new images. +
- Convert the model to TensorFlow Lite format for deployment on mobile devices or embedded systems. +
-
+
-
+
-
+
-
+
-
+
-
+
Example Code
+Below is a simplified example of building an image classification model using a custom CNN:
+ Python:+
+
+import tensorflow as tf
+from tensorflow.keras import layers
+
+# Load and preprocess data
+data_dir = "/path/to/flower_photos"
+batch_size = 32
+img_height, img_width = 180, 180
+
+train_ds = tf.keras.utils.image_dataset_from_directory(
+ data_dir,
+ validation_split=0.2,
+ subset="training",
+ seed=42,
+ image_size=(img_height, img_width),
+ batch_size=batch_size,
+)
+
+# Build a simple CNN
+model = tf.keras.Sequential([
+ layers.Conv2D(32, (3, 3), activation="relu", input_shape=(img_height, img_width, 3)),
+ layers.MaxPooling2D(),
+ layers.Flatten(),
+ layers.Dense(128, activation="relu"),
+ layers.Dense(num_classes, activation="softmax"), # num_classes = number of flower classes
+])
+
+# Compile the model
+model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
+
+# Train the model
+model.fit(train_ds, epochs=10)
+
+# Evaluate the model (on validation set)
+validation_ds = tf.keras.utils.image_dataset_from_directory(
+ data_dir,
+ validation_split=0.2,
+ subset="validation",
+ seed=42,
+ image_size=(img_height, img_width),
+ batch_size=batch_size,
+)
+model.evaluate(validation_ds)
+
+
+
+
+ Remember to replace /path/to/flower_photos
with the actual path to your dataset directory.
Conclusion
+Image classification with TensorFlow and Keras is a powerful technique that can be applied to various domains, from recognizing objects in photos to medical diagnosis. Experiment with different architectures, hyperparameters, and datasets to improve your model’s accuracy!
+