Affiliated to Dr. A.P.J.
Abdul Kalam Technical University,
Uttar Pradesh, Lucknow
Department of Computer Science & Engineering and Allied
Branches
Practical Lab File
Session: 2025 -26
Course: B. Tech.
Year: 4th
Branch: CSE-DS
Subject: DEEP LEARNING LAB
Subject Code: BAI-751
Name:
Roll No.:
Section:
Name of Instructor: Mr. Rahul Bharti
Deep Learning Lab File
S. No. Name of the Program Date Signature
Design a single unit perceptron for classification of a linearly 27-Aug-2025
separable binary dataset without using pre-defined models. Use the
1 Perceptron() fromsklearn.
Build an Artificial Neural Network by implementing the 03-Sep-2025
2 Backpropagation algorithm and test the same using appropriate data
sets. Vary the activation functions used and compare the results.
Build a Deep Feed Forward ANN by implementing the 10-Sep-2025
3
Backpropagation algorithm and test the same using appropriate data
sets.
Design and implement an Image classification model to classify a 17-Sep-2025
4 dataset of images using Deep Feed Forward NN Use the MNIST,
CIFAR-10 datasets.
Design and implement a CNN model (with 2 layers of convolutions) 24-Sep-2025
5 to classify multi category image datasets.
Design and implement a CNN model (with 4+ layers of 01-Oct-2025
convolutions) to classify multi category image datasets. Use the
6 MNIST, Fashion MNIST, CIFAR-10 datasets. Set the No. of Epoch as
5, 10 and 20. Make the necessary changes whenever required.
Design and implement a CNN model (with 2+ layers of 15-Oct-2025
convolutions) to classify multi category image datasets. Use the
7 concept of padding and Batch Normalization while designing
the CNN model.
Use the concept of Data Augmentation to increase the data size from 29-Oct-2025
8 a singleimage.
Implement the standard VGG 16 CNN architecture model to classify 12-Nov-2025
9 cat and dog image dataset .
Implement RNN for sentiment analysis on movie reviews 19-Nov-2025
10
1. Design a single unit perceptron for classification of a linearly
separable binary dataset without using pre-defined models. Use the
Perceptron() fromsklearn.
import numpy as np
import pandas as pd
import seaborn as sns
import [Link] as plt
from sklearn.linear_model import Perceptron
df=pd.read_csv('/content/gdrive/My Drive/ML_lab/[Link]') X =
[Link][:,0:2] y = [Link][:,-1] p = Perceptron() [Link](X,y)
print(p.coef_) print(p.intercept_) z=[Link](X,y)
print("accuracy score is",z)
from [Link] import plot_decision_regions
plot_decision_regions([Link], [Link], clf=p, legend=2)
2. Build an Artificial Neural Network by implementing the
Backpropagation algorithm and test the same using appropriate data
sets. Vary the activation functions used and compare the results.
Program:
from [Link] import Sequential
from [Link] import Dense, Activation import
numpy as np import pandas as pd
from sklearn import datasets iris =
datasets.load_iris() X, y = datasets.load_iris(
return_X_y = True)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40) #
Define the network model and its arguments.
# Set the number of neurons/nodes for each layer:
model = Sequential() [Link](Dense(2,
input_shape=(4,))) [Link](Activation('sigmoid'))
[Link](Dense(1)) [Link](Activation('sigmoid'))
#sgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)
#[Link](loss='categorical_crossentropy', optimizer=sgd,
metrics=['accuracy']) # Compile the model and calculate its accuracy:
[Link](loss='mean_squared_error', optimizer='sgd',
metrics=['accuracy']) #[Link](X_train, y_train, batch_size=32,
epochs=3)
# Print a summary of the Keras model:
[Link]() #[Link](X_train, y_train)
#[Link](X_train, y_train, batch_size=32, epochs=300)
[Link](X_train, y_train, epochs=5)
score = [Link](X_test, y_test) print(score)
3. Design and implement an Image classification model to classify a
dataset of images using Deep Feed ForwardNN. Record the accuracy
corresponding to the number of epochs. Use the MNIST datasets
#load required packages import
tensorflow as tf from tensorflow import
keras
from [Link] import Sequential from keras import
Input from [Link] import Dense import pandas as
pd
import numpy as np import sklearn
from [Link] import classification_report import
matplotlib import [Link] as plt
# Load digits data
(X_train, y_train), (X_test, y_test) = [Link].load_data()
# Print shapes
print("Shape of X_train: ", X_train.shape) print("Shape of y_train: ",
y_train.shape) print("Shape of X_test: ", X_test.shape) print("Shape of
y_test: ", y_test.shape)
# Display images of the first 10 digits in the training set and their true
lables fig, axs = [Link](2, 5, sharey=False, tight_layout=True,
figsize=(12,6), facecolor='white') n=0
for i in range(0,2):
for j in range(0,5): axs[i,j].matshow(X_train[n])
axs[i,j].set(title=y_train[n]) n=n+1 [Link]()
# Reshape and normalize (divide by 255) input data
X_train = X_train.reshape(60000,
784).astype("float32") / 255 X_test =
X_test.reshape(10000, 784).astype("float32") / 255
# Print shapes
print("New shape of X_train: ", X_train.shape) print("New shape of
X_test: ", X_test.shape)
#Design the Deep FF Neural Network architecture model =
Sequential(name="DFF-
Model") # Model
[Link](Input(shape=(784,), name='Input-Layer')) # Input Layer -
need to specify the shape of inputs
[Link](Dense(128, activation='relu', name='Hidden-
Layer-1', kernel_initializer='HeNormal'))
[Link](Dense(64, activation='relu', name='Hidden-
Layer-2', kernel_initializer='HeNormal'))
[Link](Dense(32, activation='relu', name='Hidden-
Layer-3', kernel_initializer='HeNormal'))
[Link](Dense(10, activation='softmax', name='Output-Layer'))
#Compile keras model
[Link](optimizer='adam',
loss='SparseCategoricalCrossentropy
',
metrics=['Accuracy'], loss_weights=None,
weighted_metrics=None, run_eagerly=None,
steps_per_execution=None)
#Fit keras model on the dataset
[Link](X_train, y_train, batch_size=10, epochs=5, verbose='auto',
callbacks=None, validation_split=0.2, shuffle=True, class_weight=None,
sample_weight=None, initial_epoch=0, # Integer, default=0, Epoch at
which to start training (useful for resuming a previous training run).
steps_per_epoch=None, validation_steps=None,
validation_batch_size=None, validation_freq=5, max_queue_size=10,
workers=1, use_multiprocessing=False,)
# apply the trained model to make predictions # Predict class labels on
training data pred_labels_tr =
[Link]([Link]([Link](X_train),axis=1)) # Predict class
labels on a test data
pred_labels_te = [Link]([Link]([Link](X_test),axis=1))
#Model Performance Summary
print("") print(' Model Summary
[Link]() print("")
')
# Printing the parameters:Deep Feed Forward Neural Network
contains more than 100K
#print(' Weights and Biases #for layer in
model_d1.layers: ')
#print("Layer: ", [Link]) # print layer name
#print(" --Kernels (Weights): ", layer.get_weights()[0]) # kernels (weights)
#print(" --
Biases: ", layer.get_weights()[1]) # biases
print("")
print('---------- Evaluation on Training Data ')
print(classification_report(y_train, pred_labels_tr))
print("")
print('---------- Evaluation on Test Data ')
print(classification_report(y_test,
pred_labels_te)) print("")
4. Design and implement a CNN model (with 2 layers of convolutions)
to classify multi category image datasets. Use the MNIST, CIFAR-10
datasets.
import tensorflow as tf
from [Link] import layers, models,
datasets import [Link] as plt
# Load the dataset (Change between MNIST and CIFAR-10 as needed)
dataset_name = "MNIST" # Change to "CIFAR-10" for CIFAR dataset
if dataset_name == "MNIST":
(X_train, y_train), (X_test, y_test) =
[Link].load_data() X_train =
X_train.reshape(-1, 28, 28, 1) / 255.0
X_test = X_test.reshape(-1, 28, 28, 1) / 255.0
num_classes = 10
input_shape = (28, 28, 1)
elif dataset_name == "CIFAR-10":
(X_train, y_train), (X_test, y_test) =
datasets.cifar10.load_data() X_train = X_train / 255.0
X_test = X_test /
255.0 num_classes
= 10
input_shape = (32, 32, 3)
# One-hot encode labels
y_train = [Link].to_categorical(y_train,
num_classes) y_test =
[Link].to_categorical(y_test, num_classes)
# Define the CNN model
def create_cnn_model(input_shape,
num_classes): model = [Link]([
# 1st Convolutional Layer
layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
layers.MaxPooling2D((2, 2)),
# 2nd Convolutional Layer
layers.Conv2D(64, (3, 3),
activation='relu'),
layers.MaxPooling2D((2, 2)),
# Flatten and Dense layers
[Link](),
[Link](128, activation='relu'),
[Link](num_classes,
activation='softmax')
])
[Link](optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
return model
# Create the CNN model
model = create_cnn_model(input_shape, num_classes)
# Train the model and record accuracy for
different epochs epochs = 10 # Number of
epochs
history = [Link](X_train, y_train, validation_data=(X_test, y_test),
epochs=epochs, batch_size=32)
# Plot training and validation accuracy over epochs
[Link]([Link]['accuracy'], label='Training Accuracy')
[Link]([Link]['val_accuracy'], label='Validation Accuracy')
[Link]('Model Accuracy')
[Link]('Epochs'
)
[Link]('Accurac
y') [Link]()
[Link]()
# Evaluate the model
test_loss, test_accuracy = [Link](X_test,
y_test) print(f"Test Accuracy: {test_accuracy:.2f}")
5. Design and implement a CNN model (with 4+ layers of convolutions)
to classify multi category image datasets. Record the accuracy
corresponding to the number of epochs. Use the Fashion MNIST
datasets
import keras
from [Link] import fashion_mnist
from [Link] import Dense, Activation, Flatten, Conv2D,
MaxPooling2D from [Link] import Sequential
from [Link] import to_categorical import
numpy as np import [Link] as plt
(train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data()
train_X = train_X.reshape(-1, 28,28, 1)
test_X = test_X.reshape(-1, 28,28, 1)
train_X = train_X.astype('float32') test_X = test_X.astype('float32') train_X =
train_X
/ 255
test_X = test_X / 255
train_Y_one_hot = to_categorical(train_Y) test_Y_one_hot =
to_categorical(test_Y) model = Sequential()
[Link](Conv2D(256, (3,3), input_shape=(28, 28, 1)))
[Link](Activation('relu')) [Link](MaxPooling2D(pool_size=(2,2)))
[Link](Conv2D(128, (3,3)))
[Link](Activation('relu'))
[Link](MaxPooling2D(pool_size=(2,2)))
[Link](Conv2D(64, (3,3), input_shape=(28, 28, 1)))
[Link](Activation('relu'))
#[Link](MaxPooling2D(pool_size=(2,2)))
[Link](Conv2D(28, (3,3)))
[Link](Activation('relu'))
#[Link](MaxPooling2D(pool_size=(2,2)))
[Link](Flatten()) [Link](Dense(64))
[Link](Dense(10))
[Link](Activation('softmax'))
6. Design and implement a CNN model (with 2+ layers of convolutions)
to classify multi category image datasets. Use the concept of padding
and Batch Normalization while designing the CNN model.
# Batch-Normalization and padding
import keras
from [Link] import fashion_mnist
from [Link] import Dense, Activation, Flatten, Conv2D, MaxPooling2D,
BatchNormalization
from [Link] import Sequential from [Link] import
to_categorical import numpy as np
import [Link] as plt
(train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data()
train_X = train_X.reshape(-1, 28,28, 1)
test_X = test_X.reshape(-1, 28,28, 1)
train_X = train_X.astype('float32') test_X = test_X.astype('float32') train_X =
train_X
/ 255
test_X = test_X / 255
train_Y_one_hot = to_categorical(train_Y) test_Y_one_hot =
to_categorical(test_Y) model = Sequential()
[Link](Conv2D(256, (3,3), input_shape=(28, 28, 1),padding='same'))
[Link](Activation('relu'))
BatchNormalization() [Link](MaxPooling2D(pool_size=(2,2)
,padding='same'))
[Link](Conv2D(128, (3,3),padding='same'))
[Link](Activation('relu')) #BatchNormalization()
[Link](MaxPooling2D(pool_size=(2,2) ,padding='same'))
[Link](Conv2D(64, (3,3), input_shape=(28, 28, 1,padding='same'))
[Link](Activation('relu'))
#BatchNormalization()
[Link](MaxPooling2D(pool_size=(2,2),padding='same'))
[Link](Conv2D(28, (3,3))) [Link](Activation('relu'))
7. Use the concept of Data Augmentation to increase the data size
from a single image.
#data augmentation on a single image
from numpy import expand_dims
from [Link] import image #from
[Link] import img_to_array
from [Link] import ImageDataGenerator from
matplotlib import pyplot
# load the image
img = image.load_img('/content/gdrive/My Drive/data/train/[Link]') #
convert to numpy array
data = image.img_to_array(img) # expand dimension to one sample
samples = expand_dims(data, 0)
# create image data augmentation generator
datagen = ImageDataGenerator(width_shift_range=[-100,100]) #
prepare iterator it = [Link](samples, batch_size=1) #
generate samples and plot
for i in range(9):
# define subplot [Link](330 + 1 + i) # generate batch of images
batch = [Link]()
# convert to unsigned integers for viewing image =
batch[0].astype('uint8') # plot raw pixel data
[Link](image)
# show the figure
[Link]()
8. Design and implement a CNN model to classify CIFAR10 image dataset.
Use the concept of Data Augmentationwhile designing the CNN
model.
# data augmentation with flow function from future import
print_function import tensorflow as tf
from tensorflow import keras
from [Link] import cifar10
from [Link] import ImageDataGenerator
from [Link] import Sequential
from [Link] import Dense, Dropout, Activation, Flatten
from [Link] import Conv2D, MaxPooling2D
import [Link] as plt
%matplotlib inline
# The data, shuffled and split between train and test sets: (x_train,
y_train), (x_test, y_test) = cifar10.load_data() print('x_train shape:',
x_train.shape) print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
num_classes = 10
y_train = [Link].to_categorical(y_train, num_classes) y_test =
[Link].to_categorical(y_test, num_classes)
x_train = x_train.astype('float32') x_test = x_test.astype('float32')
x_train /= 255 x_test /= 255
# Let's build a CNN using Keras' Sequential capabilities model_1 =
Sequential()
## 5x5 convolution with 2x2 stride and 32 filters
model_1.add(Conv2D(32, (5, 5), strides = (2,2), padding='same',
input_shape=x_train.shape[1:])) model_1.add(Activation('relu'))
## Another 5x5 convolution with 2x2 stride and 32 filters
model_1.add(Conv2D(32, (5, 5), strides = (2,2)))
model_1.add(Activation('relu'))
## 2x2 max pooling reduces to 3 x 3 x 32
model_1.add(MaxPooling2D(pool_size=(2, 2)))
model_1.add(Dropout(0.25))
## Flatten turns 3x3x32 into 288x1 model_1.add(Flatten())
model_1.add(Dense(512)) model_1.add(Activation('relu'))
model_1.add(Dropout(0.5)) model_1.add(Dense(num_classes))
model_1.add(Activation('softmax'))
model_1.summary() batch_size
= 32 # initiate RMSprop
optimizer
opt = [Link](lr=0.0005, decay=1e-6)
# Let's train the model using RMSprop
model_1.compile(loss='categorical_crossentrop
y', optimizer=opt, metrics=['accuracy'])
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the
dataset samplewise_std_normalization=False, # divide each input by its
std zca_whitening=False, # apply ZCA whitening
rotation_range=0, # randomly rotate images in the range (degrees, 0
to 180) width_shift_range=0.1, # randomly shift images horizontally
(fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of
total height) horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
[Link](x_train) # This computes any statistics that may be
needed (e.g. for centering) from the training set.
# Fit the model on the batches generated by
[Link](). model_1.fit([Link](x_train,
y_train,
batch_size=batch_size), steps_per_epoch=x_train.shape[0] //
batch_size, epochs=5, validation_data=(x_test, y_test)) test_loss,
test_acc = model_1.evaluate(x_test, y_test)
9. Implement the standard VGG 16 CNN architecture model to classify cat
and dog image dataset .
import keras,os
from [Link] import Sequential
from [Link] import Dense, Conv2D, MaxPool2D, Flatten from
[Link] import ImageDataGenerator import
numpy as np trdata = ImageDataGenerator()
traindata = trdata.flow_from_directory(directory="/content/gdrive/My
Drive/training_set",target_size=(224,224))
tsdata = ImageDataGenerator()
testdata = tsdata.flow_from_directory(directory="/content/gdrive/My
Drive/test_set", target_size=(224,224))
model = Sequential()
[Link](Conv2D(input_shape=(224,224,3),filters=64,kernel_size=(3,3),
padding="s ame"
,activation="relu"))
[Link](Conv2D(filters=64,kernel_size=(3,3),padding="same",
activation="relu")) [Link](MaxPool2D(pool_size=(2,2),strides=(2,2)))
[Link](Conv2D(filters=128, kernel_size=(3,3), padding="same",
activation="relu")) [Link](Conv2D(filters=128, kernel_size=(3,3),
padding="same", activation="relu"))
[Link](MaxPool2D(pool_size=(2,2),strides=(2,2)))
[Link](Conv2D(filters=256, kernel_size=(3,3), padding="same",
activation="relu")) [Link](Conv2D(filters=256, kernel_size=(3,3),
padding="same", activation="relu")) [Link](Conv2D(filters=256,
kernel_size=(3,3), padding="same", activation="relu"))
[Link](MaxPool2D(pool_size=(2,2),strides=(2,2)))
[Link](Conv2D(filters=512, kernel_size=(3,3), padding="same",
activation="relu")) [Link](Conv2D(filters=512, kernel_size=(3,3),
padding="same", activation="relu")) [Link](Conv2D(filters=512,
kernel_size=(3,3), padding="same", activation="relu"))
[Link](MaxPool2D(pool_size=(2,2),strides=(2,2)))
[Link](Conv2D(filters=512, kernel_size=(3,3), padding="same",
activation="relu")) [Link](Conv2D(filters=512, kernel_size=(3,3),
padding="same", activation="relu")) [Link](Conv2D(filters=512,
kernel_size=(3,3), padding="same", activation="relu"))
[Link](MaxPool2D(pool_size=(2,2),strides=(2,2)))
[Link](Flatten())
[Link](Dense(units=4096,activation="relu"))
[Link](Dense(units=4096,activation="relu"))
[Link](Dense(units=2, activation="softmax"))
from [Link] import Adam opt = Adam(lr=0.001)
[Link](optimizer=opt,
loss=[Link].categorical_crossentropy,
metrics=['accuracy'])
[Link]()
from [Link] import ModelCheckpoint, EarlyStopping checkpoint =
ModelCheckpoint("vgg16_1.h5", monitor='val_acc',
verbose=1,save_best_only=True, save_weights_only=False, mode='auto',
period=1)
early = EarlyStopping(monitor='val_acc', min_delta=0, patience=20,
verbose=1, mode='auto')
hist = model.fit_generator(steps_per_epoch=100,generator=traindata,
validation_data= testdata,
validation_steps=10,epochs=5,callbacks=[checkpoint,early])
import [Link] as plt [Link]([Link]["accuracy"])
[Link]([Link]['val_accuracy']) [Link]([Link]['loss'])
[Link]([Link]['val_loss']) [Link]("model accuracy")
[Link]("Accuracy") [Link]("Epoch")
[Link](["Accuracy","Validation Accuracy","loss","Validation
Loss"]) [Link]()
[Link] RNN for sentiment analysis on movie reviews.
RNN sentiment analysis on movie reviews
from [Link] import imdb
from [Link] import Tokenizer from [Link]
import pad_sequences
from keras import Sequential from [Link] import
Dense,SimpleRNN,Embedding,Flatten(X_train,y_train),(
X_test
,y_test) = imdb.load_data() X_train =
pad_sequences(X_train,padding='post',maxlen=50)
X_test =
pad_sequences(X_test,padding='post',maxlen=50)
X_train.shape
model = Sequential() #[Link](Embedding(10000, 2))
[Link](SimpleRNN(32,input_shape=(50,1),
return_sequences=False)) [Link](Dense(1, activation='sigmoid'))
[Link]()
[Link](optimizer='adam', loss='binary_crossentropy',
metrics=['acc']) [Link](X_train,
y_train,epochs=5,validation_data=(X_test,y_test)) test_loss, test_acc =
[Link](X_test, y_test)
print('Test loss', test_loss) print('Test accuracy', test_acc)