exno 4
exno 4
No:4 Image classification on MNIST dataset(CNN model with fully connected layer)
Aim
To write a python program for image classification on MNIST dataset(CNN
model with fully connected layer).
Algorithm
1 Start by importing the libraries needed for data manipulation, model creation, and visualization:
- matplotlib.pyplot for plotting images and results.
- numpy for numerical operations and array manipulation.
- tensorflow.keras components for loading the dataset, building the model, and training it.
2. Load the Data: Obtain the MNIST dataset using mnist.load_data(). This dataset contains images
of handwritten digits and their corresponding labels.
- Normalize the Data: Convert the pixel values of the images to a range between 0 and 1. This is
done by dividing the pixel values by 255.0.
- Expand Dimensions: Add an extra dimension to the images to represent the color channel
(grayscale in this case), making the shape compatible with the model input.
- One-Hot Encode Labels: Convert the categorical labels (0 through 9) into one-hot encoded
format, which is necessary for multi-class classification in neural networks.
3. Initialize the Model: Create an instance of the Sequential model, which allows you to stack layers
in a linear fashion.
- Add Convolutional Layers:
- The first convolutional layer detects features using 32 filters with a 3x3 kernel. It requires the
input shape of (28, 28, 1) due to the grayscale images.
- Follow it with a max pooling layer to reduce the spatial dimensions of the feature maps.
- Add a second convolutional layer with 64 filters, followed by another max pooling layer.
- Flatten the Data: Convert the 2D feature maps into a 1D vector to feed into fully connected
layers.
- Add Fully Connected Layers: Insert a dense layer with 128 neurons and ReLU activation to
capture high-level features.
- Add Output Layer: The final layer has 10 neurons with softmax activation to produce class
probabilities for each of the 10 digit classes.
4. Compile the Model: Specify the optimizer (adam), the loss function (categorical_crossentropy),
and the evaluation metric (accuracy).
- Train the Model: Fit the model to the training data for a set number of epochs (5 in this case),
using a batch size of 32. Validate the performance on the test data.
Program
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.utils import to_categorical
predictions = model.predict(x_test)
for i in range(10):
plt.imshow(x_test[i].reshape(28, 28), cmap='gray')
plt.title('Predicted: {}, Actual: {}'.format(np.argmax(predictions[i]), np.argmax(y_test[i])))
plt.show()
Output
Result:
Thus the program to write image classification on MNIST dataset (CNN
model with fully connected layer) was written and executed successfully.