CCS355 Lab Manual Overview
CCS355 Lab Manual Overview
BONAFIDE CERTIFICATE
Name : …………………………………………………………
Degree : …………………………………………………………
Branch : …………………………………………………………
Semester : …………… Year: ………… Section: ……………....
Reg. No. : …………………………………………………………
Certified that this is the bonafide record of the work done by the above student in
….......................................................................................................... Laboratory during
the academic year …………………………………
Students must be present in proper dress code and wear the ID card.
Students should enter the log-in and log-out time in the log register without fail.
Students are not allowed to download pictures, music, videos or files without the
permission of respective lab in-charge.
Students should wear their own lab coats and bring observation note books to the
laboratory classes regularly.
Record of experiments done in a particular class should be submitted in the next
lab class.
Students who do not submit the record note book in time will not be allowed to do
the next experiment and will not be given attendance for that laboratory class.
Students will not be allowed to leave the laboratory until they complete the
experiment.
Students are advised to switch-off the Monitors and CPU when they leave the lab.
Students are advised to arrange the chairs properly when they leave the lab.
College
Vision
To improve the quality of human life through multi-disciplinary programs in Engineering,
architecture and management that are internationally recognized and would facilitate research work to
incorporate social economical and environmental development.
Mission
To create a vibrant atmosphere that creates competent engineers, innovators, scientists,
entrepreneurs, academicians and thinkers of tomorrow.
To establish centers of excellence that provides sustainable solutions to industry and society.
To enhance capability through various values added programs so as to meet the
challenges of dynamically changing global needs.
Department
Vision
To cultivate creative, globally competent, employable and disciplined computing professionals
with the spirit of benchmarking educational system that promotes academic excellence, scientific
pursuits, entrepreneurship and professionalism.
Mission
To develop the creators of tomorrow’s technology to meet the social needs of our nation.
To promote and encourage the strength of research in Engineering, Science and Technology.
The Graduates inculcate soft skills such as communication, team work, leadership qualities,
PEO3 professional and ethical values and an ability to apply the acquired skills to
address the societal issues.
The Graduates will be able to work with an environment conducive for life-long learning
PEO4 needed for a successful professional career.
Program Outcomes(POs)
Design, develop, test and maintain strategies in software project development to deliver a
PSO1
quality product for business success.
Design, develop, test and maintain software in area of algorithms, system software, web
design, multimedia, big data analytics and networking for efficient design for
PSO2
computer based system.
Course Outcomes(CO’s)
C03 Develop Python programs step-wise by defining functions and calling them.
C04 Use Python lists, tuples, dictionaries for representing compound data.
Mapping
Course
Outcom PO 1 PO PO PO PO PO PO PO PO PO1 PO1
PO12 PSO1 PSO2
es 2 3 4 5 6 7 8 9 0 1
(CO’s)
C01 3 3 2 2 1 1 2 - - - - - 3 3
C02 3 3 1 - - 1 - - 1 - - - 2 2
C03 3 3 - 1 2 - 2 - 1 - - - 3 2
C04 3 3 - 1 - 1 1 - 1 - - - 2 -
C05 2 2 1 - 1 - 1 - - - - - 2 1
LAB-IN-CHARGE
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Program:
import tensorflow as tf
Output:
Result of vector addition: [5 7 9]
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above program was Successfully executed.
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Viva Questions:
1. What is TensorFlow?
2. Can you explain the difference between TensorFlow 1.x and TensorFlow 2.x?
3. What is vector addition?
4. How is vector addition performed in TensorFlow?
5. Could you walk me through the steps to implement vector addition using TensorFlow?
6. Can you write a simple code snippet in TensorFlow to add two
vectors [1, 2, 3] and [4, 5, 6]?
7. How would you execute this code snippet to get the result?
8. What is a TensorFlow session?
9. Why do we need to create a session in TensorFlow?
10. In the context of TensorFlow, what are constants and variables
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim:
The aim of this exercise is to demonstrate how to implement a simple regression
model using the Keras API, a high-level neural networks library running on top of TensorFlow.
Algorithm:
1. Generate Or Load The Dataset.
2. Define A Sequential Model.
3. Add Layers To The Model. For Regression, Typically A Single Dense Layer Is
Sufficient.
4. Compile The Model, Specifying Optimizer And Loss Function.
5. Train The Model On The Dataset Using The Fit Method.
6. Make Predictions Using The Trained Model.
7. Evaluate The Model's Performance Using Appropriate Metrics.
Program:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from [Link] import layers
predictions = [Link](X_test)
print("Predictions:")
print(predictions)
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Epoch 1/100
4/4 [==============================] - 0s 749us/step - loss: 4.5494
Epoch 2/100
4/4 [==============================] - 0s 623us/step - loss: 4.4588
...
Epoch 100/100
4/4 [==============================] - 0s 499us/step - loss: 0.0345
Predictions:
[[1.2399716]
[1.4402403]
[1.640509 ]]
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above Program was executed successfully.
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice questions:
1. Implement a binary classification model using Keras to predict whether a given email is
spam or not spam. Use the SpamAssassin Public Corpus dataset for training and testing.
2. Develop a multiclass classification model using TensorFlow to classify handwritten
digits from the MNIST dataset. Experiment with different neural network architectures
and activation functions.
3. Build a regression model using Scikit-Learn to predict house prices based on features such
as number of bedrooms, square footage, and location. Use the California housing dataset
for training and testing.
4. Fine-tune a pre-trained convolutional neural network (e.g., VGG16, ResNet) using
Keras to perform image recognition on a custom dataset of flowers or animals.
Evaluate the model's performance on a validation set.
Viva questions :
1. What is machine learning, and how does it differ from traditional programming?
2. Can you explain the three main types of machine learning: supervised learning,
unsupervised learning, and reinforcement learning?
3. What is supervised learning, and what are some common examples?
4. Describe the difference between classification and regression in supervised learning.
5. What is unsupervised learning, and what are its primary applications?
6. Explain the difference between clustering and dimensionality reduction techniques in
unsupervised learning.
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim:
The aim of this exercise is to implement a perceptron, a fundamental building block of
neural networks, in both TensorFlow and Keras environments. Through this exercise, will gain
an understanding of how to create and train a perceptron model using both of these popular deep
learning frameworks.
Algorithm:
1. Initialize Weights and Bias: Initialize weights and bias randomly or with predefined
values.
2. Define Input Data: Prepare the input data along with corresponding labels for training the
perceptron.
3. Define Placeholder (TensorFlow) or Input Shape (Keras): Depending on the framework,
define placeholders for input data (TensorFlow) or specify the input shape (Keras).
4. Define Perceptron Operation: Compute the output of the perceptron by performing the
weighted sum of inputs and adding a bias term, followed by passing the result through an
activation function (e.g., step function, sigmoid, etc.).
5. Define Loss Function: Define a suitable loss function to measure the discrepancy between
predicted and actual outputs (e.g., mean squared error, binary cross-entropy).
6. Define Optimizer: Choose an optimizer algorithm (e.g., stochastic gradient descent,
Adam) to minimize the loss and update the weights and bias accordingly.
7. Initialize Variables (TensorFlow): Initialize all variables used in the computation graph.
8. Train the Perceptron: Iterate over the training data multiple times, feeding the input data
and labels to the perceptron, and optimizing the weights and bias using the chosen
optimizer.
9. Evaluate the Perceptron (Optional): If necessary, evaluate the trained perceptron on a
separate validation or test dataset to assess its performance.
10. Make Predictions: Use the trained perceptron to make predictions on new, unseen data.
6
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Program:
Tensor Flow:
import numpy as np
import tensorflow as tf
# Define the input data
X = [Link]([[0, 0], [0, 1], [1, 0], [1, 1]])
y = [Link]([[0], [0], [0], [1]])
# Define the perceptron
class Perceptron([Link]):
def init (self):
super(Perceptron, self). init ()
self.W = [Link]([Link]([2, 1]))
self.b = [Link]([Link]([1]))
# Training loop
for epoch in range(1000):
with [Link]() as tape:
predictions = perceptron(X)
loss = loss_function(y, predictions)
gradients = [Link](loss, perceptron.trainable_variables)
optimizer.apply_gradients(zip(gradients, perceptron.trainable_variables))
Keras:
import numpy as np
import tensorflow as tf
from [Link] import Sequential
from [Link] import Dense
7
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
8
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
OUTPUT:
Predictions:
[[0.06273559]
[0.16103294]
[0.10974989]
[0.8888136 ]]
9
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The Program was executed Successfully.
10
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice Questions:
1. Implement a binary classification model using logistic regression with Scikit-Learn. Use
a dataset such as the Breast Cancer Wisconsin dataset for training and testing.
2. Develop a multiclass classification model using random forests with Scikit-Learn to
classify handwritten digits from the MNIST dataset. Experiment with different
hyperparameters such as the number of trees and maximum depth.
3. Build a regression model using gradient boosting with XGBoost or LightGBM to predict
house prices based on features such as number of bedrooms, square footage, and location.
Use the California housing dataset for training and testing.
4. Construct a CNN model using TensorFlow or Keras to perform image recognition on a
custom dataset of flowers or animals. Experiment with different architectures, activation
functions, and regularization techniques.
Viva Questions:
1. What is machine learning, and how does it differ from traditional programming?
2. Can you explain the difference between supervised, unsupervised, and
reinforcement learning?
3. What is supervised learning, and how does it work?
4. Describe the process of training a supervised learning model.
5. What is unsupervised learning, and when is it used?
6. Explain the difference between clustering and dimensionality reduction.
11
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim:
The aim of this exercise is to implement a feedforward neural network, also known as a
multilayer perceptron (MLP), in both TensorFlow and Keras environments. By completing this
exercise, participants will gain an understanding of how to build and train a basic feedforward
neural network using these popular deep learning frameworks.
Algorithm:
1. Initialize Weights and Biases: Initialize the weights and biases of each layer randomly or
using predefined values.
2. Define Input Data: Prepare the input data along with corresponding labels for training the
neural network.
3. Define Model Architecture:
a. TensorFlow:
- Define placeholders for input data.
- Define variables for weights and biases for each layer.
- Define the architecture of the neural network by specifying the number of
layers, number of neurons in each layer, and activation functions.
b. Keras:
- Initialize a sequential model.
- Add layers to the model using Dense layer specifying the number of
neurons and activation functions.
- Compile the model, specifying the optimizer, loss function, and metrics.
4. Forward Propagation:
a. TensorFlow:
- Implement forward propagation by applying the activation function to the
linear combination of inputs, weights, and biases for each layer.
b. Keras:
- Keras handles forward propagation internally during the training process.
5. Define Loss Function: Define a suitable loss function to measure the discrepancy between
predicted and actual outputs (e.g., mean squared error, categorical cross-entropy).
12
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Keras:
import numpy as np
import tensorflow as tf
from [Link] import Sequential
from [Link] import Dense
X = [Link](100, 2)
y = [Link](0, 2, (100, 1))
14
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Loss: 0.561991870880127
Accuracy: 0.7400000095367432
15
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The Program was executed Successfully.
16
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice Questions:
1. Implement a binary classification model using Support Vector Machines (SVM) with
Scikit-Learn. Use a dataset such as the Iris dataset for training and testing.
2. Apply the K-means clustering algorithm with Scikit-Learn to segment customers
based on their purchasing behavior. Use a customer segmentation dataset and
visualize the clusters.
3. Develop a CNN model using TensorFlow or Keras to classify images from the CIFAR-
10 dataset. Experiment with different CNN architectures and data augmentation
techniques.
4. Implement an RNN model using TensorFlow or Keras to generate text sequences
based on a given input. Use a text dataset such as the Shakespeare dataset for
training.
Viva Questions:
17
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Algorithm:
1. Prepare Dataset:
Load and preprocess the image dataset. This may involve resizing images to a
fixed size, normalizing pixel values, and splitting the dataset into training, validation, and test
sets.
4. Optionally apply data augmentation techniques such as random rotation, flipping, and
shifting to increase the diversity of the training data.
5. Compile Model:
18
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
6. Define the loss function, optimizer, and evaluation metrics for training the model.
7. Train Model:
8. Feed the training data to the model and train it using the fit method. Monitor the training
process using validation data.
9. Evaluate Model:
10. Evaluate the trained model on the test set to assess its performance.
11. Fine-Tuning and Hyperparameter Tuning (Optional):
12. Optionally fine-tune the model architecture and hyperparameters based on the
performance on the validation set.
13. Make Predictions:
14. Use the trained model to make predictions on new, unseen images.
Program:
import numpy as np
import tensorflow as tf
from [Link] import mnist
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten, Dense
20
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Epoch 1/5
938/938 [==============================] - 6s 6ms/step - loss: 0.1481 - accuracy:
0.9546
Epoch 2/5
938/938 [==============================] - 6s 6ms/step - loss: 0.0455 - accuracy:
0.9859
Epoch 3/5
938/938 [==============================] - 6s 6ms/step - loss: 0.0327 - accuracy:
0.9899
Epoch 4/5
938/938 [==============================] - 6s 6ms/step - loss: 0.0247 - accuracy:
0.9921
Epoch 5/5
938/938 [==============================] - 6s 6ms/step - loss: 0.0191 - accuracy:
0.9940
313/313 [==============================] - 1s 3ms/step - loss: 0.0254 - accuracy:
0.9916
Test Accuracy: 0.991599977016449
21
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above was executed successfully.
22
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practical Exercise:
Viva Questions:
1. What is a loss function, and why is it important in training a machine learning
model?
2. Explain the difference between mean squared error (MSE) and cross-entropy loss
functions.
3. What are optimization algorithms, and why are they used in machine learning?
4. Describe the gradient descent algorithm and its variants.
23
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim:
The aim of hyperparameter tuning in deep learning is to improve the performance of a
model by systematically searching for the optimal combination of hyperparameters.
Hyperparameters are settings that control the learning process, such as the learning rate, batch size,
number of layers, number of neurons per layer, activation functions, etc. By fine- tuning these
hyperparameters, we aim to achieve better accuracy, faster convergence, and improved
generalization of the model.
Algorithm:
1. Define Hyperparameter Space:
Define the hyperparameters to be tuned and their respective search spaces. For example, the
learning rate may be searched in the range [0.0001, 0.1], the number of neurons per layer
may be chosen from [32, 64, 128], etc.
2. Choose Optimization Strategy:
Select a hyperparameter optimization strategy. Common strategies include grid search, random
search, Bayesian optimization, and more advanced techniques like genetic algorithms or
evolutionary strategies.
3. Split Data:
Split the dataset into training, validation, and test sets. The validation set will be used to
evaluate the performance of each set of hyperparameters during the tuning process.
4. Define Model Architecture:
Define the architecture of the deep learning model. This includes the number of layers, types of
layers (e.g., convolutional, recurrent, dense), activation functions, regularization techniques,
etc.
5. Define Training Procedure:
Define the training procedure, including the optimizer, loss function, and any additional
callbacks or metrics to monitor during training.
6. Hyperparameter Optimization Loop:
Start the hyperparameter optimization loop:
24
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Program:
import numpy as np
from sklearn.model_selection import GridSearchCV
from [Link] import Sequential
from [Link] import Dense
from [Link].scikit_learn import KerasClassifier
25
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
# Perform GridSearchCV
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3)
grid_result = [Link](X_train, y_train)
# Summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
26
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
OUTPUT:
Best: 0.85 using {'activation': 'relu', 'neurons': 32, 'optimizer': 'adam'}
0.80 (0.02) with: {'activation': 'relu', 'neurons': 8, 'optimizer': 'adam'}
0.82 (0.01) with: {'activation': 'relu', 'neurons': 8, 'optimizer': 'rmsprop'}
...
Test Accuracy: 86.50%
27
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above program was executed successfully
28
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice Questions:
1. Implement a linear regression model using Scikit-Learn to predict housing prices
based on features such as square footage and number of bedrooms.
2. Develop a classification model using logistic regression to classify emails as spam or not
spam. Use the SpamAssassin Public Corpus dataset for training and testing.
3. Apply K-means clustering with Scikit-Learn to segment customers based on their
purchasing behavior. Visualize the clusters and analyze the characteristics of each
segment.
4. Use principal component analysis (PCA) to reduce the dimensionality of a high-
dimensional dataset such as the MNIST dataset. Visualize the principal components and
their contributions to the variance.
5. Build a convolutional neural network (CNN) using TensorFlow or Keras to classify
images from the CIFAR-10 dataset. Experiment with different architectures, activation
functions, and optimization algorithms.
Viva Questions:
1. What is machine learning, and why is it important in today's world?
2. Can you explain the difference between supervised and unsupervised learning?
3. What is supervised learning, and how does it work?
4. Can you give examples of supervised learning algorithms and their applications?
5. What is unsupervised learning, and when is it used?
6. Explain the difference between clustering and dimensionality reduction.
29
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Algorithm:
1. Select Pre-trained Model:
Choose a pre-trained model that has been trained on a large dataset with similar characteristics
to the target dataset. Common choices include VGG, ResNet, Inception, and MobileNet.
2. Load Pre-trained Model:
Load the pre-trained model and remove the top layers (fully connected layers) that are responsible
for making predictions on the original task.
3. Freeze Base Layers (Optional):
Optionally, freeze the weights of the base layers (the layers of the pre-trained model) to prevent
them from being updated during training. This step is recommended when the target dataset is
small and similar to the source dataset.
4. Add New Classification Layers:
Add new layers (typically fully connected layers) on top of the pre-trained base layers. These
layers will be responsible for making predictions on the new target task.
5. Define Training Procedure:
Define the training procedure, including the optimizer, loss function, and any additional callbacks
or metrics to monitor during training.
6. Data Augmentation (Optional):
Optionally, apply data augmentation techniques to increase the diversity of the training data and
improve the model's generalization ability.
7. Train the Model:
Train the model on the target dataset. Since the base layers are frozen (or partially frozen), only
the newly added layers will be trained. This step helps the model learn task-specific features
from the target dataset while leveraging the knowledge learned by the pre-trained model.
30
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
8. Fine-tuning (Optional):
Optionally, unfreeze some of the base layers and continue training the entire model end-to-end.
Fine-tuning allows the model to further adapt to the target dataset and potentially improve
performance.
9. Evaluate the Model:
Evaluate the trained model on a separate validation set to assess its performance. Monitor metrics
such as accuracy, precision, recall, and F1-score.
10. Deploy the Model:
Once satisfied with the model's performance, deploy it to make predictions on new, unseen
images from the target domain.
Program:
import numpy as np
from [Link] import ImageDataGenerator
from [Link] import VGG16
from [Link] import Sequential
from [Link] import Dense, Flatten, Dropout
from [Link] import Adam
# Define constants
img_width, img_height = 224, 224
train_data_dir = 'train'
validation_data_dir = 'validation'
batch_size = 32
num_classes = 2
epochs = 10
train_generator = train_datagen.flow_from_directory(train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
31
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
32
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Found 2000 images belonging to 2 classes.
Found 800 images belonging to 2 classes.
Epoch 1/10
62/62 [==============================] - 125s 2s/step - loss: 0.6138 - accuracy:
0.6746 - val_loss: 0.4546 - val_accuracy: 0.8203
Epoch 2/10
62/62 [==============================] - 123s 2s/step - loss: 0.4683 - accuracy:
0.7778 - val_loss: 0.3788 - val_accuracy: 0.8320
...
Epoch 10/10
62/62 [==============================] - 122s 2s/step - loss: 0.3621 - accuracy:
0.8422 - val_loss: 0.2734 - val_accuracy: 0.8958
25/25 [==============================] - 23s 923ms/step - loss: 0.2841 - accuracy:
0.8863
Validation Loss: 28.41%
Validation Accuracy: 88.63%
33
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above program was executed successfully.
17
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice exercise:
Viva questions:
18
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Algorithm:
1. Select Pre-trained Model:
Choose a pre-trained model from the Keras applications module. Popular choices include
VGG16, VGG19, ResNet50, InceptionV3, Xception, and MobileNet.
5. Compile Model:
Compile the model with an appropriate optimizer, loss function, and evaluation metric.
8. Fine-tuning (Optional):
Optionally, unfreeze some of the base layers and continue training the entire model end-to-
[Link]-tuning allows the model to further adapt to the target dataset and potentially
improve performance.
20
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Program:
import numpy as np
from [Link] import ImageDataGenerator from
[Link] import VGG16
from [Link] import Sequential
from [Link] import Dense, Flatten, Dropout from
[Link] import Adam
# Define constants
img_width, img_height = 224, 224
train_data_dir = 'train'
validation_data_dir = 'validation'
batch_size = 32
num_classes = 2
epochs = 10
train_generator = train_datagen.flow_from_directory(train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
21
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
22
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Found 2000 images belonging to 2 classes. Found
800 images belonging to 2 classes. Epoch 1/10
62/62 [==============================]
- 125s 2s/step - loss: 0.6138 - accuracy: 0.6746
- val_loss: 0.4546 - val_accuracy: 0.8203
...
Epoch 10/10
62/62 [==============================]
- 122s 2s/step - loss: 0.3621 - accuracy: 0.8422 - val_loss: 0.2734 - val_accuracy: 0.8958 25/25
[==============================]
- 23s 923ms/step - loss: 0.2841 - accuracy: 0.8863
Validation Loss: 28.41%
Validation Accuracy: 88.63%
23
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above Program was executed Successfully.
24
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice Exercise:
1. Load a pre-trained CNN model without the classification layers.
2. Freeze the layers of the pre-trained model.
3. Add custom classification layers on top of the pre-trained model.
4. Compile the model with appropriate optimizer and loss function.
5. Prepare the dataset for training and validation, including data augmentation.
6. Train the model using the prepared dataset.
7. Fine-tune the model by unfreezing some of the top layers (optional).
8. Evaluate the trained model on a separate test dataset.
Viva questions:
1. What is transfer learning, and why is it useful in deep learning tasks such as image
classification?
2. Explain the concept of freezing layers in transfer learning. Why do we freeze layers in a
pre-trained model?
3. How does a pre-trained convolutional neural network (CNN) serve as a feature
extractor in transfer learning?
4. What are the advantages of using a pre-trained CNN model like VGG16 or ResNet for
transfer learning?
5. Describe the process of adding custom classification layers on top of a pre-trained
CNN model for a specific task.
6. What is data augmentation, and why is it important in training deep learning
models?
25
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim:
The aim of this lab exercise is to implement a sentiment analysis model using Recurrent
Neural Networks (RNNs) to classify text data into positive or negative sentiment categories.
Algorithm:
1. Dataset Preparation:
Use a labeled dataset for sentiment analysis, such as the IMDb movie review dataset, which
consists of movie reviews labeled as positive or negative.
Split the dataset into training, validation, and test sets.
2. Data Preprocessing:
Clean the text data: Remove special characters, punctuation, and unwanted symbols.
Tokenization: Split the text into individual words or tokens.
Convert words to indices: Map each word to a unique integer index.
Padding: Ensure all sequences have the same length by padding shorter sequences with
zeros or truncating longer sequences.
3. Model Architecture:
Define an RNN architecture using libraries like TensorFlow or PyTorch.
Choose the type of RNN cell (e.g., LSTM, GRU).
Stack multiple RNN layers for better performance if needed.
Add a Dense layer with sigmoid activation for binary classification (positive or negative
sentiment).
4. Model Training:
Initialize the RNN model.
Compile the model with appropriate loss function (e.g., binary cross-entropy) and optimizer
(e.g., Adam).
Train the model on the training data.
Monitor the training process using metrics like accuracy and loss on the validation set.
26
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Tune hyperparameters like learning rate, batch size, and number of epochs based on
validation performance.
5. Evaluation:
Evaluate the trained model on the test set to assess its performance.
Calculate metrics such as accuracy, precision, recall, and F1-score.
Visualize the performance metrics and, if necessary, confusion matrices.
6. Inference:
Use the trained model to predict sentiment on new, unseen text data.
Preprocess the new text data similarly to the training data.
Feed the preprocessed data into the trained model for prediction.
7. Experimentation and Improvement:
Experiment with different model architectures, hyperparameters, and preprocessing
techniques to improve performance.
Explore the use of pre-trained word embeddings to enhance the model's understanding of
text semantics.
Consider advanced techniques like attention mechanisms or bidirectional RNNs for better
capturing context.
8. Conclusion:
Summarize the findings of the lab exercise, including the performance of the sentiment
analysis model and any insights gained during experimentation.
Discuss potential future directions for further improvement or research.
Program:
import numpy as np
from [Link] import pad_sequences
from [Link] import Sequential
from [Link] import Dense, Embedding, LSTM
from [Link] import Tokenizer
from sklearn.model_selection import train_test_split
27
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
28
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Epoch 1/10
1/1 [==============================] - 1s 1s/step - loss: 0.6927 - accuracy: 0.5000 -
val_loss: 0.6931 - val_accuracy: 0.5000
...
Epoch 10/10
1/1 [==============================] - 0s 36ms/step - loss: 0.6583 - accuracy: 1.0000 -
val_loss: 0.6963 - val_accuracy: 0.5000
1/1 [==============================] - 0s 25ms/step - loss: 0.6963 - accuracy: 0.5000
Test Loss: 0.6962565774917603
Test Accuracy: 0.5
29
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above Program was executed Successfully.
30
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice Questions:
1. Load and preprocess the dataset of movie reviews.
2. Preprocess the text data by tokenizing and padding sequences.
3. Build an RNN model for sentiment analysis.
4. Compile the model with appropriate loss and optimizer.
5. Train the model on the training data.
6. Evaluate the model on the test data.
Viva Questions:
1. What is sentiment analysis, and why is it important in natural language processing
(NLP) applications?
2. Explain the concept of Recurrent Neural Networks (RNNs) and how they are suitable for
sequence data like text.
3. How do you preprocess text data for sentiment analysis tasks? What techniques are
commonly used?
4. Describe the architecture of an RNN model for sentiment analysis. What are the key
components?
5. What is tokenization, and why is it necessary in text processing tasks like sentiment
analysis?
31
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim:
The aim of this lab exercise is to implement an LSTM-based autoencoder using
TensorFlow/Keras for sequence data compression and reconstruction.
Algorithm:
1. Dataset Preparation:
Use a dataset containing sequential data, such as time series or text data.
Split the dataset into training and test sets.
2. Data Preprocessing:
Normalize or scale the data if necessary.
Convert the sequential data into fixed-length sequences.
Optionally, add noise to the input sequences to improve the robustness of the autoencoder.
3. Model Architecture:
Define an LSTM-based autoencoder architecture using TensorFlow/Keras.
Create an encoder LSTM layer to compress the input sequence into a fixed-length latent
representation.
Create a decoder LSTM layer to reconstruct the input sequence from the latent
representation.
Connect the encoder and decoder layers to create the autoencoder model.
4. Model Training:
Initialize the LSTM autoencoder model.
Compile the model with an appropriate loss function, such as mean squared error (MSE),
and optimizer, such as Adam.
Train the model on the training data.
Monitor the training process and tune hyperparameters as needed.
5. Evaluation:
32
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Program:
import numpy as np
import tensorflow as tf
from [Link] import Input, LSTM, RepeatVector, TimeDistributed
from [Link] import Model
# Encoder
inputs = Input(shape=([Link][1], [Link][2]))
encoded = LSTM(latent_dim)(inputs)
# Decoder
decoded = RepeatVector([Link][1])(encoded)
decoded = LSTM([Link][2], return_sequences=True)(decoded)
33
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
# Autoencoder
autoencoder = Model(inputs, decoded)
34
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Output:
Epoch 1/50
3/3 [==============================] - 1s 99ms/step - loss: 0.2733 - val_loss: 0.2578
Epoch 2/50
3/3 [==============================] - 0s 12ms/step - loss: 0.2670 - val_loss: 0.2520
...
Epoch 50/50
3/3 [==============================] - 0s 10ms/step - loss: 0.0485 - val_loss: 0.0447
Original Data:
[[0.75828457]
[0.72486731]
[0.1619405 ]
[0.84798926]
[0.77168659]
[0.15825592]
[0.13336555]
[0.56128449]
[0.14060701]
[0.74388057]]
Reconstructed Data:
[[0.68393844]
[0.7702495 ]
[0.15474795]
[0.7850587 ]
[0.72745067]
[0.1947125 ]
[0.1536809 ]
[0.58117414]
[0.15412793]
[0.7389922 ]]
35
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Result:
The above Program was executed Successfully.
36
DHIRAJLAL GANDHI COLLEGE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Practice exercise:
1. Load and preprocess the MNIST dataset.
2. Build an LSTM-based autoencoder architecture.
3. Train the autoencoder model to reconstruct the input digit sequences.
4. Evaluate the performance of the trained model.
5. Use the TensorFlow/Keras library to implement the autoencoder model.
Viva Questions:
37
Experiment Score /10
[Link] Date
of Completion Additional Credits
Aim:
The aim of this lab exercise is to implement a Generative Adversarial Network (GAN) using
TensorFlow/Keras for generating realistic images.
Algorithm:
1. Dataset Preparation:
Choose a dataset suitable for image generation, such as CIFAR-10, CelebA, or MNIST.
Preprocess the dataset, including normalization and resizing, if necessary.
Split the dataset into training and validation sets.
2. Generator Model:
Define the generator model architecture using TensorFlow/Keras.
Start with a simple architecture, such as a series of dense layers followed by upsampling layers
(e.g., transposed convolutions or upsampling layers).
Use activation functions like ReLU or LeakyReLU for intermediate layers and tanh for the
output layer to ensure pixel values are in the range [-1, 1].
3. Discriminator Model:
Define the discriminator model architecture using TensorFlow/Keras.
Start with a convolutional neural network (CNN) architecture to classify real and generated
images.
Use activation functions like LeakyReLU and sigmoid for the output layer to produce a
probability score indicating the likelihood of the input image being real.
4. GAN Model:
Combine the generator and discriminator models to form the GAN model.
Freeze the discriminator weights during GAN training to prevent the generator from
overpowering the discriminator too early.
Compile the GAN model with appropriate loss functions (e.g., binary cross-entropy) and
optimizer (e.g., Adam).
5. Training:
Train the GAN model iteratively in alternating steps:
Train the discriminator using batches of real and fake images, adjusting its weights to better
distinguish between real and generated images.
Train the generator by generating fake images and trying to fool the discriminator into
classifying them as real.
Monitor the training process and adjust hyperparameters such as learning rate and batch size as
needed.
6. Evaluation:
Evaluate the trained GAN model on the validation set to assess the quality of generated images.
Visualize generated images and compare them with real images to evaluate realism and
diversity.
Calculate metrics like Inception Score or Frechet Inception Distance (FID) to quantitatively
evaluate the quality of generated images.
7. Fine-tuning and Optimization:
Experiment with different architectures and hyperparameters to improve the quality of generated
images.
Consider techniques like progressive growing, spectral normalization, or feature matching to
stabilize training and improve image quality.
8. Conclusion:
Summarize the findings of the lab exercise, including the performance of the GAN model and
any insights gained during experimentation.
Discuss potential applications of GANs in image generation and future research directions for
further exploration.
Program:
import numpy as np
import [Link] as plt
from [Link] import mnist
from [Link] import Sequential, Model
from [Link] import Dense, LeakyReLU, BatchNormalization, Reshape, Flatten, Input
from [Link] import Adam
# Generator
def build_generator(latent_dim):
model = Sequential()
[Link](Dense(128, input_dim=latent_dim))
[Link](LeakyReLU(alpha=0.2))
[Link](BatchNormalization(momentum=0.8))
[Link](Dense(256))
[Link](LeakyReLU(alpha=0.2))
[Link](BatchNormalization(momentum=0.8))
[Link](Dense(512))
[Link](LeakyReLU(alpha=0.2))
[Link](BatchNormalization(momentum=0.8))
[Link](Dense([Link]((28, 28, 1)), activation='tanh'))
[Link](Reshape((28, 28, 1)))
return model
# Discriminator
def build_discriminator():
model = Sequential()
[Link](Flatten(input_shape=(28, 28, 1)))
[Link](Dense(512))
[Link](LeakyReLU(alpha=0.2))
[Link](Dense(256))
[Link](LeakyReLU(alpha=0.2))
[Link](Dense(1, activation='sigmoid'))
return model
# Train Generator
noise = [Link](0, 1, (batch_size, latent_dim))
g_loss = combined.train_on_batch(noise, [Link]((batch_size, 1)))
# Print progress
if epoch % sample_interval == 0:
print("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100 * d_loss[1],
g_loss))
# Rescale images 0 - 1
gen_imgs = 0.5 * gen_imgs + 0.5
Viva Questions:
Training from scratch may be preferable when the task or dataset is significantly different from the domain the pre-trained model was designed for, necessitating a model that can learn from a new distribution of data without prior biases. Additionally, training from scratch allows full control over network architecture and hyperparameter tuning, which might lead to more optimized solutions for specific needs .
Using a pre-trained model for transfer learning allows leveraging the knowledge learned by the model on a large dataset, which helps improve performance on a new task with less training time and fewer data. By fine-tuning the pre-trained model on the new data, the model can effectively adapt to the new task while maintaining the robustness acquired from the pre-trained dataset .
Freezing the layers of a pre-trained model is beneficial because it prevents the initial weights from being altered. This is especially useful when the target dataset is small and similar to the source dataset, as it allows the model to retain the comprehensive features already learned, thereby reducing the risk of overfitting while saving on computational resources .
Fine-tuning improves the adaptation of a pre-trained convolutional neural network (CNN) by unfreezing some or all of its layers and retraining the entire model end-to-end with a lower learning rate. This approach enables the model to adjust its weights to better capture the characteristics of the new dataset, thus enhancing its performance on the target domain .
Clustering is an unsupervised learning technique that involves grouping data points into distinct categories based on their similarities. It is useful for tasks like market segmentation. Dimensionality reduction, on the other hand, transforms data from a high-dimensional space into a lower-dimensional space to simplify data visualization and analysis while preserving important information. Principal component analysis (PCA) is a common method. Unlike clustering, dimensionality reduction does not categorize data into groups .
Vector addition in TensorFlow involves creating tensors using tf.constant and performing element-wise addition with the tf.add function. This operation benefits the development of machine learning models by simplifying the manipulation of weights and biases, facilitating the efficient computation of complex operations, and enhancing model scalability .
The Adam optimizer combines the advantages of two other extensions of stochastic gradient descent. It leverages adaptive learning rates for different parameters, which can lead to faster convergence and improved training performance. However, it might not always provide the best generalization for certain tasks compared to more classical optimizers like SGD or RMSProp, especially when hyperparameters are not well-tuned .
The 'include_top=False' argument excludes the top layer (typically the fully connected layers used for classification) when loading a pre-trained model in Keras. This allows flexibility to add and customize new layers for different tasks than the original task the model was trained on, facilitating the use of the model's feature extraction capabilities in new contexts .
Data augmentation artificially increases the size and variability of a training dataset by applying various transformations such as rotations, shifts, flips, and zooms. This helps in improving the model's ability to generalize by reducing overfitting and enhancing robustness under different conditions, which is particularly valuable when the available data is limited .
In TensorFlow, a placeholder is a symbolic variable used to feed data into the network during training, it represents the input data. A variable, however, is a tensor whose value can be changed during execution, representing the weights and biases of the model that are optimized during training .