Ccs355 Experiments
Ccs355 Experiments
INDEX
2
lOMoARcPSD|37319915
Ex. No: 01
Date:
Implement simple vector addition in TensorFlow
Aim:
To implement a basic vector addition using TensorFlow.
Algorithm:
1. Import the TensorFlow library.
2. Define two vectors as constants (e.g., vector1 and vector2).
3. Use the [Link] operation to add the two vectors element-wise.
4. Print the result of the vector addition.
Program:
import tensorflow as tf
Output:
Result of vector addition:
[5. 7. 9.]
Result:
Thus the above program for basic vector addition using TensorFlow were executed and
the output is verified successfully.
3
lOMoARcPSD|37319915
Ex. No: 02
Implement a regression model in Keras.
Date:
Aim:
To implement a regression model using the Keras.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Generate synthetic data for training the regression model.
3. Define the architecture of the neural network for regression.
4. Compile the model, specifying the loss function and optimizer.
5. Train the model using the synthetic data.
6. Evaluate the model's performance.
7. Make predictions using the trained model.
Program:
import tensorflow as tf
from [Link] import Sequential
from [Link] import Dense
from sklearn.model_selection import train_test_split
import numpy as np
[Link](42)
X = [Link](100, 1)
y = 3 * X + 2 + 0.1 * [Link](100, 1)
model = Sequential()
[Link](Dense(1, input_dim=1, activation='linear'))
[Link](optimizer='sgd', loss='mean_squared_error')
predictions = [Link](X_test)
4
lOMoARcPSD|37319915
print("\nSample Predictions:")
for i in range(5):
print(f"Actual: {y_test[i][0]}, Predicted: {predictions[i][0]}")
Output:
Epoch 50/50
Sample Predictions:
Result:
Thus the above program for implementation of regression model in keras were
executed and the output is verified successfully.
5
lOMoARcPSD|37319915
Ex. No: 03
Implement a perceptron in TensorFlow/Keras Environment.
Date:
Aim:
To implement a perceptron using the TensorFlow/Keras Environment.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Generate synthetic data for training the perceptron.
3. Define the architecture of the perceptron with a single layer and one output neuron.
4. Compile the model, specifying the binary cross-entropy loss and the stochastic
gradient descent (SGD) optimizer.
5. Train the perceptron using the synthetic data.
6. Evaluate the model's performance.
7. Make predictions using the trained perceptron.
Program:
import numpy as np
import tensorflow as tf
from [Link] import Dense
from [Link] import Sequential
from [Link] import SGD
[Link](42)
X = [Link](100, 2)
y = [Link](X[:, 0] + X[:, 1] > 1, 1, 0)
model = Sequential()
[Link](Dense(units=1, activation="sigmoid", input_shape=(2,)))
[Link](loss="binary_crossentropy", optimizer=SGD(learning_rate=0.1),
metrics=["accuracy"])
prediction = [Link](X)
prediction_labels = [Link](prediction)
print("predicted Labels: ", [Link](prediction_labels))
6
lOMoARcPSD|37319915
Output:
0. 1. 1. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 1. 0. 0. 1. 0. 0. 1. 1. 0. 1. 1.
0. 0. 0. 0. 1. 1. 0. 0. 1. 1. 1. 1. 1. 0. 0. 1. 0. 0. 0. 1. 1. 1. 1. 0.
0. 1. 0. 1. 0. 1. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 1. 1. 0. 1. 0. 1. 0. 0.
1. 0. 1. 1.]
Result:
Thus the above program for implementation of perceptron were executed and the
output is verified successfully.
7
lOMoARcPSD|37319915
Ex. No: 04
Date:
Implement a Feed-Forward Network in TensorFlow/Keras.
Aim:
To implement a feed-forward neural network using the TensorFlow/Keras.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Generate synthetic data for training the neural network.
3. Define the architecture of the feed-forward neural network with multiple layers.
4. Compile the model, specifying the loss function and optimizer.
5. Train the neural network using the synthetic data.
6. Evaluate the model's performance.
7. Make predictions using the trained neural network.
Program:
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from [Link] import make_classification
model = [Link](
[
[Link](64, activation="relu", input_shape=(20,)),
[Link](1, activation="sigmoid"),
]
)
[Link](optimizer="adam", loss="binary_crossentropy",
metrics=["accuracy"])
[Link](X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
8
lOMoARcPSD|37319915
Output:
Epoch 10/10
Result:
Thus the above program for implementation of feed forward network were executed
and the output is verified successfully.
9
lOMoARcPSD|37319915
Ex. No: 05
Date:
Implement an Image Classifier using CNN in TensorFlow/Keras.
Aim:
To implement an image classifier using a Convolutional Neural Network (CNN) with
TensorFlow/Keras.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Load and preprocess image data.
3. Define the architecture of the CNN with convolutional and pooling layers.
4. Compile the model, specifying the loss function, optimizer, and metrics.
5. Train the CNN using the image data.
6. Evaluate the model's performance.
7. Make predictions using the trained CNN.
Program:
import tensorflow as tf
from keras import datasets, layers, models
import [Link] as plt
class_names = [
"airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck",
]
[Link](figsize=(10, 10))
for i in range(25):
[Link](5, 5, i + 1)
[Link]([])
[Link]([])
[Link](False)
10
lOMoARcPSD|37319915
[Link](train_images[i])
[Link](class_names[train_labels[i][0]])
[Link]()
model = [Link]()
[Link](layers.Conv2D(32, (3, 3), activation="relu", input_shape=(32, 32,
3)))
[Link](layers.MaxPooling2D((2, 2)))
[Link](layers.Conv2D(64, (3, 3), activation="relu"))
[Link](layers.MaxPooling2D((2, 2)))
[Link](layers.Conv2D(64, (3, 3), activation="relu"))
[Link]()
[Link]([Link]())
[Link]([Link](64, activation="relu"))
[Link]([Link](10))
[Link]()
[Link](
optimizer="adam",
loss=[Link](from_logits=True),
metrics=["accuracy"],
)
history = [Link](
train_images, train_labels, epochs=10, validation_data=(test_images,
test_labels)
)
[Link]([Link]["accuracy"], label="accuracy")
[Link]([Link]["val_accuracy"], label="val_accuracy")
[Link]("Epoch")
[Link]("Accuracy")
[Link]([0.5, 1])
[Link](loc="lower right")
Output:
11
lOMoARcPSD|37319915
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 30, 30, 32) 896
12
lOMoARcPSD|37319915
=================================================================
Total params: 56,320
Trainable params: 56,320
Non-trainable params: 0
_________________________________________________________________
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 30, 30, 32) 896
13
lOMoARcPSD|37319915
=================================================================
Total params: 122,570
Trainable params: 122,570
Non-trainable params: 0
_________________________________________________________________
Epoch 10/10
1563/1563 [==============================] - 104s 66ms/step - loss: 0.6062 -
accuracy: 0.7883 - val_loss: 0.8608 - val_accuracy: 0.7181
313/313 - 4s - loss: 0.8608 - accuracy: 0.7181 - 4s/epoch - 13ms/step
0.7181000113487244
Result:
Thus the above program for implementation of image classifier using CNN were
executed and the output is verified successfully.
14
lOMoARcPSD|37319915
Ex. No: 06
Improve the Deep learning model by fine tuning hyper parameters.
Date:
Aim:
To improve the deep learning model by fine-tuning hyperparameters.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Generate synthetic data for training the neural network.
3. Define a function to create the model with hyperparameters as arguments.
4. Compile the model, specifying the loss function and optimizer.
5. Train the neural network using the synthetic data.
6. Evaluate the model's performance.
7. Fine-tune hyperparameters and repeat steps 3-6.
Program:
import tensorflow as tf
from [Link] import Sequential
from [Link] import Dense
from sklearn.model_selection import train_test_split
import numpy as np
[Link](42)
X = [Link](100, 10)
y = [Link](0, 2, size=(100,))
[Link](Dense(1, activation='sigmoid'))
optimizer = [Link](learning_rate=learning_rate)
15
lOMoARcPSD|37319915
[Link](optimizer=optimizer, loss='binary_crossentropy',
metrics=['accuracy'])
return model
initial_hidden_layers = 2
initial_neurons_per_layer = 8
initial_learning_rate = 0.001
initial_activation_function = 'relu'
fine_tuned_neurons_per_layer = 16
fine_tuned_epochs = 100
fine_tuned_model = create_model(initial_hidden_layers,
fine_tuned_neurons_per_layer, initial_learning_rate,
initial_activation_function)
Output:
Epoch 100/100
Result:
Thus the above program for improving the Deep Learning model by fine tunning
hyper parameters were executed and the output is verified successfully.
16
lOMoARcPSD|37319915
Ex. No: 07
Date:
Implement a Transfer Learning concept in Image Classification.
Aim:
To implement Transfer Learning in Image Classification
Algorithm:
1. Load cifar10 dataset form keras datasets.
2. Load the pre-trained MobileNetV2 model.
3. Modify the model by adding new layers for the specific classification task.
4. Compile the model, specifying the loss function, optimizer, and metrics.
5. Train the model using the image data.
6. Evaluate the model's performance.
7. Make predictions using the trained model.
Program:
import [Link] as plt
import seaborn as sns
import cv2
import os
import numpy as np
def get_data(data_dir):
data = []
for label in labels:
path = [Link](data_dir, label)
class_num = [Link](label)
for img in [Link](path):
try:
img_arr = [Link]([Link](path, img))[..., ::-1]
resized_arr = [Link](img_arr, (img_size, img_size))
[Link]([resized_arr, class_num])
except Exception as e:
print(e)
return [Link](data)
17
lOMoARcPSD|37319915
train = get_data("/content/input/train")
val = get_data("/content/input/test")
l = []
for i in train:
if i[1] == 0:
[Link]("rugby")
else:
[Link]("soccer")
sns.set_style("darkgrid")
[Link](x=l, hue=l, palette="Set3")
[Link]()
[Link](figsize=(5, 5))
[Link](train[1][0])
[Link](labels[train[0][1]])
[Link](figsize=(5, 5))
[Link](train[-1][0])
[Link](labels[train[-1][1]])
[Link]()
18
lOMoARcPSD|37319915
Output:
Result:
Thus the above program for implementation of Transfer Learning concept in Image
Classification were executed and the output is verified successfully.
19
lOMoARcPSD|37319915
Ex. No: 08
Date:
Using a pre trained model on Keras for Transfer Learning
Aim:
To using a pre-trained model on Keras for Transfer Learning
Algorithm:
1. Load and preprocess the new dataset.
2. Load the pre-trained MobileNetV2 model without the top (classification) layer.
3. Add a new classification layer suited to your task on top of the pre-trained model.
4. Compile the model.
5. Train the model on the new dataset.
6. Evaluate the model's performance.
Program:
import numpy as np
from [Link] import Model
from [Link].vgg16 import VGG16, preprocess_input
from [Link] import Dense, Flatten, Input
from [Link] import load_img, img_to_array
from [Link] import ImageDataGenerator
flatten_layer = Flatten()([Link])
[Link](optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
train_data_gen = ImageDataGenerator(
rescale=1.0 / 255,
shear_range=0.5,
zoom_range=0.7,
horizontal_flip=True,
vertical_flip=True,
20
lOMoARcPSD|37319915
train_data = train_data_gen.flow_from_directory(
"/content/Wether/Wether/Train", target_size=(224, 224),
class_mode="categorical"
)
test_data = test_data_gen.flow_from_directory(
"/content/Wether/Wether/Test", target_size=(224, 224),
class_mode="categorical"
)
prediction = [Link](my_image)
res = [[Link](x) for x in prediction]
print(res)
21
lOMoARcPSD|37319915
Output:
Epoch 1/5
36/36 [==============================] - 19s 511ms/step - loss: 1.0154 - accuracy:
0.6107 - val_loss: 0.5228 - val_accuracy: 0.7920
Epoch 2/5
36/36 [==============================] - 19s 540ms/step - loss: 0.4699 - accuracy:
0.8320 - val_loss: 0.4626 - val_accuracy: 0.8400
Epoch 3/5
36/36 [==============================] - 19s 512ms/step - loss: 0.3671 - accuracy:
0.8693 - val_loss: 0.1625 - val_accuracy: 0.9600
Epoch 4/5
36/36 [==============================] - 18s 499ms/step - loss: 0.3070 - accuracy:
0.9004 - val_loss: 0.2483 - val_accuracy: 0.9360
Epoch 5/5
36/36 [==============================] - 18s 502ms/step - loss: 0.3277 - accuracy:
0.8782 - val_loss: 0.1385 - val_accuracy: 0.9520
1/1 [==============================] - 1s 603ms/step
[array([0., 0., 0., 1.], dtype=float32)]
Result:
Thus the above program for using pre-trained model on keras for Transfer Learning
were executed and the output is verified successfully.
22
lOMoARcPSD|37319915
Ex. No: 09
Perform Sentiment Analysis using RNN.
Date:
Aim:
To perform sentiment analysis using a Recurrent Neural Network (RNN) with
TensorFlow/Keras.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Load and preprocess text data for sentiment analysis.
3. Tokenize and pad the text sequences.
4. Define the architecture of the RNN model.
5. Compile the model, specifying the loss function and optimizer.
6. Train the RNN using the text data.
7. Evaluate the model's performance.
8. Make predictions using the trained RNN.
Program:
import numpy as np
import tensorflow as tf
from [Link] import Sequential
from [Link] import Embedding, SimpleRNN, Dense, Flatten
from [Link] import Tokenizer
from [Link] import pad_sequences
from sklearn.model_selection import train_test_split
texts = ["I love this product!", "Not satisfied with the service.", "Amazing
experience.", "Disappointing quality."]
labels = [1, 1, 1, 0]
labels = [Link](labels)
model = Sequential()
[Link](Embedding(input_dim=1000, output_dim=16, input_length=10))
23
lOMoARcPSD|37319915
[Link](SimpleRNN(8, activation='relu'))
[Link](Dense(1, activation='sigmoid'))
[Link](optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
predictions = [Link](X_test)
print("\nSample Predictions:")
for i in range(len(predictions)):
print(f"Actual: {y_test[i]}, Predicted: {round(predictions[i][0])}")
Output:
Epoch 50/50
Sample Predictions:
Actual: 1, Predicted: 1
Result:
Thus the above program for performing Sentiment Analysis using RNN were
executed and the output is verified successfully.
24
lOMoARcPSD|37319915
Ex. No: 10
Date:
Implement an LSTM based Autoencoder in TensorFlow/Keras.
Aim:
To implement an LSTM-based Autoencoder using TensorFlow/Keras.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Load and preprocess sequential data.
3. Define the architecture of the LSTM-based Autoencoder.
4. Compile the model, specifying the loss function and optimizer.
5. Train the Autoencoder using the sequential data.
6. Evaluate the model's performance.
7. Make predictions using the trained Autoencoder.
Program:
import tensorflow as tf
from [Link] import Sequential
from [Link] import LSTM, RepeatVector, TimeDistributed, Dense
import numpy as np
[Link](42)
sequence_data = [Link](100, 10, 1)
model = Sequential()
encoded_data = [Link](sequence_data)
25
lOMoARcPSD|37319915
print("\nSample Predictions:")
for i in range(3):
print(f"Original Sequence:\n{sequence_data[i]}")
print(f"Encoded and Decoded Sequence:\n{encoded_data[i]}")
print("\n")
Output:
Epoch 50/50
Sample Predictions:
Original Sequence:
[[0.37454012]
[0.95071431]
[0.73199394]
[0.59865848]
[0.15601864]
[0.15599452]
[0.05808361]
[0.86617615]
[0.60111501]
[0.70807258]]
[[0.35951287]
[0.48757628]
[0.5377357 ]
[0.548638 ]
[0.54050046]
[0.5242156 ]
[0.5055392 ]
26
lOMoARcPSD|37319915
[0.4873782 ]
[0.47106645]
[0.45708445]]
Original Sequence:
[[0.02058449]
[0.96990985]
[0.83244264]
[0.21233911]
[0.18182497]
[0.18340451]
[0.30424224]
[0.52475643]
[0.43194502]
[0.29122914]]
[[0.26717597]
[0.3793814 ]
[0.43721834]
[0.46050552]
[0.4647041 ]
[0.45918518]
[0.44929692]
[0.43799573]
[0.42685196]
[0.4166411 ]]
Original Sequence:
[[0.61185289]
27
lOMoARcPSD|37319915
[0.13949386]
[0.29214465]
[0.36636184]
[0.45606998]
[0.78517596]
[0.19967378]
[0.51423444]
[0.59241457]
[0.04645041]]
[[0.26825362]
[0.38092735]
[0.43878633]
[0.4619585 ]
[0.46601555]
[0.46036348]
[0.45036083]
[0.4389659 ]
[0.42774758]
[0.41747904]]
Result:
Thus the above program for implementation of LSTM based Autoencoder were
executed and the output is verified successfully.
28
lOMoARcPSD|37319915
Ex. No: 11
Date:
Image generation using GAN Additional Experiments.
Aim:
To experiment with image generation using a Generative Adversarial Network (GAN).
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Define the generator and discriminator models.
3. Create the GAN model by combining the generator and discriminator.
4. Compile the GAN model.
5. Train the GAN model on a dataset.
6. Generate new images using the trained GAN.
Program:
import torch
import [Link] as nn
import [Link] as optim
import torchvision
from torchvision import datasets, transforms as T
train_dataset = datasets.CIFAR10(
root="./data", train=True, download=True, transform=[Link]()
)
dataloader = [Link](train_dataset, batch_size=32,
shuffle=True)
latent_dim = 100
lr = 0.0002
beta1 = 0.5
beta2 = 0.999
num_epochs = 10
class Generator([Link]):
def __init__(self, latent_dim):
super(Generator, self).__init__()
[Link] = [Link](
29
lOMoARcPSD|37319915
class Discriminator([Link]):
def __init__(self):
super(Discriminator, self).__init__()
[Link] = [Link](
nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
[Link](0.2),
[Link](0.25),
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
nn.ZeroPad2d((0, 1, 0, 1)),
nn.BatchNorm2d(64, momentum=0.82),
[Link](0.25),
[Link](0.25),
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(128, momentum=0.82),
[Link](0.2),
[Link](0.25),
nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(256, momentum=0.8),
[Link](0.25),
[Link](0.25),
[Link](),
[Link](256 * 5 * 5, 1),
[Link](),
)
30
lOMoARcPSD|37319915
generator = Generator(latent_dim).to(device)
discriminator = Discriminator().to(device)
adversarial_loss = [Link]()
optimizer_D.zero_grad()
fake_images = generator(z)
d_loss.backward()
optimizer_D.step()
optimizer_G.zero_grad()
gen_images = generator(z)
g_loss.backward()
optimizer_G.step()
if (i + 1) % 100 == 0:
print(
f"Epoch [{epoch+1}/{num_epochs}]\
Batch {i+1}/{len(dataloader)} "
f"Discriminator Loss: {d_loss.item():.4f} "
f"Generator Loss: {g_loss.item():.4f}"
)
if (epoch + 1) % 10 == 0:
31
lOMoARcPSD|37319915
with torch.no_grad():
z = [Link](16, latent_dim, device=device)
generated = generator(z).detach().cpu()
grid = [Link].make_grid(generated, nrow=4,
normalize=True)
[Link]([Link](grid, (1, 2, 0)))
[Link]("off")
[Link]()
Output:
Epoch [10/10] Batch 1500/1563 Discriminator Loss: 0.4170 Generator Loss: 1.1472
Result:
Thus the above program for image generation using GAN addition experiments were
executed and the output is verified successfully.
32
lOMoARcPSD|37319915
Ex. No: 12
Train a Deep learning model to classify a given image using
Date: pre trained model
Aim:
To train a deep learning model to classify a given image using a pre-trained model.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Load and preprocess the dataset.
3. Load a pre-trained model (MobileNetV2) without the top classification layer.
4. Add a new classification layer suitable for the target dataset.
5. Compile the model, specifying the loss function, optimizer, and metrics.
6. Train the model on the target dataset using transfer learning.
7. Evaluate the model's performance.
8. Make predictions using the trained model.
Program:
import tensorflow as tf
from keras import layers, models
from [Link] import MobileNetV2
from [Link] import cifar10
from [Link] import to_categorical
model = [Link]()
[Link](base_model)
[Link](layers.GlobalAveragePooling2D())
[Link]([Link](256, activation='relu'))
[Link]([Link](10, activation='softmax'))
33
lOMoARcPSD|37319915
[Link](optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
Output:
Epoch 5/5
Result:
Thus the above program for training a Deep learning model to classify a given image using pre
trained model were executed and the output is verified successfully.
34
lOMoARcPSD|37319915
Ex. No: 13
Recommendation system from sales data using Deep Learning
Date:
Aim:
To implement a recommendation system using deep learning on sales data.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Prepare the sales data, which typically includes user-item interactions and purchase
history.
3. Build a matrix factorization model for collaborative filtering using deep learning.
4. Compile the model, specifying the appropriate loss function and optimizer.
5. Train the model using the sales data.
6. Use the trained model to make recommendations.
Program:
import tensorflow as tf
from [Link] import Model
from [Link] import Input, Embedding, Dot, Flatten
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
sales_data = [Link]({
'user_id': [1, 1, 2, 2, 3, 3, 4, 4],
'item_id': [101, 102, 101, 103, 102, 104, 101, 104],
'purchase': [1, 1, 1, 1, 1, 1, 1, 1]
})
sales_data['user_index'] = sales_data['user_id'].map(user_mapping)
sales_data['item_index'] = sales_data['item_id'].map(item_mapping)
num_users = len(user_mapping)
num_items = len(item_mapping)
embedding_dim = 10
35
lOMoARcPSD|37319915
[Link](optimizer='adam', loss='mean_squared_error')
[Link]([train_data['user_index'], train_data['item_index']],
train_data['purchase'], epochs=10, batch_size=1)
user_id_to_recommend = 1
items_not_purchased = sales_data.loc[~((sales_data['user_id'] ==
user_id_to_recommend) & (sales_data['purchase'] == 1)), 'item_index'].unique()
recommendation_input = [Link]({'user_index':
[user_mapping[user_id_to_recommend]] * len(items_not_purchased),
'item_index': items_not_purchased})
predictions = [Link]([recommendation_input['user_index'],
recommendation_input['item_index']])
top_recommendations = [Link](5)
top_recommendations['item_id'] = top_recommendations['item_index'].map({idx:
item_id for item_id, idx in item_mapping.items()})
print("\nTop Recommendations:")
print(top_recommendations[['item_id', 'predicted_purchase']])
36
lOMoARcPSD|37319915
Output:
Epoch 500/500
Top Recommendations:
item_id predicted_purchase
0 101 0.968562
2 102 0.958725
1 103 0.933026
3 104 0.929990
Result:
Thus the above program for Recommendation system from sales data using Deep
Learning were executed and the output is verified successfully.
37
lOMoARcPSD|37319915
Ex. No: 14
Implement Object Detection using CNN
Date:
Aim:
To implement object detection using a Convolutional Neural Network (CNN) in
TensorFlow/Keras.
Algorithm:
1. Import the necessary libraries: TensorFlow and Keras.
2. Load and pre-process image and annotation data.
3. Define the architecture of the SSD model.
4. Compile the model, specifying the appropriate loss function and optimizer.
5. Train the SSD model using the image and annotation data.
6. Evaluate the model's performance on a test dataset.
7. Use the trained model for object detection on new images.
Program:
import tensorflow as tf
from keras import layers
from [Link] import Model
from [Link] import Adam
from [Link] import binary_crossentropy
from [Link] import MobileNetV2
import numpy as np
ssd_model.compile(optimizer=Adam(), loss='binary_crossentropy',
metrics=['accuracy'])
38
lOMoARcPSD|37319915
Output:
Epoch 50/50
Result:
Thus the above program for implementation of Object Detection using CNN were executed
and the output is verified successfully.
39
lOMoARcPSD|37319915
Ex. No: 15
Date:
Implement any simple Reinforcement Algorithm for an NLP problem
Aim:
To implement a simple reinforcement algorithmfor an NLP problem.
Algorithm:
1. Define the environment, states, actions, and rewards.
2. Initialize Q-values for state-action pairs.
3. Implement the Q-learning algorithm:
a. Select an action based on the current state and exploration-exploitation
strategy.
b. Execute the action and observe the reward and the next state.
c. Update the Q-value for the selected action based on the observed reward
and the Q-learning formula.
d. Repeat until convergence or a specified number of iterations.
4. Train the chatbot using the Q-learning algorithm.
Program:
import tensorflow as tf
model = Sequential([
Embedding(input_dim=len(vocab), output_dim=5, input_length=1),
LSTM(10, return_sequences=True),
Dense(len(vocab), activation='softmax')
])
40
lOMoARcPSD|37319915
[Link](optimizer=Adam(), loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
[Link](X_train, y_train, epochs=150, verbose=0.2)
Output:
Epoch 150/150
Result:
Thus the above program for implementation of simple Reinforcement Algorithm for an NLP
problem were executed and the output is verified successfully.
41