0% found this document useful (0 votes)
7 views33 pages

CNN and RNN for Image Recognition

The document outlines a series of experiments conducted using neural networks for various applications, including image recognition, age classification, sequential data prediction, and image denoising. Each experiment includes the aim, program code, and output results, demonstrating the implementation of convolutional and recurrent neural networks, as well as multi-layer perceptrons. The experiments utilize TensorFlow and Keras libraries, showcasing practical applications of artificial intelligence in real-world scenarios.

Uploaded by

navya132911
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

CNN and RNN for Image Recognition

The document outlines a series of experiments conducted using neural networks for various applications, including image recognition, age classification, sequential data prediction, and image denoising. Each experiment includes the aim, program code, and output results, demonstrating the implementation of convolutional and recurrent neural networks, as well as multi-layer perceptrons. The experiments utilize TensorFlow and Keras libraries, showcasing practical applications of artificial intelligence in real-world scenarios.

Uploaded by

navya132911
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ROLL NO:22NE1A0568

EXPERIMENT - 1

AIM:Build a Convolution Neural Network for Image Recognition. Go through the modules of
the course mentioned and answer the self-assessment questions given in the link below at the end
of the course.

program

import tensorflow astf


from [Link] import datasets, layers, models
[Link]
(train_images, train_labels), (test_images, test_labels) =
datasets.cifar10.load_data()
train_images, test_images=train_images/255.0, test_images/255.0
class_names= ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog',
'horse', 'ship', 'truck']
[Link](figsize=(10, 10))
foriinrange(25):
[Link](5, 5, i+1)
[Link]([])
[Link]([])
[Link](False)
[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](64, activation='relu'))
[Link]([Link](10))
[Link](optimizer='adam'
loss=[Link](from_logits=True),metrics=['ac
curacy'])
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')

TIRUMALA ENGINEERING COLLEGE Page| 1


ROLL NO:22NE1A0568

test_loss, test_acc=[Link](test_images, test_labels, verbose=2)


print(f"Test accuracy: {test_acc}")
[Link]('cifar10_cnn_model.h5')

OUTPUT

Downloading data from [Link]


[Link]
170498071/170498071━━━━━━━━━━━━━━━━━━━━14s 0us/step

Epoch 1/10
1563/1563━━━━━━━━━━━━━━━━━━━━13s 6ms/step - accuracy: 0.3648
- loss: 1.7232 - val_accuracy: 0.5743 - val_loss: 1.2208
Epoch 2/10
1563/1563━━━━━━━━━━━━━━━━━━━━6s 4ms/step - accuracy: 0.5882
- loss: 1.1565 - val_accuracy: 0.6341 - val_loss: 1.0557
Epoch 3/10
1563/1563━━━━━━━━━━━━━━━━━━━━6s 4ms/step - accuracy: 0.6514
- loss: 0.9898 - val_accuracy: 0.6540 - val_loss: 0.9883
Epoch 4/10
1563/1563━━━━━━━━━━━━━━━━━━━━7s 4ms/step - accuracy: 0.6996
- loss: 0.8680 - val_accuracy: 0.6887 - val_loss: 0.8978
Epoch 5/10
1563/1563━━━━━━━━━━━━━━━━━━━━6s 4ms/step - accuracy: 0.7212
- loss: 0.8004 - val_accuracy: 0.6914 - val_loss: 0.8956
Epoch 6/10
1563/1563━━━━━━━━━━━━━━━━━━━━8s 5ms/step - accuracy: 0.7456
- loss: 0.7277 - val_accuracy: 0.6622 - val_loss: 0.9708
Epoch 7/10
1563/1563━━━━━━━━━━━━━━━━━━━━9s 4ms/step - accuracy: 0.7578
- loss: 0.6960 - val_accuracy: 0.7057 - val_loss: 0.8554
Epoch 8/10
1563/1563━━━━━━━━━━━━━━━━━━━━6s 4ms/step - accuracy: 0.7781
- loss: 0.6353 - val_accuracy: 0.7212 - val_loss: 0.8352
Epoch 9/10
1563/1563━━━━━━━━━━━━━━━━━━━━6s 4ms/step - accuracy: 0.7885
- loss: 0.6022 - val_accuracy: 0.7098 - val_loss: 0.8723
Epoch 10/10
1563/1563━━━━━━━━━━━━━━━━━━━━10s 4ms/step - accuracy: 0.8027
- loss: 0.5620 - val_accuracy: 0.7116 - val_loss: 0.890

TIRUMALA ENGINEERING COLLEGE Page| 2


ROLL NO:22NE1A0568

TIRUMALA ENGINEERING COLLEGE Page| 3


ROLL NO:22NE1A0568

EXPERIMENT-2

AIM :Module name : Understanding and Using ANN : Identifying age group of an actor
Exercise : Design Artificial Neural Networks for Identifying and Classifying an actor using
Kaggle Dataset.

Program

!pip install deepface


from deepface import DeepFace from
[Link] import files import
[Link] as plt from PIL
import Image
import numpy as np uploaded = [Link]()
imp_path=list([Link]())[0]
img=[Link](imp_path)
[Link](img)
[Link]('off') [Link]("uploaded
image") [Link]()
predicted_age = [Link](imp_path, actions = ['age'])
print(f"predicted age:{predicted_age[0]['age']}")
defget_age_group(age):
if age <=12:
return"child" elif
age<=19:
return"teenager"
elif age<=35:
return"younger"
else:
return"senior" age_group=get_age_group(predicted_age[0]['age'])
print(f"age group:{age_group}")

TIRUMALA ENGINEERING COLLEGE Page| 4


ROLL NO:22NE1A0568

OUTPUT :-

[Link](87kB)
━━━━━━━━━━━━━━━━━━━━━━━━87.2/87.2 kB4.9 MB/s eta 0:00:00
25-08-05 04:45:45 - Directory /root/.deepface has been created
25-08-05 04:45:45 - Directory /root/.deepface/weights has been created

Downloading...
From:
[Link]
weights.h5
To: /root/.deepface/weights/age_model_weights.h5
25-08-05 04:46:16 - ◻ age_model_weights.h5 will be downloaded from
[Link]
weights.h5 to /root/.deepface/weights/age_model_weights.h5...
100%|██████████| 539M/539M [00:01<00:00, 303MB/s]
predicted age:26
age group:younger

TIRUMALA ENGINEERING COLLEGE Page| 5


ROLL NO:22NE1A0568

EXPERIMENT-3

AIM :Module name : Understanding and Using CNN : Image recognition


Exercise: Design a CNN for Image Recognition which includes hyperparameter
tuning

Program

import tensorflow as tf
from [Link] import cifar10
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten, Dense
import [Link] as plt
import numpy as np
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train/255.0, x_test/255.0
y_train_cat = [Link].to_categorical(y_train,10)
y_test_cat = [Link].to_categorical(y_test,10)
model = Sequential([
Conv2D(32,(3,3),activation='relu',input_shape=(32,32,3)),
MaxPooling2D(2,2),
Conv2D(64,(3,3),activation='relu'),
MaxPooling2D(2,2),
Flatten(),
Dense(128,activation='relu'),
Dense(10,activation='softmax')
])
[Link](optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
[Link](x_train, y_train_cat, epochs=3, validation_split=0.2)
preds = [Link](x_test)
pred_labels = [Link](preds, axis=1)
classes =
['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','
truck']
[Link](figsize=(12,6))
shown_classes = set()
i = 0
whilelen(shown_classes) <10and i <len(x_test):
true_class = int(y_test[i])
if true_class notin shown_classes:
[Link](2,5,len(shown_classes)+1)
[Link](x_test[i])
[Link](f"Pred: {classes[pred_labels[i]]}\nTrue:
{classes[true_class]}")
[Link]('off')

TIRUMALA ENGINEERING COLLEGE Page| 6


ROLL NO:22NE1A0568

shown_classes.add(true_class)
i += 1
[Link]()

OUTPUT

Epoch 1/3
1250/1250━━━━━━━━━━━━━━━━━━━━9s 6ms/step - accuracy: 0.3892 -
loss: 1.6867 - val_accuracy: 0.5680 - val_loss: 1.2325
Epoch 2/3
1250/1250━━━━━━━━━━━━━━━━━━━━5s 4ms/step - accuracy: 0.5911 -
loss: 1.1568 - val_accuracy: 0.6154 - val_loss: 1.1027
Epoch 3/3
1250/1250━━━━━━━━━━━━━━━━━━━━6s 4ms/step - accuracy: 0.6498 -
loss: 0.9981 - val_accuracy: 0.6452 - val_loss: 1.0122
313/313━━━━━━━━━━━━━━━━━━━━1s 2ms/step

TIRUMALA ENGINEERING COLLEGE Page| 7


ROLL NO:22NE1A0568

EXPERIMENT-4

AIM : Module name : Predicting Sequential Data Exercise: Implement a


Recurrence Neural Network for Predicting Sequential Data.

Program

import numpy as np
import tensorflow as tf
from [Link] import Sequential
from [Link] import LSTM, Dense
import [Link] as plt
defgenerate_sine_wave(length, frequency, amplitude, noise_level=0.1):
x = [Link](0, length)
sine_wave = amplitude * [Link](2 * [Link] * frequency * x / length)
noise = [Link](0, noise_level, length)
return sine_wave + noise
data_length = 100
time_series_data = generate_sine_wave(data_length, frequency=5,
amplitude=1)
defcreate_sequences(data, n_steps):
X, y = [], []
for i inrange(len(data) - n_steps):
seq = data[i:i + n_steps]
target = data[i + n_steps]
[Link](seq)
[Link](target)
return [Link](X), [Link](y)
n_steps = 10
X, y = create_sequences(time_series_data, n_steps)
X = [Link](([Link][0], [Link][1], 1))
print(f"Shape of X (input sequences): {[Link]}")
print(f"Shape of y (target values): {[Link]}\n")
model = Sequential()
[Link](LSTM(50, activation='relu', input_shape=(n_steps, 1)))
[Link](Dense(1))
[Link](optimizer='adam', loss='mean_squared_error')
[Link]()
history = [Link](X, y, epochs=200, verbose=0, validation_split=0.2)
print("\nModel training complete.")
train_predictions = [Link](X, verbose=0).flatten()
last_sequence = time_series_data[-n_steps:]
last_sequence = last_sequence.reshape((1, n_steps, 1))
future_predictions = []
current_input = last_sequence

TIRUMALA ENGINEERING COLLEGE Page| 8


ROLL NO:22NE1A0568

for _ inrange(20):
next_value = [Link](current_input, verbose=0)[0]
future_predictions.append(next_value[0])
current_input = [Link](current_input[:, 1:, :], [[next_value]],
axis=1)
[Link](figsize=(14, 8))
[Link]([Link](data_length), time_series_data, label='Original Data',
color='blue', linewidth=2)
[Link]([Link](n_steps, data_length), train_predictions, label='In-
Sample Predictions', color='orange', linestyle='--', linewidth=2)
prediction_range = [Link](data_length, data_length +
len(future_predictions))
[Link](prediction_range, future_predictions, label='Future Predictions',
color='red', linestyle='--', linewidth=2)
[Link](x=data_length - 1, color='gray', linestyle='--', linewidth=1)
[Link]("Sequential Data Prediction using an LSTM Network")
[Link]("Time Step")
[Link]("Value")
[Link]()
[Link](True)
[Link]()

TIRUMALA ENGINEERING COLLEGE Page| 9


ROLL NO:22NE1A0568

OUTPUT
Shape of X (input sequences): (90, 10, 1)
Shape of y (target values): (90,)

Total params: 10,451 (40.82 KB)


Trainable params: 10,451 (40.82 KB)
Non-trainable params: 0 (0.00 B)

Model training complete.

TIRUMALA ENGINEERING COLLEGE Page| 10


ROLL NO:22NE1A0568

EXPERIMENT-5

AIM :Module Name: Removing noise from the images Exercise: Implement
Multi-Layer Perceptron algorithm for Image denoising hyperparameter tuning

Program

import numpy as np
import [Link] as plt
from [Link] import Sequential
from [Link] import Dense
from [Link] import mnist
from [Link] import Adam
from [Link] import EarlyStopping
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train_flat = x_train.reshape((len(x_train), [Link](x_train.shape[1:])))
x_test_flat = x_test.reshape((len(x_test), [Link](x_test.shape[1:])))
noise_factor = 0.5
x_train_noisy = x_train_flat + noise_factor * [Link](loc=0.0,
scale=1.0, size=x_train_flat.shape)
x_test_noisy = x_test_flat + noise_factor * [Link](loc=0.0,
scale=1.0, size=x_test_flat.shape)
x_train_noisy = [Link](x_train_noisy, 0., 1.)
x_test_noisy = [Link](x_test_noisy, 0., 1.)
input_dim = x_train_flat.shape[1]
model = Sequential()
[Link](Dense(256, activation='relu', input_shape=(input_dim,)))
[Link](Dense(128, activation='relu'))
[Link](Dense(256, activation='relu'))
[Link](Dense(input_dim, activation='sigmoid'))
[Link](optimizer=Adam(learning_rate=0.001),
loss='mean_squared_error')
[Link]()
early_stopping = EarlyStopping(monitor='val_loss', patience=5,
restore_best_weights=True)
history = [Link](
x_train_noisy,
x_train_flat,
epochs=10,
batch_size=256,
shuffle=True,
validation_split=0.2,
callbacks=[early_stopping]
)

TIRUMALA ENGINEERING COLLEGE Page| 11


ROLL NO:22NE1A0568

[Link](figsize=(10, 6))
[Link]([Link]['loss'], label='Training Loss')
[Link]([Link]['val_loss'], label='Validation Loss')
[Link]('Model Loss over Epochs')
[Link]('Epochs')
[Link]('Loss')
[Link]()
[Link]()
denoised_images = [Link](x_test_noisy)
n = 10
[Link](figsize=(20, 6))
for i inrange(n):
ax = [Link](3, n, i + 1)
[Link](x_test[i].reshape(28, 28))
[Link]('Original')
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = [Link](3, n, i + 1 + n)
[Link](x_test_noisy[i].reshape(28, 28))
[Link]('Noisy')
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = [Link](3, n, i + 1 + 2*n)
[Link](denoised_images[i].reshape(28, 28))
[Link]('Denoised')
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
[Link]()

TIRUMALA ENGINEERING COLLEGE Page| 12


ROLL NO:22NE1A0568

OUTPUT

Downloading data from [Link]


datasets/[Link]

11490434/11490434━━━━━━━━━━━━━━━━━━━━ 0s 0us/step

Total params: 468,368 (1.79 MB)


Trainable params: 468,368 (1.79 MB)
Non-trainable params: 0 (0.00 B)

Epoch 1/10
188/188━━━━━━━━━━━━━━━━━━━━7s 28ms/step - loss: 0.0871 -
val_loss: 0.0370
Epoch 2/10
188/188━━━━━━━━━━━━━━━━━━━━4s 21ms/step - loss: 0.0332 -
val_loss: 0.0268
Epoch 3/10
188/188━━━━━━━━━━━━━━━━━━━━5s 25ms/step - loss: 0.0254 -
val_loss: 0.0232
Epoch 4/10
188/188━━━━━━━━━━━━━━━━━━━━4s 21ms/step - loss: 0.0222 -
val_loss: 0.0212
Epoch 5/10
188/188━━━━━━━━━━━━━━━━━━━━5s 21ms/step - loss: 0.0203 -
val_loss: 0.0199
Epoch 6/10
188/188━━━━━━━━━━━━━━━━━━━━5s 21ms/step - loss: 0.0190 -
val_loss: 0.0191
Epoch 7/10
188/188━━━━━━━━━━━━━━━━━━━━4s 21ms/step - loss: 0.0182 -
val_loss: 0.0183
Epoch 8/10
188/188━━━━━━━━━━━━━━━━━━━━4s 23ms/step - loss: 0.0174 -
val_loss: 0.0177
Epoch 9/10

TIRUMALA ENGINEERING COLLEGE Page| 13


ROLL NO:22NE1A0568

188/188━━━━━━━━━━━━━━━━━━━━5s 21ms/step - loss: 0.0168 -


val_loss: 0.0172
Epoch 10/10
188/188━━━━━━━━━━━━━━━━━━━━4s 21ms/step - loss: 0.0162 -
val_loss: 0.0168

TIRUMALA ENGINEERING COLLEGE Page| 14


ROLL NO:22NE1A0568

EXPERIMENT-6
AIM :Module Name: Advanced Deep Learning Architectures Exercise: Implement Object Dection
Using YOLO

Program

!pip install ultralytics -q


from ultralytics import YOLO
# Load a model
model = YOLO("[Link]") # load a pretrained model (recommended for
training)
# Predict with the model
results = model("[Link] # predict on
an image
# Show results
results[0].show()

OUTPUT

Downloading [Link] to '[Link]':


100%|██████████ 49.2k/49.2k [00:00<00:00, 4.78MB/s]
image 1/1 /content/[Link]: 384x640 2 persons, 1 tie, 150.7ms
Speed: 2.7ms preprocess, 150.7ms inference, 1.1ms postprocess per image at
shape (1, 3, 384, 640)

TIRUMALA ENGINEERING COLLEGE Page| 15


ROLL NO :- 22NE1A0568

EXPERIMENT – 7

AIM: Module Name: Optimization of Training in Deep Learning ,Exercise Name: Design a Deep
learning Network for Robust Bi-Tempered Logistic Loss.\

Program

import torch
import [Link] as nn
import [Link] as F
def bi_tempered_logistic_loss(logits, labels, t1=0.8, t2=1.2,
label_smoothing=0.0):
if label_smoothing > 0.0:
smooth_labels = (1.0 - label_smoothing) * labels + label_smoothing
/ [Link](1)
else:
smooth_labels = labels
exp_t1 = 1.0 / (t1 - 1.0)
tempered_logits = [Link]([Link]([Link](logits, dim=-1),
min=1e-9), exp_t1)
exp_t2 = 1.0 / (t2 - 1.0)
tempered_log_probs = [Link]([Link](F.log_softmax(logits, dim=-
1), min=1e-9), exp_t2)
loss = tempered_log_probs * smooth_labels
loss = -[Link](loss, dim=-1)
return [Link](loss)
import torch
import [Link] as nn
class SimpleNet([Link]):
def init (self, input_size, num_classes):
super(SimpleNet, self). init ()
self.fc1 = [Link](input_size, 128)
[Link] = [Link]()
self.fc2 = [Link](128, num_classes)
def forward(self, x):
x = self.fc1(x)
x = [Link](x)
x = self.fc2(x)
return x
input_size = 784
num_classes = 10
model = SimpleNet(input_size, num_classes)
batch_size = 64
dummy_input = [Link](batch_size, input_size)

TIRUMALA ENGNEERING COLLAGE Page| 16


ROLL NO :- 22NE1A0568

dummy_labels = [Link](0, num_classes, (batch_size,))


dummy_labels_one_hot = F.one_hot(dummy_labels,
num_classes=num_classes).float()
outputs = model(dummy_input)
loss = bi_tempered_logistic_loss(outputs, dummy_labels_one_hot)
print(f"Example Bi-Tempered Logistic Loss: {[Link]()}")

OUTPUT

Example Bi-Tempered Logistic Loss: -1.401298464324817e-45

TIRUMALA ENGNEERING COLLAGE Page| 17


ROLL NO :- 22NE1A0568

EXPERIMENT – 8

AIM :- Module name: Advanced CNN ,Exercise: Build AlexNet using Advanced CNN.

Program

import tensorflow as tf
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten, Dense,
Dropout, BatchNormalization, Input
def build_alexnet(input_shape=(224, 224, 3), num_classes=1000):
model = Sequential([
Input(shape=input_shape),
Conv2D(96, (11, 11), strides=(4, 4), activation='relu'),
BatchNormalization(),
MaxPooling2D((3, 3), strides=(2, 2)),
Conv2D(256, (5, 5), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D((3, 3), strides=(2, 2)),
Conv2D(384, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(384, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
Conv2D(256, (3, 3), padding='same', activation='relu'),
BatchNormalization(),
MaxPooling2D((3, 3), strides=(2, 2)),
Flatten(),
Dense(4096, activation='relu'),
Dropout(0.5),
Dense(4096, activation='relu'),
Dropout(0.5),
Dense(num_classes, activation='softmax')
])
return model
alexnet_model = build_alexnet()
alexnet_model.summary()

TIRUMALA ENGNEERING COLLAGE Page| 18


ROLL NO :- 22NE1A0568

OUTPUT

TIRUMALA ENGNEERING COLLAGE Page| 19


ROLL NO :- 22NE1A0568

EXPERIMENT – 9

AIM :- Module name: Autoencoders Advanced ,Exercise: Demonstration of Application of


Autoencoders.

Program

%pip install tensorflow keras


import tensorflow as tf
(x_train, _), (x_test, _) = [Link].fashion_mnist.load_data()
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape((len(x_train), 28 * 28))
x_test = x_test.reshape((len(x_test), 28 * 28))
print(x_train.shape)
print(x_test.shape)
from [Link] import Input, Dense
from [Link] import Model
input_dim = 784
latent_dim = 32
input_layer = Input(shape=(input_dim,))
encoder = Dense(128, activation='relu')(input_layer)
encoder = Dense(64, activation='relu')(encoder)
latent_representation = Dense(latent_dim, activation='relu')(encoder)
decoder = Dense(64, activation='relu')(latent_representation)
decoder = Dense(128, activation='relu')(decoder)
output_layer = Dense(input_dim, activation='sigmoid')(decoder)
autoencoder = Model(inputs=input_layer, outputs=output_layer)
[Link]()
[Link](optimizer='adam', loss='binary_crossentropy')
history = [Link](x_train, x_train,
epochs=3,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
loss = [Link](x_test, x_test)
print(f"Test loss: {loss}")
encoder_model = Model(inputs=[Link],
outputs=latent_representation)
encoded_data = encoder_model.predict(x_test)
decoded_data = [Link](x_test)
print("Shape of encoded data:", encoded_data.shape)
print("Shape of decoded data:", decoded_data.shape)
import numpy as np
noise_factor = 0.5

TIRUMALA ENGNEERING COLLAGE Page| 20


ROLL NO :- 22NE1A0568

x_test_noisy = x_test + noise_factor * [Link](loc=0.0,


scale=1.0, size=x_test.shape)
x_test_noisy = [Link](x_test_noisy, 0., 1.)
denoised_data = [Link](x_test_noisy)
print("Shape of denoised data:", denoised_data.shape)
import [Link] as plt
n = 10
[Link](figsize=(20, 6)) for i in range(n):
ax = [Link](4, n, i + 1)
[Link](x_test[i].reshape(28, 28))
[Link]("Original")
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = [Link](4, n, i + 1 + n)
[Link](decoded_data[i].reshape(28, 28))
[Link]("Decoded")
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = [Link](4, n, i + 1 + 2*n)
[Link](x_test_noisy[i].reshape(28, 28))
[Link]("Noisy")
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = [Link](4, n, i + 1 + 3*n)
[Link](denoised_data[i].reshape(28, 28))
[Link]("Denoised")
[Link]()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.tight_layout()
[Link]()

TIRUMALA ENGNEERING COLLAGE Page| 21


ROLL NO :- 22NE1A0568

OUT PUT

Downloading data from [Link]


datasets/[Link]
29515/29515 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
Downloading data from [Link]
datasets/[Link]
26421880/26421880 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
Downloading data from [Link]
datasets/[Link]
5148/5148 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
Downloading data from [Link]
datasets/[Link]
4422102/4422102 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
(60000, 784)
(10000, 784)

Epoch 1/3
235/235 ━━━━━━━━━━━━━━━━━━━━ 6s 18ms/step - loss: 0.4617 -
val_loss: 0.3180
Epoch 2/3
235/235 ━━━━━━━━━━━━━━━━━━━━ 5s 20ms/step - loss: 0.3129 -
val_loss: 0.3072
Epoch 3/3
235/235 ━━━━━━━━━━━━━━━━━━━━ 4s 18ms/step - loss: 0.3036 -
val_loss: 0.3010
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 3ms/step - loss: 0.3008

TIRUMALA ENGNEERING COLLAGE Page| 22


ROLL NO :- 22NE1A0568

Test loss: 0.3010242283344269

313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 1ms/step


313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step
Shape of encoded data: (10000, 32)
Shape of decoded data: (10000, 784)

313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step


Shape of denoised data: (10000, 784)

TIRUMALA ENGNEERING COLLAGE Page| 23


ROLL NO :- 22NE1A0568

EXPERIMENT – 10

AIM:- Module name: Advanced GANs , Exercise:Demonstration of GAN.

Program

import tensorflow as tf
from [Link] import layers
import numpy as np
import [Link] as plt
(X_train, _), (_, _) = [Link].load_data()
X_train = (X_train.astype(np.float32) - 127.5) / 127.5
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
BUFFER_SIZE = 60000
BATCH_SIZE = 256
train_dataset =
[Link].from_tensor_slices(X_train).shuffle(BUFFER_SIZE).batch(BAT
CH_SIZE)
def make_generator_model():
model = [Link]([
[Link](7*7*256, use_bias=False, input_shape=(100,)),
[Link](),
[Link](),
[Link]((7, 7, 256)),
layers.Conv2DTranspose(128, (5, 5), strides=(1, 1),
padding='same', use_bias=False),
[Link](),
[Link](),
layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same',
use_bias=False),
[Link](),
[Link](),
layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same',
use_bias=False, activation='tanh')
])
return model
def make_discriminator_model():
model = [Link]([
layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]),
[Link](),
[Link](0.3),
layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'),
[Link](),
[Link](0.3),
[Link](),

TIRUMALA ENGNEERING COLLAGE Page| 24


ROLL NO :- 22NE1A0568

[Link](1)
])
return model
cross_entropy = [Link](from_logits=True)
def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
return real_loss + fake_loss
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
generator_optimizer = [Link](1e-4)
discriminator_optimizer = [Link](1e-4)
@[Link]
def train_step(images, generator, discriminator):
noise = [Link]([BATCH_SIZE, 100])
with [Link]() as gen_tape, [Link]() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output)
gradients_of_generator = gen_tape.gradient(gen_loss,
generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss,
discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator,
generator.trainable_variables))

discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,
discriminator.trainable_variables))
def generate_and_save_images(model, epoch, test_input):
predictions = model(test_input, training=False)
predictions = 0.5 * predictions + 0.5
fig = [Link](figsize=(4, 4))
for i in range(16): # Show 16 images
[Link](4, 4, i + 1)
[Link](predictions[i, :, :, 0], cmap='gray')
[Link]('off')
[Link](f'Generated Images - Epoch {epoch}')
[Link]()
def train(dataset, epochs):
seed = [Link]([16, 100])
generator = make_generator_model()
discriminator = make_discriminator_model()
for epoch in range(epochs):

TIRUMALA ENGNEERING COLLAGE Page| 25


ROLL NO :- 22NE1A0568

for image_batch in dataset:


train_step(image_batch, generator, discriminator)
if (epoch + 1) % 5 == 0:
print(f'Epoch {epoch + 1} completed.')
generate_and_save_images(generator, epoch + 1, seed)
if name == ' main ':
EPOCHS = 10
print("Starting GAN training on MNIST...")
train(train_dataset, EPOCHS)

OUTPUT

TIRUMALA ENGNEERING COLLAGE Page| 26


ROLL NO :- 22NE1A0568

EXPERIMENT – 11

AIM: - Module name : Capstone project , Exercise : Complete the requirements given in
capstone project ,Description: In this capstone, learners will apply their deep learning knowledge
and expertise to a real world challenge.

Program

import tensorflow as tf
from [Link] import layers
from [Link] import imdb
from [Link] import pad_sequences
from [Link] import Sequential
from [Link] import EarlyStopping
import numpy as np
import [Link] as plt
from [Link] import classification_report, confusion_matrix
import seaborn as sns
print("Loading IMDb dataset...")
max_features = 10000
maxlen = 200
(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)
print(f"Data: Train {x_train.shape}, Test {x_test.shape}")
model = Sequential([
[Link](max_features, 128, input_length=maxlen),
[Link](64, dropout=0.2, recurrent_dropout=0.2),
[Link](1, activation='sigmoid')
])
[Link](optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
EPOCHS = 3
BATCH_SIZE = 32
early_stop = EarlyStopping(monitor='val_loss', patience=2,
restore_best_weights=True)
history = [Link](x_train, y_train, epochs=EPOCHS,
batch_size=BATCH_SIZE,
validation_split=0.2, callbacks=[early_stop],
verbose=1)
test_loss, test_acc = [Link](x_test, y_test, verbose=0)
print(f"Test Accuracy: {test_acc:.4f}")
y_pred = ([Link](x_test) > 0.5).astype(int)
print("\nClassification Report:")

TIRUMALA ENGNEERING COLLAGE Page| 27


ROLL NO :- 22NE1A0568

print(classification_report(y_test, y_pred, target_names=['Negative',


'Positive']))
cm = confusion_matrix(y_test, y_pred)
[Link](figsize=(6, 4))
[Link](cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['Negative', 'Positive'], yticklabels=['Negative',
'Positive'])
[Link]('Confusion Matrix')
[Link]('True')
[Link]('Predicted')
[Link]()
fig, (ax1, ax2) = [Link](1, 2, figsize=(10, 4))
[Link]([Link]['accuracy'], label='Train Acc')
[Link]([Link]['val_accuracy'], label='Val Acc')
ax1.set_title('Accuracy')
[Link]()
[Link]([Link]['loss'], label='Train Loss')
[Link]([Link]['val_loss'], label='Val Loss')
ax2.set_title('Loss')
[Link]()
plt.tight_layout()
[Link]()
sample_reviews = [
"This product is amazing and works perfectly!",
"Terrible quality, broke after one use.",
"Okay, but could be better for the price."
]
word_index = imdb.get_word_index()
def predict_sentiment(texts):
sequences = []
for text in texts:
seq = [word_index.get(w, 0) for w in [Link]().split() if w in
word_index]
seq = seq[:maxlen]
[Link](seq)
padded = pad_sequences(sequences, maxlen=maxlen)
preds = [Link](padded)
for text, pred in zip(texts, preds):
sent = 'Positive' if pred[0] > 0.5 else 'Negative'
conf = pred[0] if pred[0] > 0.5 else 1 - pred[0]
print(f"'{text}' → {sent} (Conf: {conf:.2f})")
print("\nSample Predictions:")
predict_sentiment(sample_reviews)
[Link]('simple_sentiment_model.h5')
print("Model saved as 'simple_sentiment_model.h5'")

TIRUMALA ENGNEERING COLLAGE Page| 28


ROLL NO :- 22NE1A0568

OUTPUT
Loading IMDb dataset...
Downloading data from [Link]
datasets/[Link]
17464789/17464789 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
Data: Train (25000, 200), Test (25000, 200)
/usr/local/lib/python3.12/dist-
packages/keras/src/layers/core/[Link]: UserWarning: Argument
`input_length` is deprecated. Just remove it.
[Link](

Epoch 1/5
625/625 ━━━━━━━━━━━━━━━━━━━━ 255s 391ms/step - accuracy:
0.7119 - loss: 0.5576 - val_accuracy: 0.8314 - val_loss: 0.3894
Epoch 2/5
625/625 ━━━━━━━━━━━━━━━━━━━━ 238s 381ms/step - accuracy:
0.8416 - loss: 0.3635 - val_accuracy: 0.8422 - val_loss: 0.3764
Epoch 3/5
625/625 ━━━━━━━━━━━━━━━━━━━━ 238s 380ms/step - accuracy:
0.8897 - loss: 0.2795 - val_accuracy: 0.8236 - val_loss: 0.4540
Epoch 4/5
625/625 ━━━━━━━━━━━━━━━━━━━━ 236s 378ms/step - accuracy:
0.9068 - loss: 0.2376 - val_accuracy: 0.8546 - val_loss: 0.3615
Epoch 5/5
625/625 ━━━━━━━━━━━━━━━━━━━━ 239s 383ms/step - accuracy:
0.9231 - loss: 0.2038 - val_accuracy: 0.8316 - val_loss: 0.3995

Test Accuracy: 0.8483


782/782 ━━━━━━━━━━━━━━━━━━━━ 88s 112ms/step

Classification Report:

precision recall f1-score support

Negative 0.84 0.87 0.85 12500


Positive 0.86 0.83 0.85 12500

accuracy 0.85 25000


macro avg 0.85 0.85 0.85 25000
weighted avg 0.85 0.85 0.85 25000

TIRUMALA ENGNEERING COLLAGE Page| 29


ROLL NO :- 22NE1A0568

Downloading data from [Link]


datasets/imdb_word_index.json
1641221/1641221 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step

Sample Predictions:
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 220ms/step
WARNING:absl:You are saving your model as an HDF5 file via `[Link]()` or
`[Link].save_model(model)`. This file format is considered legacy. We
recommend using instead the native Keras format, e.g.
`[Link]('my_model.keras')` or `[Link].save_model(model,
'my_model.keras')`.
'This product is amazing and works perfectly!' → Positive (Conf: 0.69)
'Terrible quality, broke after one use.' → Positive (Conf: 0.78)
'Okay, but could be better for the price.' → Positive (Conf: 0.61)
Model saved as 'simple_sentiment_model.h5'

TIRUMALA ENGNEERING COLLAGE Page| 30


ROLL NO :- 22NE1A0568

EXPERIMENT – 12

AIM:- Module name : Capstone project , Exercise : Complete the requirements given in capstone
project

Program

import tensorflow as tf
from tensorflow import keras
from [Link] import layers
import numpy as np
import [Link] as plt
(x_train, y_train), (x_test, y_test) = [Link].load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
model = [Link]([
layers.Conv2D(32, kernel_size=(3, 3), activation='relu',
input_shape=(28, 28, 1)),
layers.MaxPooling2D(pool_size=(2, 2)),
[Link](),
[Link](128, activation='relu'),
[Link](10, activation='softmax')])
[Link](optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = [Link](x_train, y_train, epochs=5, validation_split=0.2)
test_loss, test_acc = [Link](x_test, y_test)
print(f"\nTest accuracy: {test_acc * 100:.2f}%")
predictions = [Link](x_test)
def plot_sample(index):
[Link](x_test[index].reshape(28, 28), cmap='gray')
[Link](f"Predicted: {[Link](predictions[index])}, Actual:
{y_test[index]}")
[Link]()
plot_sample(0)
[Link]('capstone_mnist_model.h5')
print("Model saved as 'capstone_mnist_model.h5'")
[Link]([Link]['accuracy'], label='Training Accuracy')
[Link]([Link]['val_accuracy'], label='Validation Accuracy')
[Link]('Epochs')
[Link]('Accuracy')
[Link]()
[Link]()

TIRUMALA ENGNEERING COLLAGE Page| 31


ROLL NO :- 22NE1A0568

OUTPUT

Downloading data from [Link]


datasets/[Link]
11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step

/usr/local/lib/python3.12/dist-
packages/keras/src/layers/convolutional/base_conv.py:113: UserWarning: Do not
pass an `input_shape`/`input_dim` argument to a layer. When using Sequential
models, prefer using an `Input(shape)` object as the first layer in the model
[Link](). init (activity_regularizer=activity_regularizer,
**kwargs)

Epoch 1/5
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 9s 4ms/step - accuracy: 0.8977 -
loss: 0.3332 - val_accuracy: 0.9794 - val_loss: 0.0707
Epoch 2/5
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.9829 -
loss: 0.0538 - val_accuracy: 0.9801 - val_loss: 0.0638
Epoch 3/5
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.9893 -
loss: 0.0343 - val_accuracy: 0.9822 - val_loss: 0.0590
Epoch 4/5
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.9931 -
loss: 0.0222 - val_accuracy: 0.9841 - val_loss: 0.0500
Epoch 5/5
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 4s 3ms/step - accuracy: 0.9962 -
loss: 0.0125 - val_accuracy: 0.9836 - val_loss: 0.0584

313/313 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9818 -


loss: 0.0685

Test accuracy: 98.50%


313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step

TIRUMALA ENGNEERING COLLAGE Page| 32


ROLL NO :- 22NE1A0568

WARNING:absl:You are saving your model as an HDF5 file via `[Link]()` or


`[Link].save_model(model)`. This file format is considered legacy. We
recommend using instead the native Keras format, e.g.
`[Link]('my_model.keras')` or `[Link].save_model(model,
'my_model.keras')`.
Model saved as 'capstone_mnist_model.h5'

TIRUMALA ENGNEERING COLLAGE Page| 33

You might also like