Q: Code a CNN using TensorFlow and Keras to classify CIFAR-10 dataset?

Introduction to CIFAR-10

The CIFAR-10 dataset is a popular benchmark dataset in machine learning, consisting of 60,000 32x32 color images in 10 different classes, with 6,000 images per class (e.g., airplane, car, bird, cat, etc.). This dataset is often used for training image classification models, and it provides a convenient starting point for beginners interested in deep learning.

Setting Up the Environment

First, ensure you have the necessary libraries installed:

pip install tensorflow keras

Importing the Libraries

Now, let's import the required libraries for our CNN:

import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, models # Set random seeds for reproducibility np.random.seed(42) tf.random.set_seed(42)

Loading the CIFAR-10 Dataset

Next, we'll load the CIFAR-10 dataset directly from Keras:

# Load dataset (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() # Normalize the data to values between 0 and 1 x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 # One-hot encode the labels y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10)

Here, we split the dataset into training and testing sets, normalized pixel values, and one-hot encoded the labels.

Building the CNN Model

Now it’s time to build our convolutional neural network. Here's a simple, yet effective architecture for classifying images:

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') ]) model.summary()

Explanation of Each Layer:

  • Conv2D Layers: These layers create convolution filters that help the model learn spatial hierarchies in the images.
  • MaxPooling2D Layers: After convolutional layers, pooling layers reduce the dimensionality and help capture the most important features.
  • Flatten Layer: This layer takes the 2D outputs from the convolutional layers and flattens them into a 1D array.
  • Dense Layers: These fully connected layers allow the model to make predictions based on the features learned from the previous layers.

Compiling the Model

After building the model, we must specify the optimizer, loss function, and metrics:

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

Training the Model

Let’s train our CNN with the training dataset:

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

Evaluating the Model

After training, we need to evaluate our model's performance on the test data:

test_loss, test_acc = model.evaluate(x_test, y_test) print("Test accuracy:", test_acc)

Visualizing Training History

It's useful to visualize the training and validation accuracy over epochs to understand how well our model is performing:

import matplotlib.pyplot as plt plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label='val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend() plt.show()

Conclusion

In this tutorial, we've constructed a CNN using TensorFlow and Keras to classify the CIFAR-10 dataset. We learned how to load the data, build a model, train it, and evaluate its performance. Don’t hesitate to play around with the model architecture or parameters to see how it influences the accuracy!

Popular Tags

Share now!