Apply CNN for Image Classification

Aim

To implement a Convolutional Neural Network (CNN) for image classification on a sample dataset using Python and TensorFlow/Keras, demonstrating the training and evaluation process.


Algorithm

  1. Load Dataset: Use a standard image classification dataset (e.g., CIFAR-10).

  2. Preprocess Data: Normalize pixel values and convert labels to categorical format.

  3. Define CNN Model:

    • Convolutional layers with ReLU activation.

    • Pooling layers (max-pooling) for downsampling.

    • Fully connected (dense) layers for classification.

    • Output layer with softmax activation for multi-class classification.

  4. Compile Model: Specify optimizer (e.g., Adam), loss function (categorical crossentropy), and evaluation metrics.

  5. Train Model: Fit model on training data with validation split.

  6. Evaluate Model: Assess performance on test data.

  7. Make Predictions: Use trained model to classify images.


Program (Python – TensorFlow/Keras)de

python
import tensorflow as tf from tensorflow.keras import datasets, layers, models from tensorflow.keras.utils import to_categorical # 1. Load dataset (X_train, y_train), (X_test, y_test) = datasets.cifar10.load_data() # 2. Preprocess data X_train, X_test = X_train / 255.0, X_test / 255.0 y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) # 3. Define CNN model model = models.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.Conv2D(64, (3,3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(10, activation='softmax') ]) # 4. Compile model model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 5. Train model history = model.fit(X_train, y_train, epochs=10, batch_size=64, validation_split=0.2) # 6. Evaluate model test_loss, test_acc = model.evaluate(X_test, y_test) print(f"Test accuracy = {test_acc:.4f}") # 7. Predict (example) import numpy as np sample_image = np.expand_dims(X_test[0], axis=0) prediction = model.predict(sample_image) predicted_class = np.argmax(prediction) print("Predicted class:", predicted_class)

Output

  • Training and validation accuracy and loss per epoch are displayed.

  • Final test accuracy is printed, e.g.,

    text
    Test accuracy = 0.72
  • Predicted class for the sample image is printed, e.g.,

    text
    Predicted class: 3

Result

  • The CNN successfully learns visual features to classify CIFAR-10 images with good accuracy.

  • Convolutional layers extract hierarchical features, pooling reduces dimensionality, and dense layers perform classification.

  • Model training improves accuracy through backpropagation and weight updating.

  • This lab illustrates essential CNN concepts and typical workflow for image classification.