Tharun
Tharun
Tharun
PADMAVATHY ENGINEERING
COLLEGE
(An Autonomous Institution)
Mambakkam-Medavakkam MainRoad,
Ponmar,Chennai- 600127
Academic Year:2023–2024
Register Number :
Year/ Semester :
PRINCE SHRI VENKATESHWARA
PADMAVATHYENGINEERING COLLEGE
(An Autonomous Institution)
BONAFIDE CERTIFICATE
Name : ………………………………………………
Register No : ………………………………………………
Semester : ………………………………………………
Branch : ………………………………………………
Certified that this is a Bonafide Record of the work done by the above student in the
CCS355-Neural Networks and Deep LearningLaboratory during the year2023- 2024.
To be a prominent institution for technical education and research to meet the global
challenges and demand for the societal needs.
To nurture in the students, professional and ethical values, and to install in them a spirit
of innovation and entrepreneurship.
To encourage in the students a desire for higher learning and research, to equip them to
face the global challenges.
To provide opportunities for students to get the needed additional skills to make them
industry ready.
To produce competent graduates suitable for industries, organization and research at global level
by providing quality technical education and by imparting human values to meet the
globalized technological society.
M2. To produce competent graduates suitable for industries, organization and research at global
level by providing quality technical education and by imparting human values to meet the
globalized technological society.
M3. To promote higher education, research and develop a culture of innovation driven
entrepreneurship by inculcating the professional and moral values in the students.
INSTRUCTIONS TO STUDENTS
Before entering the lab the student should carry the following things (MANDATORY)
Identity card issued by the college.
Class notes
Lab observation book
Lab Manual
Lab Record
Student must sign in and sign out in the register provided when attending the lab session
without fail.
Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed
to attend the lab.
Students need to maintain 100% attendance in lab if not a strict action will be taken.
All students must follow a Dress Code while in the laboratory
Foods, drinks are NOT allowed.
All bags must be left at the indicated place.
Refer to the lab staff if you need any help in using the lab.
Respect the laboratory and its other users.
Workspace must be kept clean and tidy after experiment is completed.
Read the Manual carefully before coming to the laboratory and be sure about what you
are supposed to do.
Do the experiments as per the instructions given in the manual.
Copy all the programs to observation which are taught in class before attending the lab
session.
Students are not supposed to use floppy disks, pen drives without permission of lab- in
charge.
Lab records need to be submitted on or before the date of submission.
Syllabus
TABLE OF CONTENTS
TOPIC BEYOND THE SYLLABUS
AIM:
The aim of implementing simple vector addition in TensorFlow is to demonstrate the
basic syntax and functionality of the framework while performing a fundamental
mathematical operation.
ALGORITHM:
Step 1: Import the TensorFlow library. Importing the TensorFlow library allows us to
use all of the functions and classes that TensorFlow provides
Step 2: Create two vectors, x and y .Creating two vectors, x and y, is done using the
tf.constant() function. This function takes a list of values asinput and creates a
TensorFlow tensor from it.
Step 3: Add the two vectors together. Adding the two vectors together is done using the
tf.add() function. This function takes two tensors as input and returns a
tensor that isthe sum of the two input tensors .
Step 4: Print the result .Printing the result is done using the print() function. This
function prints the value of the input tensor to the console.
PROGRAM:
import tensorflow as tf
# Define two vectors as constants
vector1 = tf.constant([1.0, 2.0, 3.0])
vector2 = tf.constant([4.0, 5.0, 6.0])
# Add the vectors using the add operation
result = tf.add(vector1, vector2)
# Create a TensorFlow session
with tf.Session() as session:
# Run the computation and get the result
addition_result = session.run(result)
# Print the result
print("Vector 1:", addition_result[0])
print("Vector 2:", addition_result[1])
print("Vector Sum:", addition_result[2])
OUTPUT:
VIVA QUESTIONS:
1.What is Tensorflow?
TensorFlow is defined as an open-source platform and framework for
machine
learning, which includes libraries and tools based on Python and Java —
designed with theobjective of training machine learning and deep learning
models on data.
3.Can you explain the concept of a neural network and its basic architecture?
The architecture of neural networks is made up of an input, output, and hidden layer.
Neural networks themselves, or artificial neural networks (ANNs), are a subset of machine
learning designed to mimic the processing power of a human brain.
5.How do you define activation functions in the context of neural networks? Can you
provide examples of commonly used activation functions and explain their purposes?
•Linear or Identity Activation Function.
•Non-linear Activation Function.
•Sigmoid or Logistic Activation Function.
RESULT:
Thus the implementation simple Vector addition in Tensorflow has been
EX NO:2
DATE: IMPLEMENT AREGRESSION MODEL IN KERAS
AIM:
The aim of implementing a regression model in Keras is to develop a neural network that
can accurately predict continuous values based on input features.
ALGORITHM:
Step 1: Import Libraries: Import necessary libraries including Keras, NumPy, and
any other required libraries.
Step 2: Build the Model:Initialize the model Create a Sequential model in Keras.
Step 3: Evaluate the model: Use the evaluate method to evaluate the model's
performance on the test data.
Step 4: Make predictions: Use the trained model to make predictions on new/unseen
data.
Step 5: Save the model: Serialize the trained model to disk for future use
without retraining.
Step 6: Deploy the model: Deploy the trained model in a production environment
for real-world use.
Step 7: Monitor model performance: Continuously monitor the model's performance
and iterates needed to improve it.
PROGRAM:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Generate some sample data for regression
X = np.random.rand(100, 1)
# Input feature
y = 2 * X + 1 + 0.1 * np.random.rand(100, 1)
# Simulated linear relationship with noise
# Define the model architecture
model = keras.Sequential([
layers.Input(shape=(1,)), # Input layer
layers.Dense(1) # Output layer with 1 unit for regression
])
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model model.fit(X, y, epochs=100, verbose=0) # You can adjust the
number of epochs
# Evaluate the model (optional)
loss = model.evaluate(X, y)
print("Mean Squared Error:", loss)
# Make predictions
new_data = np.array([[0.5], [0.8], [1.0]]) # New data for prediction
predictions = model.predict(new_data)
PSVPEC/IT/CCS355/ NEURAL NETWORK AND DEEP LEARNING LABORATORY 19
Reg-411721205051
print("Predictions:", predictions)
OUTPUT:
VIVA
QUESTIONS:
1. What is Keras?
Keras is a high-level, deep learning API developed by Google for implementing
neural networks. It is written in Python and is used to make the implementation
of neural networks easy. It also supports multiple backend neural network
computation.
RESULT:
Thus the implementing a regression model in keras has been successfully
AIM:
The aim of this program is to implement a perceptron model using
TensorFlow/Keras, a powerful library for building and training neural Networks.
ALGORITHM:
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
import numpy as np
# Generate some sample data for a logical OR operation
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # Input features
y = np.array([0, 1, 1, 1]) # Output labels (OR gate)
# Define a simple perceptron model
model = keras.Sequential([
Dense(units=1, input_dim=2, activation='sigmoid')
])
# Compile the model
model.compile(optimizer=SGD(learning_rate=0.1), loss='mean_squared_error',
metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=1000, verbose=0) # You can adjust the number of epochs
# Evaluate the model
loss, accuracy = model.evaluate(X, y)
print("Loss:", loss)
print("Accuracy:", accuracy)
# Make predictions
predictions = model.predict(X)
print("Predictions:")
print(predictions)
OUTPUT:
VIVA QUESTIONS:
2. Define the terms input layer, hidden layer, and output layer in the context of a neural
network.
The Neural Network is constructed from 3 type of layers:
Input layer — initial data for the neural network.
Hidden layers — intermediate layer between input and output layer and place where all the
computation is done.
Output layer — produce the result for given inputs.
5. Explain the concept of gradient descent and how it is used to optimize neural
network parameters.
Gradient Descent is an optimization algorithm for finding a local minimum of a differentiable
function. Gradient descent in machine learning is simply used to find the values of a
function's parameters (coefficients) that minimize a cost function as far as possible
RESULT:
Thus the Implement a perceptron in TensorFlow/Keras Environment has been
successfully executed and codes are generated.
AIM:
Thus the Implement a perceptron in TensorFlow/Keras Environment has been
successfully executed and codes are generated.
ALGORITHM:
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense
import numpy as np
# Generate some sample data
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # Input features
y = np.array([0, 1, 1, 0]) # Output labels (XOR gate)
# Define a feedforward neural network model
model = keras.Sequential([
Dense(units=4, input_dim=2, activation='relu'),
# 2 input features, 4 hidden units with ReLU activation
Dense(units=1, activation='sigmoid') # 1 output unit with sigmoid activation
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=1000, verbose=0) # You can adjust the number of epochs
# Evaluate the model
loss, accuracy = model.evaluate(X, y)
print("Loss:", loss)
print("Accuracy:", accuracy)
# Make predictions
predictions = model.predict(X)
print("Predictions:")
print(predictions)
OUTPUT:
VIVA QUESTIONS:
2. What is a neural network and how does it mimic the human brain?
A neural network is a method in artificial intelligence that teaches computers to
process data in a way that is inspired by the human brain. It is a type of machine
learning process, called deep learning, that uses interconnected nodes or neurons
in a layered structure that resembles the human brain.
4. How do you interpret the weights and activations of a trained neural network
model?
The weights are usually initialized randomly while the bias at 0. The behaviour
of a neuron is also influenced by its activation function which, parallel to the
action potential for a natural neuron, defines the activation conditions and relative
values of the final output.
5. What are some common methods for handling missing data in neural
training?
• Deleting Rows with missing values.
• Impute missing values for continuous variable.
• Impute missing values for categorical variable.
• Other Imputation Methods
RESULT:
Thus the Implement a Feed-Forward Network in TensorFlow/Keras has been
successfully executed and codes are generated.
AIM:
The aim of this project is to implement an Image Classifier using Convolutional
Neural Networks (CNNs) in TensorFlow/Keras.
ALGORITHM:
Step 1:Prepare the Data: Gather and preprocess your dataset. This involves loading
images,resizing them to a uniform size, and possibly normalizing pixel values.
Step 2:Build the CNN Model: Import necessary libraries such as TensorFlow and Keras.
Step 3: Compile the Model: Specify metrics to evaluate the model's performance during
training
Step 4: Train the Model:Feed the training data into the model
Step 8:Save or Deploy the Model:Save the trained model for future use.
PROGRAM:
import tensorflow as tf
from tensorflow import keras from tensorflow.keras.layers import Conv2D, MaxPooling2D,
Flatten, Dense, Dropout
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10) # One-hot encode the labels
y_test = to_categorical(y_test, 10)
# Define the CNN model
model = keras.Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
Flatten(),
Dense(64, activation='relu'),
Dropout(0.5), 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
loss, accuracy = model.evaluate(x_test, y_test)
print("Test Loss:", loss)
print("Test Accuracy:", accuracy)
OUTPUT:
VIVA QUESTIONS:
1. What is mean by CNN?
A convolutional neural network (CNN) is a type of artificial neural network used
primarily for image recognition and processing, due to its ability to recognize
patterns in images.
4. Explain the concept of adaptive learning rate methods such as AdaGrad and
RMSProp.
By adopting Adaptive Learning Rate methodologies like AdaGrad and RMSprop,
we let these optimizer tune the learning rate by learning the characteristics of the
underlying data.
RESULT:
Thus the implement an image Classifier Using Convolutional Neural Networks
(CNNs) in Tensorflow/Keras has been successfully executed and codes are
generated.
AIM:
The aim of this program is to improve the performance of deep learning models by fine-tuning
their hyperparameters.
ALGORITHM:
Step 1: Define Hyperparameters:Identify the hyperparameters of your deep learning model that
you want to fine-tune.
Step 2: Choose Evaluation Metric:Determine the evaluation metric(s) you want to optimize for,
such as accuracy, precision, recall, F1 score, etc.
Step 3: Split Data:Split your dataset into training, validation, and test sets.
Step 4: Set Hyperparameter Search Space:Define the range or distribution for each hyperparameter
you want to tune.
Step 5: Hyperparameter Optimization Loop
Step 6: Select Best Hyperparameters
Step 7: Train Final Model: Train the final model using the selected hyperparameters
Step 8: Evaluate on Test Set: Evaluate the performance of the final model on the test
Step 9: Iterate: Depending on the results, you might want to iterate on the process by adjusting the
search space or trying different hyperparameter optimization techniques.
Step 10: Deploy Model : Once satisfied with the performance, deploy the model for real-world use.
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10) # One-hot encode the labels
y_test = to_categorical(y_test, 10)
# Define a function to create and compile the CNN model
def create_cnn_model(learning_rate=0.001, dropout_rate=0.25):
model = keras.Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
Flatten(),
Dense(64, activation='relu'),
Dropout(dropout_rate),
Dense(10, activation='softmax')
])
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
return model
# Define hyperparameters to search
learning_rates = [0.001, 0.01, 0.0001]
dropout_rates = [0.25, 0.5]
best_accuracy = 0
best_model = None
# Hyperparameter tuning loop
for lr in learning_rates:
for dr in dropout_rates:
print(f"Training model with learning rate = {lr} and dropout rate = {dr}")
model = create_cnn_model(learning_rate=lr, dropout_rate=dr)
model.fit(x_train, y_train, epochs=10, verbose=0)
_, accuracy = model.evaluate(x_test, y_test)
if accuracy >best_accuracy:
best_accuracy = accuracy
best_model = model
print(f"Best Test Accuracy: {best_accuracy}")
OUTPUT:
VIVA QUESTIONS:
RESULT:
Thus the performance of deep learning models by fine-tuning their
hyperparameters has been successfully executed and codes are generated.
AIM:
The aim of implementing transfer learning in an image classification program is to
harness the knowledge learned by pre-trained models on large datasets and apply it to
similar tasks with limited data availability.
ALGORITHM:
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.optimizers import Adam
# Load a pre-trained model (MobileNetV2) excluding the top classification layers
base_model = MobileNetV2(weights='imagenet', include_top=False)
# Create a new model on top
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
model = keras.Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the pre-trained model
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy',
metrics=['accuracy'])
# Load and preprocess your dataset
# You can use your own dataset or a built-in dataset like CIFAR-10
# Example of using CIFAR-10
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
PSVPEC/IT/CCS355/ NEURAL NETWORK AND DEEP LEARNING LABORATORY 47
Reg-411721205051
OUTPUT:
VIVA QUESTIONS:
RESULT:
Thus the Implement a Transfer Learning concept in Image Classification
has been successfully executed and codes are generated
AIM:
The aim of using a pre-trained model for transfer learning in Keras is to expedite the
process of developing highly accurate image classification models, even when faced
with limited computational resources or labeled data.
ALGORITHM:
Step 1:Select Pre-trained Model: Choose a pre-trained convolutional neural
network (CNN) model such as VGG, ResNet, Inception, or MobileNet.
Step 2:Load Pre-trained Model: Load the pre-trained model along with its
weights, excluding the classification layers.
Step 3:Freeze Base Layers :Optionally freeze the weights of the convolutional base
layers to prevent them from being updated during training.
Step 4:Modify Architecture Replace
Step 5:Compile Model: Compile the modified model with an appropriate loss
Function,optimizer, and evaluation metric for your classification task.
Step 6:Train Model: Train the modified model on your new dataset.
Step 7:Fine-tune: Optionally unfreeze some of the top layers of the pre-trained model
and continue training on the new dataset with a lower learning rate to fine-tune
the model further.
Step 8:Evaluate Model: Evaluate the trained model on a separate validation set to
assess its performance.
Step 9:Test Model :Test the trained model on a separate test set to assess its
generalization performance on unseen data.
Step 10:Deploy Model Once satisfied with the model's performance, deploy it
for inference on new images in real-world applications.
PROGRAM:
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Load pre-trained VGG16 model without top layers
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# Freeze base model layers
for layer in base_model.layers:
layer.trainable = False
# Custom output layers
model = Sequential()
model.add(base_model)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy'])
# Print model summary
model.summary()
# Define data generators
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory('train',
target_size=(224, 224),
batch_size=32,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory('validation',
target_size=(224, 224),
batch_size=32,
class_mode='binary')
# Train the model
history = model.fit(train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=validation_generator,
validation_steps=len(validation_generator))
print("Training and validation accuracy over epochs:")
print(history.history['accuracy'])
print(history.history['val_accuracy'])
OUTPUT:
VIVA QUESTIONS:
1. What is a pre-trained model in the context of deep learning?
A pre-trained model is a model that has been trained on a large dataset, typically
for a specific task such as image classification, object detection, or natural
language processing.
5. When would you choose to fine-tune the layers of a pre-trained model during
transfer learning?
Fine-tuning the layers of a pre-trained model is typically done when the new
task is similar to the task the model was originally trained on, but the dataset for
the new task is significantly different. In such cases, fine-tuning allows the model
to adapt its learned features to the nuances of the new dataset, potentially leading
to better performance. However, fine-tuning requires caution as it can lead to
overfitting, especially when the new dataset is small.
RES
ULT:
PSVPEC/IT/CCS355/ NEURAL NETWORK AND DEEP LEARNING LABORATORY 57
Reg-411721205051
AIM:
To train an RNN model on a dataset containing labeled examples of text with
corresponding sentiment labels.
ALGORITHM:
Step 1:Data Collection Gather a dataset of text documents labeled with sentiment.
Step 2:Data Preprocessing : Tokenization Split each text document into individual
words or tokens.
Step 3:Embedding Layer:Convert each word index into a dense vector representation .
Step 5:Inference:Use the trained model to predict sentiment labels for new text data.
PROGRAM:
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, SimpleRNN, Dense
from tensorflow.keras.optimizers import Adam
# Load and preprocess the IMDb dataset
max_features = 10000 # Maximum number of words in the vocabulary
maxlen = 100 # Maximum sequence length
batch_size = 32
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
x_train = pad_sequences(x_train, maxlen=maxlen)
x_test = pad_sequences(x_test, maxlen=maxlen)
# Build the RNN model
model = Sequential()
model.add(Embedding(max_features, 32))
model.add(SimpleRNN(32))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer=Adam(lr=0.001), loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=5, batch_size=batch_size, validation_split=0.2)
# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test)
print("Test Loss:", loss)
OUTPUT:
VIVA QUESTIONS:
. 2.What is an RNN, and how does it differ from other types of neural networks?
A Recurrent Neural Network (RNN) is a type of neural network architecture
designed to handle sequential data by maintaining a hidden state that captures
information from previous time steps. Unlike feedforward neural networks, which
process input data independently, RNNs are capable of capturing temporal
dependencies in sequences.
. 3.How does the embedding layer work in the context of sentiment analysis?
The embedding layer converts input word indices into dense vectors of fixed size,
allowing the model to learn meaningful representations of words in a continuous
space. This dense representation helps capture semantic relationships between
words and improves the model's ability to generalize to unseen data.
. 5.What is the significance of the activation function 'sigmoid' in the output layer
. of the sentiment analysis model?
The sigmoid activation function squashes the output of the neural network to a
range between 0 and 1, making it suitable for binary classification tasks like
sentimentanalysis.
RESULT:
Thus the Perform Sentiment Analysis using RNN has been successfully
executed and codes are generated.
AIM:
The aim of this project is to implement an LSTM-based autoencoder using
TensorFlow/Keras.
ALGORITHM:
Step 1:Import Necessary Libraries: Import TensorFlow and other required libraries
like Keras.
Step 2: Prepare the Data: Prepare your data for training the autoencoder. It could be
time series data or any sequential data.
Step 3:Combine Encoder and Decoder: Create an instance of the Sequential or
Functional API model.
Step 4:Compile the Model: Define the loss function, typically mean squared
error (MSE), since it's a reconstruction task.
Step 5:Train the Model: Fit the model to your training data.
Step 6:Evaluate the Model: Evaluate the performance of the autoencoder on
your validation set.
Step 7:Use the Autoencoder: Once trained, you can use the encoder part to
extract meaningful representations from your data.
Step 8:Fine-tuning and Optimization: Experiment with different architectures,
hyperparameters, and training strategies to improve performance.
Step 9:Save and Deploy :Save the trained model for future use or deployment in
production systems.
PROGRAM:
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Load pre-trained VGG16 model without top layers
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# Freeze base model layers
for layer in base_model.layers:
layer.trainable = False
# Custom output layers
model = Sequential()
model.add(base_model)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy'])
# Print model summary
model.summary()
# Define data generators
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory('train',
target_size=(224, 224),
batch_size=32,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory('validation',
target_size=(224, 224),
batch_size=32,
class_mode='binary')
# Train the model
history = model.fit(train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=validation_generator,
validation_steps=len(validation_generator))
# Example output
print("Training and validation accuracy over epochs:")
print(history.history['accuracy'])
print(history.history['val_accuracy'])
OUTPUT:
VIVA QUESTIONS:
1. What is an autoencoder?
An autoencoder is an unsupervised learning neural network architecture that
aims to learn efficient representations of input data by training the model to
reconstruct its input.
2. How does the LSTM architecture differ from traditional feedforward neural
networks?
Long Short-Term Memory (LSTM) networks are a type of recurrent neural
network (RNN) designed to process sequential data while addressing the
vanishing gradient problem
RESULT:
Thus the Implement an LSTM based Autoencoder in TensorFlow/Keras has
been successfully executed and codes are generated.
AIM:
The aim of an Image Generation using GANs program is to harness the power of
deep learning to generate images that exhibit realistic characteristics.
ALGORITHM:
Step 1:Import Necessary Libraries: Import TensorFlow (or any other deep learning
framework) along with other required libraries like NumPy for numerical
operations and Matplotlib for visualization.
Step 2:Build the Discriminator: Define the discriminator architecture using
convolutional layers.
Step 3:Compile Discriminator:Compile the discriminator with appropriate loss
function (binary cross-entropy) and optimizer (e.g., Adam).
Step 4:Compile GAN Model: Compile the GAN model with binary cross-entropy loss
and optimizer (e.g., Adam).
Step 5:Training Loop: Iterate over a fixed number of epochs.
Step 6:Evaluate and Visualize: Periodically, evaluate the performance of the generator
by generating sample images.
Step 7:Tune and Optimize: Experiment with different architectures, hyperparameters,
and training strategies to improve the quality of generated images.
Step 8:Save and Deploy: Save the trained generator model for future use or deployment
in production systems.
Step 9:Iterate and Improve: Iterate on the GAN architecture and training process
to achieve better image generation results.
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, LeakyReLU, Reshape, Flatten
from tensorflow.keras.optimizers import Adam
# Define the generator
generator = keras.Sequential([
Dense(128, input_shape=(100,), activation='relu'),
Dense(784, activation='sigmoid'),
Reshape((28, 28))
])
# Define the discriminator
discriminator = keras.Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
# Combine the generator and discriminator to form a GAN
discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
discriminator.trainable = False # Set discriminator non-trainable
gan_input = keras.Input(shape=(100,))
x = generator(gan_input)
gan_output = discriminator(x)
gan = keras.Model(gan_input, gan_output)
gan.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
# Load the MNIST dataset
mnist = keras.datasets.mnist
(X_train, _), (_, _) = mnist.load_data()
OUTPUT:
VIVA QUESTIONS:
Mode collapse: The generator may learn to generate a limited set of samples,
ignoring the diversity of the true data distribution.
Instability: GAN training is sensitive to hyperparameters and architecture
choices, and it may suffer from mode collapse or oscillation during training.
RESULT:
Thus the Image generation using GAN has been successfully executed and codes are
generated.
AIM:
The aim of this project is to train a deep learning model to classify given images into
multiple classes using a pre-trained model as a base.
ALGORITHM:
Step 1:Import Necessary Libraries Import TensorFlow (or any other deep learning
framework), along with other required libraries like Keras, NumPy, and
Matplotlib.
Step 2:Load Pre-trained Model: Load a pre-trained convolutional neural
network (CNN) model that has been trained on a large dataset (e.g., ImageNet).
Step 3:Data Augmentation Optionally, apply data augmentation techniques such as
random rotations, flips, shifts, or zooms to increase the diversity of training
examples and improve generalization.
Step 4:Evaluate the Model: Evaluate the performance of the trained model on your
testing data using the evaluate() method. Calculate metrics such as
accuracy,precision, recall, and F1-score to assess classification performance.
Step 5:Visualize Results: Visualize the model's predictions on sample images from the
testing set to gain insights into its performance and identify any
misclassifications.
Step 6:Fine-tune and Optimize: Experiment with different architectures,
hyperparameters,and training strategies to improve the model's performance.
Fine-tune based on evaluation results to achieve better classification accuracy.
Step 7:Save and Deploy Save the trained model weights and architecture for future use
or deployment in production systems.
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Input
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Load a pre-trained model (MobileNetV2) excluding the top classification layers
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(32, 32, 3))
# Add custom classification layers on top
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x) # 10 classes in CIFAR-10
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the pre-trained model
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
OUTPUT:
VIVA QUESTIONS:
4. What are some common activation functions used in the classification layers of
deep learning models?
Common activation functions used in classification layers include ReLU (Rectified
Linear Unit) for hidden layers and softmax for the output layer in multi-class
classification tasks.
5. How do you evaluate the performance of a deep learning model trained for
image classification?
The performance of an image classification model can be evaluated using metrics such
as accuracy, precision, recall, and F1-score on a separate validation or test dataset.
Additionally, visual inspection of the model's predictions onsample images can provide
insights into its performance and potential areas for improvement.
RESULT:
Thus the Train a Deep learning model to classify a given image using pretrained model has
been successfully executed and codes are generated.
AIM:
The aim of this recommendation system from sales data using deep learning is to provide
personalized product recommendations.
ALGORITHM:
Step 1:Data Collection and Preprocessing: Collect historical sales data, including
information about customers, products, and transactions.
Step 2:Train the Model: Train the deep learning model using the training data.
Step 3:Evaluate the Model: Evaluate the performance of the trained model on the
testing data.
Step 5:Deploy the Model: Deploy the trained model into a production environment
where it can generate recommendations in real-time or in batch mode.
PROGRAM:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Input
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
# Load and preprocess the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Normalize pixel values to the range [0, 1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Load a pre-trained model (MobileNetV2) excluding the top classification layers
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(32, 32, 3))
# Add custom classification layers on top
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x) # 10 classes in CIFAR-10
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the pre-trained model
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
OUTPUT:
VIVA QUESTIONS:
2. How can deep learning be applied to build recommendation systems from sales
data?
Deep learning techniques, such as neural collaborative filtering (NCF) and deep
autoencoders, can be applied to learn complex patterns and representations from
sales data to generate accurate recommendations.
3. What types of sales data are typically used to build recommendation systems?
Various types of sales data can be used, including transactional data
(e.g., purchase history), user behavior data (e.g., browsing history,
clickstream data), user profile data (e.g., demographic information, preferences),
and item attributes (e.g., product descriptions, features).
RESULT:
Thus the Recommendation system from sales data using Deep Learning has been
successfully executed and codes are generated.
AIM:
The aim of implementing object detection using CNN is to develop a model capable
of accurately detecting and localizing objects within images.
ALGORITHM:
Step 1:Data Collection and Annotation: Gather a dataset of images containing the
objects you want to detect.
Step 2: Preprocess the Data: Resize the images to a consistent size suitable for input to
the CNN.
Step 3:Choose a CNN Architecture:Select a CNN architecture suitable for object
detection tasks.
Step 4:Split Data into Training and Testing Sets: Divide the dataset into training and
testing sets to evaluate the model's performance.
Step 5:Build the Model: Implement the chosen CNN architecture using a deep learning
framework like TensorFlow or PyTorch.
Step 6:Train the Model: Train the model on the training data using the fit() or train()
method.
Step 7:Evaluate the Model:Evaluate the performance of the trained model on the
testing data.
Step 8:Deploy the Model:Deploy the trained model in a production environment
where it can detect objects in new images or videos.
PROGRAM:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# Define the paths to the model and label map
PATH_TO_FROZEN_GRAPH = 'path/to/frozen_inference_graph.pb'
PATH_TO_LABELS = 'path/to/label_map.pbtxt'
# Load a frozen model and label map
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
lOMoARcPSD|33990425
tf.import_graph_def(od_graph_def, name='')
category_index =
label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,
use_display_name=True)
# Function to run object detection
def run_inference_for_single_image(image, graph):
with graph.as_default():
image = Image.open(image_path)
image_np = np.array(image)
# Actual detection.
output_dict = run_inference_for_single_image(image_np, detection_graph)
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=8)
plt.figure(figsize=(12, 8))
plt.imshow(image_np)
plt.show()
OUTPUT:
VIVA QUESTIONS:
1. What is object detection, and how does it differ from image classification?
Object detection is the process of identifying and localizing objects within an
image, often by drawing bounding boxes around them. Unlike image
classification, which assigns a single label to the entire image, object detection
requires identifying multiple objects and their locations within the image.
such as precision, recall, F1-score, and mean Average Precision (mAP). These
metrics assess the accuracy, completeness, and localization quality of the detected
objects compared to ground truth annotations.
RESULT:
Thus the Implement Object Detection using CNN has been successfully executed
and codes are generated.
AIM:
The aim of this project is to implement a simple reinforcement learning algorithm for
solving an NLP problem.
ALGORITHM:
Step 1:Import Necessary Libraries: Import libraries such as TensorFlow, Keras, or
PyTorch for deep learning, along with any other required libraries for text
processing and RL.
Step 2:Preprocess Text Data: Prepare your text data for training. This may involve
tokenization, padding, and any other necessary preprocessing steps.
Step 3:Define the Environment: Define the RL environment for the text generation task.
Step 4:Define the Reward Function: Define a reward function that evaluates the
quality of generated text sequences.
Step 5:Training Loop: Iterate over a fixed number of episodes or until convergence.
Step 6:Fine-tune and Optimize: Experiment with different architectures,
hyperparameters, and training strategies to improve text generation quality.
Step 7:Generate Text: Use the trained text generation model to generate text samples.
Step 8:Deploy the Model: Deploy the trained text generation model in a production
environment where it can generate text on-demand.
PROGRAM:
import random
# Define a simple environment with a chatbot
class ChatbotEnvironment:
def __init__(self):
self.state = "Hello, how can I assist you?"
self.conversation_history = []
self.reward = 0
def step(self, action):
user_query = action
self.conversation_history.append((self.state, user_query))
# Simulate chatbot's response (you can replace this with a more advanced model)
if "help" in user_query:
self.state = "Sure, I can help you with that. What do you need?"
self.reward += 1
elif "thank you" in user_query:
self.state = "You're welcome! Let me know if you need anything else."
self.reward += 1
else:
self.state = "I'm sorry, I didn't understand. Can you rephrase your question?"
self.reward -= 1
return self.state, self.reward
# Define a simple Q-learning agent
class QLearningAgent:
def __init__(self, actions, learning_rate=0.1, discount_factor=0.9,
exploration_prob=0.2):
self.actions = actions
self.learning_rate = learning_rate
self.discount_factor = discount_factor
self.exploration_prob = exploration_prob
self.q_table = {}
def choose_action(self, state):
if random.uniform(0, 1) <self.exploration_prob:
return random.choice(self.actions)
else:
q_values = [self.q_table.get((state, a), 0) for a in self.actions]
return self.actions[q_values.index(max(q_values))]
def learn(self, state, action, reward, next_state):
current_q = self.q_table.get((state, action), 0)
best_next_q = max([self.q_table.get((next_state, a), 0) for a in self.actions])
updated_q = current_q + self.learning_rate * (reward + self.discount_factor * best_next_q - current_q)
self.q_table[(state, action)] = updated_q
# Train the chatbot using Q-learning
env = ChatbotEnvironment()
agent = QLearningAgent(actions=["ask", "thank"])
epochs = 1000
for _ in range(epochs):
state = env.state
action = agent.choose_action(state)
next_state, reward = env.step(action)
agent.learn(state, action, reward, next_state)
# Test the trained chatbot
state = env.state
print("Chatbot's response:", state)
OUTPUT:
VIVA QUESTIONS:
1. What is reinforcement learning, and how does it differ from other machine
learning paradigms?
Reinforcement learning is a type of machine learning paradigm where an agent
learns to make decisions by interacting with an environment to maximize cumulative
rewards.
3. How is the concept of states, actions, and rewards applied in the context of
NLP problems?
In NLP problems, states represent the current context or partial output, actions
correspond to possible words or tokens that can be added to the output, and
rewards can be based on the quality or fluency of the generated text.
4. What are the key components of the Q-learning algorithm, and how do they
interact?
The key components of the Q-learning algorithm include the Q-table, which stores
the expected cumulative rewards for each action-state pair, the environment,
which defines the state transitions and rewards, and the learning parameters such
as learning rate (alpha), discount factor (gamma), and exploration rate (epsilon).
RESULT:
Thus the Implement any simple Reinforcement Algorithm for an NLP problem has been
successfully executed and codes are generated.