Experiment 3
Experiment 3
Algorithm
1.Import the necessary libraries: TensorFlow, Keras, Matplotlib, and Numpy.
2.Load the CIFAR-10 dataset into X_train, y_train, X_test, and y_test.
3.Reshape the y_train and y_test labels from 2D to 1D using reshape(-1,).
4.Create a list classes containing the 10 class names (airplane, automobile, bird,
etc.).
5.Define a function plot_sample(X, y, index) to visualize a sample image with its
label.
6.Normalize the training and testing images by dividing pixel values by 255.
7.Define a sequential ANN model with a flatten layer, two dense layers with ReLU
activation, and an output dense layer with Softmax activation.
8.Compile the ANN model using the SGD optimizer, sparse categorical cross-
entropy loss, and accuracy as the metric.
9.Train the ANN model on the training data for 5 epochs using ann.fit().
10.Predict the test labels using the ANN model with ann.predict(), and convert
predicted probabilities to class labels using np.argmax().
11.Print the classification report to evaluate the ANN model's performance.
12.Define a sequential CNN model with two convolutional layers followed by max
pooling, a flatten layer, a dense layer with ReLU, and an output dense layer with
Softmax activation.
13.Compile the CNN model using the Adam optimizer, sparse categorical cross-
entropy loss, and accuracy as the metric.
14.Train the CNN model on the training data for 10 epochs using cnn.fit().
15.Evaluate the CNN model's performance on the test data using cnn.evaluate().
16.Predict the test labels using the CNN model with cnn.predict(), and convert
predicted probabilities to class labels using np.argmax().
17.Plot a sample image from the test set and display its predicted and actual
class labels using plot_sample().
Program
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import numpy as np
#Load the dataset
(X_train, y_train), (X_test,y_test) = datasets.cifar10.load_data()
X_train.shape
X_test.shape
y_train.shape
y_train[:5]
y_train = y_train.reshape(-1,)
y_train[:5]
y_test = y_test.reshape(-1,)
classes =
["airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"]
#Let's plot some images to see what they are
def plot_sample(X, y, index):
plt.figure(figsize = (15,2))
plt.imshow(X[index])
plt.xlabel(classes[y[index]])
plot_sample(X_train, y_train, 0)
plot_sample(X_train, y_train, 1)
#Normalizing the training data
X_train = X_train / 255.0
X_test = X_test / 255.0
#Build simple artificial neural network for image classification
ann = models.Sequential([
layers.Flatten(input_shape=(32,32,3)),
layers.Dense(3000, activation='relu'),
layers.Dense(1000, activation='relu'),
layers.Dense(10, activation='softmax')
])
ann.compile(optimizer='SGD',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
ann.fit(X_train, y_train, epochs=5)
from sklearn.metrics import confusion_matrix , classification_report
import numpy as np
y_pred = ann.predict(X_test)
y_pred_classes = [np.argmax(element) for element in y_pred]
print("Classification Report: \n", classification_report(y_test, y_pred_classes))
#Now let us build a convolutional neural network to train our images
cnn = models.Sequential([
layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu',
input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
cnn.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
cnn.fit(X_train, y_train, epochs=10)
cnn.evaluate(X_test,y_test)
y_pred = cnn.predict(X_test)
y_pred[:5]
y_classes = [np.argmax(element) for element in y_pred]
y_classes[:5]
y_test[:5]
plot_sample(X_test, y_test,3)
classes[y_classes[3]]
classes[y_classes[3]]
Dataset
In this notebook, we will classify small images CIFAR10 dataset from tensorflow
keras datasets. There are total 10 classes as shown below. We will use CNN for
classification
Output
Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
170498071/170498071 ━━━━━━━━━━━━━━━━━━━━ 3s 0us/step
(50000, 32, 32, 3)
(10000, 32, 32, 3)
(50000, 1)
array([[6],
[9],
[9],
[4],
[1]], dtype=uint8)
array([6, 9, 9, 4, 1], dtype=uint8)
/usr/local/lib/python3.10/dist-packages/keras/src/layers/reshaping/flatten.py:37:
UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer.
When using Sequential models, prefer using an `Input(shape)` object as the first
layer in the model instead.
super().__init__(**kwargs)
Epoch 1/5
1563/1563 ━━━━━━━━━━━━━━━━━━━━ 123s 79ms/step - accuracy: 0.3044 - loss:
1.9267
Epoch 2/5
1563/1563 ━━━━━━━━━━━━━━━━━━━━ 125s 80ms/step - accuracy: 0.4262 - loss:
1.6375
Epoch 3/5
1563/1563 ━━━━━━━━━━━━━━━━━━━━ 174s 111ms/step - accuracy: 0.4513 - loss:
1.5578
Epoch 4/5
1563/1563 ━━━━━━━━━━━━━━━━━━━━ 152s 79ms/step - accuracy: 0.4735 - loss:
1.4973
Epoch 5/5
1563/1563 ━━━━━━━━━━━━━━━━━━━━ 139s 78ms/step - accuracy: 0.4931 - loss:
1.4404
<keras.src.callbacks.history.History at 0x780adc0c44c0>
313/313 ━━━━━━━━━━━━━━━━━━━━ 8s 24ms/step
Classification Report:
precision recall f1-score support
‘airplane’
‘airplane’
Result