Create an Image Classifier with TensorFlow ๐Ÿ“ธ๐Ÿค–

Rajil TL
4 Min Read
Disclosure: This website may contain affiliate links, which means I may earn a commission if you click on the link and make a purchase. I only recommend products or services that I personally use and believe will add value to my readers. Your support is appreciated!

Image classification is a fundamental computer vision task that allows AI to identify and categorize objects in images. With TensorFlow and Keras, we can easily build a powerful deep learning model to classify images.

What is Image Classification? ๐Ÿ–ผ๏ธ๐Ÿ”

Image classification is the process of assigning a label (class) to an image based on its contents. AI models learn to recognize patterns and distinguish between different categories, such as:

  • โœ… Cats vs. Dogs ๐Ÿฑ๐Ÿถ
  • โœ… Healthy vs. Diseased Plants ๐ŸŒฑ๐Ÿšจ
  • โœ… Vehicles: Cars, Bikes, Trucks ๐Ÿš—๐Ÿ๏ธ๐Ÿš›

๐Ÿ“ Real-World Applications:

  • ๐Ÿš— Self-Driving Cars โ€“ Detecting pedestrians and road signs.
  • ๐Ÿฅ Medical Diagnosis โ€“ Identifying diseases from X-rays.
  • ๐Ÿ“น Security Surveillance โ€“ Recognizing suspicious activity.

Setting Up the Development Environment ๐Ÿ› ๏ธ

๐Ÿ”น Install TensorFlow & Required Libraries

pip install tensorflow numpy matplotlib opencv-python

Import Necessary Libraries ๐Ÿ“‚

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt

Load and Preprocess the Dataset ๐Ÿ“Š

(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

class_names = ["airplane", "automobile", "bird", "cat", "deer",
               "dog", "frog", "horse", "ship", "truck"]

๐Ÿ”น Visualize Sample Images

plt.figure(figsize=(10, 5))
for i in range(10):
    plt.subplot(2, 5, i+1)
    plt.imshow(x_train[i])
    plt.title(class_names[y_train[i][0]])
    plt.axis("off")
plt.show()

Build the Convolutional Neural Network (CNN) ๐Ÿง 

model = keras.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])

๐Ÿ”น Compile and Train the Model

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))

๐Ÿ”น Visualize Training Progress

plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

Evaluate and Test the Model ๐Ÿ“Š

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"Test Accuracy: {test_acc * 100:.2f}%")

๐Ÿ”น Make Predictions on New Images

import random
index = random.randint(0, len(x_test) - 1)
image = x_test[index]
true_label = class_names[y_test[index][0]]

predictions = model.predict(np.expand_dims(image, axis=0))
predicted_label = class_names[np.argmax(predictions)]

plt.imshow(image)
plt.title(f"True: {true_label} | Predicted: {predicted_label}")
plt.axis("off")
plt.show()

Save and Load the Model for Future Use ๐Ÿ’พ

model.save("image_classifier.h5")
loaded_model = keras.models.load_model("image_classifier.h5")

Improving the Image Classifier ๐Ÿ”ฅ

  • โœ… Data Augmentation โ€“ Apply transformations to improve training.
  • โœ… Using a More Powerful CNN โ€“ Add extra layers.
  • โœ… Transfer Learning โ€“ Use a pre-trained model like MobileNetV2.
base_model = keras.applications.MobileNetV2(weights='imagenet', include_top=False, input_shape=(32, 32, 3))

Real-World Applications of AI-Powered Image Classification ๐ŸŒŽ

  • ๐Ÿ“ท Face Recognition โ€“ AI detects faces for security.
  • ๐Ÿฅ Medical Imaging โ€“ AI classifies X-rays and MRI scans.
  • ๐Ÿ›๏ธ E-Commerce โ€“ AI recommends products based on images.
  • ๐Ÿš— Autonomous Vehicles โ€“ AI classifies traffic signs.

Conclusion ๐Ÿ†

In this tutorial, we built an AI-powered image classifier using TensorFlow and CNNs. We covered:

  • โœ… Data loading & preprocessing
  • โœ… Building a CNN model
  • โœ… Training & evaluating performance
  • โœ… Making predictions

๐Ÿš€ Ready to take it further? Try training the model on your own custom dataset!

Share This Article

Rajil TL is a SenseCentral contributor focused on tech, apps, tools, and product-building insights. He writes practical content for creators, founders, and learnersโ€”covering workflows, software strategies, and real-world implementation tips. His style is direct, structured, and action-oriented, often turning complex ideas into step-by-step guidance. Heโ€™s passionate about building useful digital products and sharing what works.