0% found this document useful (0 votes)
9 views11 pages

DL Experiment 4

The document outlines an experiment using TensorFlow to implement the LeNet model for image classification on the MNIST and CIFAR-10 datasets. It includes steps for loading, preprocessing the data, defining the model architecture, training, and evaluating the model's performance. Additionally, it provides visualization of sample images from the CIFAR-10 dataset.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

DL Experiment 4

The document outlines an experiment using TensorFlow to implement the LeNet model for image classification on the MNIST and CIFAR-10 datasets. It includes steps for loading, preprocessing the data, defining the model architecture, training, and evaluating the model's performance. Additionally, it provides visualization of sample images from the CIFAR-10 dataset.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Experiment - 4

Performing LetNet

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.utils import to_categorical

# Load and preprocess the MNIST dataset


(train_images, train_labels), (test_images, test_labels) =
datasets.mnist.load_data()

# Normalize pixel values to be between 0 and 1


train_images, test_images = train_images / 255.0, test_images /
255.0

# Reshape the images to (28, 28, 1)


train_images = train_images.reshape(train_images.shape[0], 28,
28, 1)
test_images = test_images.reshape(test_images.shape[0], 28, 28,
1)

# Convert class vectors to one-hot encoded labels


train_labels = to_categorical(train_labels, 10)
test_labels = to_categorical(test_labels, 10)
# Define the LeNet model
def build_lenet(input_shape, num_classes):
model = models.Sequential()

model.add(layers.Conv2D(6, (5, 5), activation='relu',


input_shape=input_shape))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(16, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(120, activation='relu'))
model.add(layers.Dense(84, activation='relu'))
model.add(layers.Dense(num_classes, activation='softmax'))

return model

# Specify input shape and number of classes


input_shape = (28, 28, 1)
num_classes = 10

# Build the LeNet model


model = build_lenet(input_shape, num_classes)

# Compile the model


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

# Train the model


history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))

# Evaluate the model


test_loss, test_acc = model.evaluate(test_images, test_labels,
verbose=2)
print(f'Test accuracy: {test_acc}')
# Save the model if needed
# model.save('lenet_mnist.h5')

Output:-
import tensorflow as tf
import matplotlib.pyplot as plt

# Load CIFAR-10 dataset


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

# Define class names (for CIFAR-10)


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

# Choose an image to visualize (change the index as needed)


image_index = 1

# Display the image


plt.figure()
plt.imshow(x_train[image_index])
plt.colorbar()
plt.grid(False)
plt.title(f'Label: {class_names[y_train[image_index][0]]}')
plt.show()

Label:-
import tensorflow as tf
import matplotlib.pyplot as plt

# Load CIFAR-10 dataset


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

# Define class names (for CIFAR-10)


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

# Choose an image to visualize (change the index as needed)


image_index = 0

# Display the image with improved interpolation


plt.figure()
plt.imshow(x_train[image_index], interpolation='nearest')
plt.colorbar()
plt.grid(False)
plt.title(f'Label: {class_names[y_train[image_index][0]]}')
plt.show()

Label:-
import tensorflow as tf
import matplotlib.pyplot as plt

# Load CIFAR-10 dataset


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

# Define class names (for CIFAR-10)


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

# Choose an image to visualize (change the index as needed)


image_index = 234

# Set a larger figure size for improved clarity


plt.figure(figsize=(5, 5))
plt.imshow(x_train[image_index])
plt.colorbar()
plt.grid(False)
plt.title(f'Label: {class_names[y_train[image_index][0]]}')
plt.show()

Label:-
import tensorflow as tf
import matplotlib.pyplot as plt

# Load CIFAR-10 dataset


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

# Define class names (for CIFAR-10)


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

# Choose an image to visualize (change the index as needed)


image_index = 990

# Set a larger figure size for improved clarity


plt.figure(figsize=(5, 5))
plt.imshow(x_train[image_index])
plt.grid(False)
plt.title(f'Class: {class_names[y_train[image_index][0]]}')
plt.axis('off') # Turn off axis labels
plt.show()

Label:-
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical

# Load CIFAR-10 dataset


(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# Normalize pixel values to be between 0 and 1


x_train, x_test = x_train / 255.0, x_test / 255.0

# Convert class vectors to one-hot encoded labels


y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

# Define the LeNet-5 model


model = models.Sequential()
model.add(layers.Conv2D(6, (5, 5), activation='relu',
input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(16, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(120, activation='relu'))
model.add(layers.Dense(84, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

# Compile the model


model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=10, validation_data=(x_test,
y_test))

# Evaluate the model


test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'Test accuracy: {test_acc}')

Output:-

import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
import numpy as np

# Load MNIST dataset


(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize pixel values to be between 0 and 1
x_train, x_test = x_train / 255.0, x_test / 255.0

# Resize the images to 32x32


x_train_resized = []
x_test_resized = []

for img in x_train:


x_train_resized.append(tf.image.resize(tf.expand_dims(img,
axis=-1), (32, 32)).numpy())

for img in x_test:


x_test_resized.append(tf.image.resize(tf.expand_dims(img,
axis=-1), (32, 32)).numpy())

x_train = np.array(x_train_resized)
x_test = np.array(x_test_resized)

# Convert class vectors to one-hot encoded labels


y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

# Define the LeNet-5 model


model = models.Sequential()
model.add(layers.Conv2D(6, (5, 5), activation='relu',
input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(16, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(120, activation='relu'))
model.add(layers.Dense(84, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])

# Train the model


model.fit(x_train, y_train, epochs=2, batch_size=128,
validation_data=(x_test, y_test))

# Evaluate the model


test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'Test accuracy: {test_acc}')

Output:-

You might also like