Deep Learning-Lab Manual
Deep Learning-Lab Manual
Deep Learning-Lab Manual
LAB MANUAL
PREPARED BY….
LAB PRACTICE-IV
CLASS: BE AI&ML
SEMESTER - VII
LAB MANUAL
PREPARED BY…..
M2: To Explore IT Innovations through Collaborative learning and Partnerships with Institutions and
Industries.
M5: To augment IT skills through continue education program for lifelong learning.
1) To strive hard for high academic excellence through continual efforts for enhancement in
teaching-learning process.
2) To enhance placements by strong interactions with reputed industries.
3) To inculcate recent trends in I.T. field through interactions with experts of IITs and foreign
universities.
4) To strive hard to enhance team building and communication skills of students through
curricular, co-curricular and extracurricular activities.
5) To groom students with awareness of social, ethical, moral values along with legal, health,
safety through social as well as techno-social activities.
1. Ability to apply decision-making skills through the use of appropriate technology with ability of lifelong
learning in industry culture.
2. Ability to apply Problem solving skills on open source platform with open source software’s and tools for
designing and developing I.T. solution to real world problems.
3. Ability to apply professional skills of fundamentals of mathematics, applied algorithms, Software
Engineering, System programming, web designing, Networking, Cloud computing, Big Data Analytics,
theory of computations, Cyber security in I.T. based systems.
4. An ability to understand professional, social, ethical and moral responsibilities along with health, safety,
legal and cultural issues for betterment of mankind.
Environment An ability to analyze and provide solution for the local and global impactof
PO7 and information technology on individuals, organizations and society.
Sustainability
Ethics An ability to understand professional, ethical, legal, security and
PO8 social issues and responsibilities.
Individual and An ability to function effectively as an individual or as a team memberto
PO9 Team Work accomplish a desired goal(s).
Communication An ability to engage in life-long learning and continuing professional
Skills development to cope up with fast changes in the technologies /tools with
PO10 the help of electives, profession along animations and extra- curricular
activities.
Project An ability to communicate effectively in engineering community at large
Management by means of effective presentations, report writing, paper publications,
PO11 and demonstrations.
Finance
Life-long An ability to understand engineering, management, financial aspects,
PO12 Learning performance, optimizations and time complexity necessaryfor
professional practice.
COURSE OBJECTIVE
To apply the algorithms to a real-world problem, optimize the models learned and report on
CO3
the expected accuracy that can be achieved by applying the models.
COURSE OUTCOMES
CO2 Build and train a deep Neural Network models for use in various applications.
Apply Deep Learning techniques like CNN, RNN Auto encoders to solve real word Problems.
CO3
CO4 Evaluate the performance of the model build using Deep Learning.
Sr. Page
List of Assignments
No No
1 Study of Deep learning Packages: Tensorflow, Keras, Theano and PyTorch.
Document the distinct features and functionality of the packages.
Note: Use a suitable dataset for the implementation of following assignments.
Build the Image classification model by dividing the model into following 4
stages:
3 a. Loading and preprocessing the image data
b. Defining the model’s architecture
c. Training the model
d. Estimating the model’s performance
Implement the Continuous Bag of Words (CBOW) Model. Stages can be:
a. Data preparation
b. Generate training data
5 c. Train model
d. Output
Object detection using Transfer Learning of CNN architectures
6 a. Load in a pre-trained CNN model trained on a large dataset
b. Freeze parameters (weights) in model’s lower convolutional layers
c. Add custom classifier with several layers of trainable parameters to model
d. Train classifier layers on training data available for task
e. Fine-tune hyper parameters and unfreeze more layers as needed
8
Sr. CO’S BT
List of Assignments Reali Level
No
zed
1 Study and use of Deep learning Packages: Tensorflow, Keras, Theano and CO1, 3
PyTorch. Document the distinct features and functionality of the packages. CO2,
Note: Use a suitable dataset for the implementation of following CO3,
assignments. CO4
CO1, 6
Build the Image classification model by dividing the model into following
CO2,
4 stages:
3 CO3,
e. Loading and preprocessing the image data
CO4
f. Defining the model’s architecture
g. Training the model
h. Estimating the model’s performance
Implement the Continuous Bag of Words (CBOW) Model. Stages can be: CO1, 5
a. Data preparation CO2
b. Generate training data CO3,
5 c. Train model CO4
d. Output
Object detection using Transfer Learning of CNN architectures CO1, 5
6 f. Load in a pre-trained CNN model trained on a large dataset CO2
g. Freeze parameters (weights) in model’s lower convolutional layers CO3,
h. Add custom classifier with several layers of trainable parameters to CO4
model
i. Train classifier layers on training data available for task
j. Fine-tune hyper parameters and unfreeze more layers as needed
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 2 2 - - 3 - - - - - 1 1
CO2 3 3 3 2 3 - - - 1 1 1 2
CO3 3 3 3 2 3 1 - - 1 1 1 2
CO4 3 3 3 2 3 - - - 1 1 1 2
CO-PSO MAPPING
CO1 2 2 2 1
CO2 3 2 3 1
CO3 3 2 3 2
CO4 3 2 3 2
10
11
Title: Study of Deep learning Packages: Tensorflow, Keras, Theano and PyTorch.
Document the distinct features and functionality of the packages.
Theory:
12
4. Update PIP:
pip install --upgrade pip
5. Install TensorFlow:
The virtual environment is activated, and it’ s up and running. Now, it’ s time to install the TensorFlow
package.
pip install -- upgrade TensorFlow
Installation of Keras on Ubntu :
Prerequisite : Python version 3.5 or above.
Step 1: Install and Update Python3 and Pip
Skip this step if you already have Python3 and Pip on your machine.
sudo apt install python3 python3.pip
sudo pip3 install – – upgrade pip
Step 2: Upgrade Setuptools
pip3 install – – upgrade setuptools
Step 3: Install TensorFlow
pip3 install tensorflow
Verify the installation was successful by checking the software package information:
pip3 show tensorflow
Step 4: Install Keras
pip3 install keras
Verify the installation by displaying the package information:
pip3 show keras
[https://phoenixnap.com/kb/how-to-install-keras-on-linux]
13
14
Conclusion:
Tensorflow, PyTorch, Keras and Theano all these packages are installed and ready for Deep learning
applications . As per application domain and dataset we can choose the appropriate package and build
required type of Neural Network.
Output of Code:
Note: Run the code and attach your output of the code here.
Questions:
1) What is Deep learning ?
2) What are various packages in python for supporting Machine Learning libraries and which are mainly
used for Deep Learning ?
3) Compare Tensorflow / Keras/Theno and PyTorch on following points(make a table) :
i. Available Functionality
ii. GUI status
iii. Versions.
iv. Features
16
17
Problem Statement:
Objectives:
1. Understand how to use Tensorflow Eager and Keras Layers to build a neural network architecture.
2. Understand how a model is trained and evaluated.
3. Identify digits from images.
4. Our main goal is to train a neural network (using Keras) to obtain > 90% accuracy on MNIST
dataset.
5. Research at least 1 technique that can be used to improve model generalization.
Solution Expected:
Implement and train a feed-forward neural network (also known as an "MLP" for "multi-layer
perceptron") on a dataset called MNIST and improve model generalization by achieving increased
accuracy and decrease loss where model gains good confidence with the prediction.
Methodology to be used
⮚ Deep Learning
⮚ Feed Forward Neural Network
Theory:
Deep learning has revolutionized the world of machine learning as more and more ML practitioners have
18
Figure 1: Conceptual diagram of the neural network. Each output unit corresponds to a digit and has its
confidence value. The final classification is the digit with the maximum confidence value.
TensorFlow and Keras Libraries:
If Keras and TensorFlow are not installed on your system, you can easily do so using pip or conda
depending upon your Python environment.
pip install tensorflow
19
20
model.compile(optimizer='sgd',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
Train the Neural Network:
Now that the model is ready, it’s time to train it. We’ll load the dataset, train the model, and view the
training process. Note that the outputs shown here will vary with every run of the program because of the
21
22
Confusion Matrix
26
With above code we can see that, throughout the epochs, our model accuracy increases and loss decreases
that is good since our model gains confidence with our prediction
1. The two loss(loss and val_loss) are decreasing and the accuracy (accuracy and val_accuracy) increasing.
2. The val_accuracy is the measure of how good the model is predicting so, it is observed that the model is
well trained after 10 epochs
References
1. S. Arora and M. P. S. Bhatia, "Handwriting recognition using Deep Learning in Keras," 2018
International Conference on Advances in Computing, Communication Control and Networking
(ICACCCN), 2018, pp. 142-145, doi: 10.1109/ICACCCN.2018.8748540.
2. https://towardsdatascience.com/feed-forward-neural-networks-how-to-successfully-build-them-in-
python-74503409d99a
3. https://pyimagesearch.com/2021/05/06/implementing-feedforward-neural-networks-with-keras-and-
tensorflow/
4. https://exchange.scale.com/public/blogs/how-to-build-a-fully-connected-feedforward-neural-network-
using-keras-and-tensorflow
5. https://www.kaggle.com/code/prashant111/mnist-deep-neural-network-with-keras/notebook
6. https://sanjayasubedi.com.np/deeplearning/tensorflow-2-first-neural-network-for-fashion-mnist/
27
Problem Statement:
Build the Image classification model by dividing the model into following 4 stages:
Objective:
1. To be able to apply deep learning algorithms to solve problems of moderate complexity
2. Understand how a model is trained and evaluated.
3. Classifying images from the image dataset.
4. Our main goal is to train a neural network (using Keras) to obtain > 90% accuracy on image
dataset..
5. To apply the algorithms to a real-world problem, optimize the models learned and report on
the expected accuracy that can be achieved by applying the models
2. Build and train a deep Neural Network models for use in various applications.
3. Apply Deep Learning techniques like CNN, RNN Auto encoders to solve real word
Problems.
Solution Expected:
Implement and train a Convulutional neural network (CNN) on an hand-written digits image
dataset called MNIST and improve model generalisation by achieving increased accuracy and
decreased loss where model gains good confidence with the prediction.
Methodology to be used:
⮚ Deep Learning
28
29
The input layer accepts three-dimensional input generally in the form spatially of the size (width × height)
of the image and has a depth representing the color channels (generally three for RGB color channels) as
shown in fig 2 above.
The feature-extraction layers have a general repeating pattern of the sequence as shown in figure 1:
Convolution layer
We express the Rectified Linear Unit (ReLU) activation function as a layer in the diagram in figure 1.
Convolutional layers transform the input data by using a patch of locally connecting neurons from the
previous layer.
30
3. Classification layers
Finally we have the classification layers in which we have one or more fully connected layers to take the
higher-order features and produce class probabilities or scores. These layers are fully connected to all of the
neurons in the previous layer, as their name implies. The output of these layers produces typically a two
dimensional output of the dimensions [b × N], where b is the number of examples in the mini-batch and N is
the number of classes we’re interested in scoring.
31
32
33
Thus, we have seen steps that are important for building CNN model.
Code Snippets:
#Importing Libraries
import numpy as np
import pandas as pd
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Conv2D, Dense, MaxPooling2D
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.datasets import mnist
35
model = Sequential([
Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 1)),
MaxPooling2D((2, 2)),
Flatten(),
Dense(100, activation="relu"),
Dense(10, activation="softmax")
])
We now have our model. The next step is to define how we want to train it:
Let's use an SGD optimizer (Stochastic Gradient Descent) with 0.01 as the learning rate.
As we discussed before, we need to use the sparse_categorical_crossentropy loss because our target values
are represented as integers.
37
Model: "sequential_1"
38
plt.figure(figsize=(16, 10))
for i in range(20):
image = random.choice(X_test).squeeze()
digit = np.argmax(model.predict(image.reshape((1, 28, 28, 1)))[0], axis=-1)
plot_digit(image, digit, plt, i)
plt.show()
39
Test accuracy 99%+ implies the model is trained well for prediction. If we visualize the whole training log,
then with more number of epochs the loss and accuracy of the model on training and testing data converged
thus making the model a stable one.
40
41
Conclusion:
Thus, we have implemented the Image classification model using CNN. With above code we can see that
sufficient accuracy has been met. Throughout the epochs, our model accuracy increases and loss decreases
that is good since our model gains confidence with our prediction
This indicates the model is trained in a good way
1. The loss is decreasing and the accuracy is increasing with every epoch.
2. The test accuracy is the measure of how good the model is predicting so, it is observed that the model
is well trained after 10 epochs
References:
1. https://www.analyticsvidhya.com/blog/2021/06/image-classification-using-convolutional-neural-
network-with-python/
2. Josh Patterson, Adam Gibson "Deep Learning: A Practitioner's Approach", O’ReiIIy Media, 2017
3. https://deepnote.com/@svpino/MNIST-with-Convolutional-Neural-Networks-a4b3c412-b802-4185-
9806-02640fbba02e
4. https://towardsdatascience.com/a-simple-2d-cnn-for-mnist-digit-recognition-a998dbc1e79a
42
Problem Statement:
Use Autoencoder to implement anomaly detection.
Build the model by using
Solution Expected:
AutoEncoders are widely used in anomaly detection. The reconstruction errors are used as the
anomaly scores. Let us look at how we can use AutoEncoder for anomaly detection using
TensorFlow.
Import the required libraries and load the data. Here we are using the ECG data which consists of
labels 0 and 1. Label 0 denotes the observation as an anomaly and label 1 denotes the observation
as normal.
Objectives to be achieved:
1)Use Autoencoder to implement anomaly detection.
Methodology to be used:
AutoEncoder is a generative unsupervised deep learning algorithm used for reconstructing high-
dimensional input data using a neural network with a narrow bottleneck layer in the middle which
contains the latent representation of the input data.
43
48
49
Normal data has a value of 0 in the target variable. Using the target variable to create a normal
and fraud dataset.
50
51
53
To calculate the reconstruction loss on test data, predict the test data and calculate the mean
square error between the test data and the reconstructed test data.
54
55
56
Conclusion:
Autoencoders can be used as an anomaly detection algorithm when we have an unbalanced dataset
where we have a lot of good examples and only a few anomalies. Autoencoders are trained to
minimize reconstruction error. When we train the autoencoders on normal data or good data, we can
hypothesize that the anomalies will have higher reconstruction errors than the goodor normal data.
58
Aim: Implement the Continuous Bag of Words (CBOW) Model. Stages can be:
a. Data preparation
b. Generate training data
c. Train model
d. Output
Theory :
1) What is NLP ?
2) What is Word embedding related to NLP ?
3) Explain Word2Vec techniques.
4) Enlist applications of Word embedding in NLP.
5) Explain CBOW architecture.
6) What will be input to CBOW model and Output to CBW model.
7) What is Tokenizer .
8) Explain window size parameter in detail for CBOW model.
9) Explain Embedding and Lmbda layer from keras
10) What is yield()
Steps/ Algorithm
1. Dataset link and libraries :
Create any English 5 to 10 sententece paragraph
as inputImport following data from keras :
keras.models import Sequential
keras.layers import Dense, Embedding, Lambda
keras.utils import np_utils
keras.preprocessing import sequence
keras.preprocessing.text import Tokenizer
59
Ref: https://analyticsindiamag.com/the-continuous-bag-of-words-cbow-model-in-nlp-
hands-on-implementation-with-codes/
a) Import following libraries gemsim and numpy set i.e. text file created . It
should bepreprocessed.
b) Tokenize the every word from the paragraph . You can call in built tokenizer
present inGensim
c) Fit the data to tokenizer
d) Find total no of words and total no of sentences.
e) Generate the pairs of Context words and target words :
e.g. cbow_model(data, window_size,
total_vocab):total_length =
window_size*2
for text in data:
text_len =
len(text)
for idx, word in
enumerate(text):
context_word = []
target = []
begin = idx -
window_size end = idx +
window_size + 1
context_word.append([text[i] for i in range(begin, end) if 0 <= i < text_len and i
!= idx])
target.append(word)
contextual = sequence.pad_sequences(context_word, total_length=total_length)
final_target = np_utils.to_categorical(target, total_vocab)
60
Conclusion: In this experiment, we saw what a CBOW model is and how it works. We also
implemented the model on a custom dataset and got good output. We learnt what word embeddings
are and how CBOW is useful. These can be used for text recognition, speech to text conversion etc.
61
Theory:
1) What is Transfer learning ?
2) What are pretrained Neural Network models ?
3) Explain Pytorch library in short.
4) What are advantages of Transfer learning.
5) What are applications of Transfer learning.
6) Explain Caltech 101 images dataset.
7) Explain Imagenet dataset .
8) List down basic steps for transfer learning.
9) What is Data augmentation?
10) How and why Data augmentation is done related to transfer learning?
11) Why preprocessing is needed on inputdata in Transfer learning.
12) What is PyTorch Transforms module.Explain following commands w.r.t it :
Compose([RandomResizedCrop(size=256, scale=(0.8, 1.0)),RandomRotation(degrees=15),
ColorJitter(),
RandomHorizontalFlip(),
CenterCrop(size=224), # Image net standards
.ToTensor(),
Normalize
13) Explain the Validation Transforms steps with Pytorch Transforms.
14) Explain VGG-16 model from Pytorch
62
.
.
/test
/class1
/class2
.
Libraries required :
PyTorch
torchvision import transforms
torchvision import datasets
torch.utils.data import
DataLoadertorchvision
import models torch.nn as nn
torch import optim
Ref: https://towardsdatascience.com/transfer-learning-with-convolutional-neural-networks-in-
pytorch-dd09190245ce
63
bias=True)(4): ReLU(inplace)
65
(6) : Sequential(
bias=True)(4): LogSoftmax()
)
)
8) Initialize the loss and
optimizercriteration =
nn.NLLLoss()
optimizer = optim.Adam(model.parameters())
9) Train the model using
Pytorch for epoch in
range(n_epochs): for data,
targets in trainloader:
# Generate
predictionsout =
model(data)
# Calculate loss
loss = criterion(out,
targets)#
Backpropagation
loss.backward()
# Update model
parameters
optimizer.step()
10) Perform Early stopping
11) Draw performance curve
66
Conclusion: In this experiment, we were able to see the basics of using PyTorch as well as the concept
of transfer learning, an effective method for object recognition. Instead of training a model from
scratch, we can use existing architectures that have been trained on a large dataset and then tunethem
for our task. This reduces the time to train and often results in better overall performance. The
outcome of this experiment is knowledge of transfer learning and PyTorch that we can build on to
build more complex applications.
https://www.google.com/url?q=https://towardsdatascience.com/transfer−learning−
with− convolutional−neural−networks−in−pytorch−dd0
image = img_to_array(image)
image = preprocess_input(image)
model = VGG16()
yhat = model.predict(image)
label = decode_predictions(yhat)
label = label[0][0]
68