DLV Lab Manual Print
DLV Lab Manual Print
NAME: __________________________________________
REG NO: __________________________________________
YEAR: __________________________________________
SEMESTER: __________________________________________
LIST OF EXPERIMENTS
Ex. Date Name of the Experiment Page Staff
No. No Sign
1 Implementation of basic image
processing operations including
Feature Representation and Feature
Extraction
2 Implementation of simple neural
network
3 Study of Pretrained Deep Neural
Network Model for Images
Output:
Result:
It focuses on performing basic image processing tasks such as edge detection (using the Canny
edge detector) and feature extraction (using Harris Corner detection), followed by displaying the
results with highlighted features in the images.
EX.NO:02 2. Implementation of simple neural network
Date:
Program :
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
import tensorflow as tf
# Input layer and first hidden layer with 10 neurons and ReLU activation
model.add(Dense(10, input_dim=4, activation='relu'))
# Output layer with 3 neurons (one for each class) and softmax activation
model.add(Dense(3, activation='softmax'))
Output :
Epoch 1/100
24/24 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.3858 - loss: 1.2491
Epoch 2/100
24/24 ━━━━━━━━━━━━━━━━━━━━ 0s 4ms/step - accuracy: 0.7343 - loss: 0.8896
Epoch 3/100
24/24 ━━━━━━━━━━━━━━━━━━━━ 0s 5ms/step - accuracy: 0.6574 - loss: 0.8656
Epoch 4/100
.
.
.
.
.
.
.
24/2━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.9697 - loss: 0.0752
Epoch 100/100
24/24 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.9831 - loss: 0.0714
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 279ms/step - accuracy: 0.9667 - loss: 0.0997
Test Loss: 0.0997
Test Accuracy: 0.9667
Result:
1. Training Progress: During the training, you will see the loss and accuracy for each
epoch. As training progresses, the model improves, and the loss decreases while
accuracy increases.
2. Test Accuracy: After training, the model's accuracy on the test set is displayed. The
higher the accuracy, the better the model has learned to classify the data. For this
example, we may see an accuracy of around 96.67% on the test set, which indicates
that the model is performing well.
3. Loss: The test loss is also reported, showing how far off the model's predictions were
from the actual labels on the test data. A lower test loss indicates a better-performing
model.
EX.NO:03 3. Study of Pretrained Deep Neural Network
Model for Images
Date:
Program :
Output :
Date:
Program :
# Import libraries
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
Output :
Epoch 1/10
Epoch 2/10
….
..
Epoch 10/10
Date:
Program:
# Import libraries
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
plt.show()
Inference:
Output:
Result:
After running the program, the output will show:
Example:
Date:
Program:
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import cv2
import os
# Step 4: Training
# cnn_model.fit(video_sequences, labels, epochs=10) # Example training
# Step 5: Prediction
predictions = cnn_model.predict(video_sequences)
print("Predictions:", predictions)
Output:
1. Predictions:
The output is a classification probability for the video sequence, e.g.,
2. Predictions: [[0.85]]
3. Visual Output:
Not directly provided in this code but can be added to visualize feature extraction
or prediction results.
Result:
The RNN model successfully processed video sequences and predicted the
classification result for the input video. The performance of the model depends on the
quality of the training dataset and the temporal resolution of the video clips.
EX.NO:07 7. Implementation of Deep Generative model for
Image editing
Date:
Program
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import transforms, datasets, utils
from torchvision.models import vgg19
import os
# Define Generator
class Generator(nn.Module):
def __init__(self, in_channels, out_channels):
super(Generator, self).__init__()
self.encoder = nn.Sequential(
self._conv_block(in_channels, 64, 4, 2, 1),
self._conv_block(64, 128, 4, 2, 1),
self._conv_block(128, 256, 4, 2, 1),
self._conv_block(256, 512, 4, 2, 1)
)
self.decoder = nn.Sequential(
self._deconv_block(512, 256, 4, 2, 1),
self._deconv_block(256, 128, 4, 2, 1),
self._deconv_block(128, 64, 4, 2, 1),
nn.ConvTranspose2d(64, out_channels, kernel_size=4, stride=2, padding=1),
nn.Tanh()
)
# Define Discriminator
class Discriminator(nn.Module):
def __init__(self, in_channels):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
self._conv_block(in_channels, 64, 4, 2, 1),
self._conv_block(64, 128, 4, 2, 1),
self._conv_block(128, 256, 4, 2, 1),
nn.Conv2d(256, 1, kernel_size=4, stride=1, padding=1)
)
# Hyperparameters
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
lr = 2e-4
batch_size = 16
epochs = 100
image_size = 128
in_channels = 3
out_channels = 3
# Data Preparation
transform = transforms.Compose([
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
# Initialize Models
generator = Generator(in_channels, out_channels).to(device)
discriminator = Discriminator(in_channels + out_channels).to(device)
# Training Loop
for epoch in range(epochs):
for i, (input_image, target_image) in enumerate(dataloader):
input_image, target_image = input_image.to(device), target_image.to(device)
real_labels = torch.ones((input_image.size(0), 1), requires_grad=False).to(device)
fake_labels = torch.zeros((input_image.size(0), 1), requires_grad=False).to(device)
# Train Generator
optimizer_G.zero_grad()
generated_image = generator(input_image)
disc_fake = discriminator(torch.cat((input_image, generated_image), dim=1))
g_loss = adversarial_loss(disc_fake, real_labels) + pixel_loss(generated_image,
target_image)
g_loss.backward()
optimizer_G.step()
# Train Discriminator
optimizer_D.zero_grad()
disc_real = discriminator(torch.cat((input_image, target_image), dim=1))
real_loss = adversarial_loss(disc_real, real_labels)
disc_fake = discriminator(torch.cat((input_image, generated_image.detach()), dim=1))
fake_loss = adversarial_loss(disc_fake, fake_labels)
d_loss = (real_loss + fake_loss) / 2
d_loss.backward()
optimizer_D.step()
# Logging
if i % 50 == 0:
print(f"Epoch [{epoch}/{epochs}] Batch {i}/{len(dataloader)} - Loss D: {d_loss.item()},
Loss G: {g_loss.item()}")
# Save Models
torch.save(generator.state_dict(), "generator.pth")
torch.save(discriminator.state_dict(), "discriminator.pth")
print("Training Complete!")
Inference :
# Generator (Autoencoder)
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(nn.Conv2d(3, 64, 4, 2, 1), nn.ReLU())
self.decoder = nn.Sequential(nn.ConvTranspose2d(64, 3, 4, 2, 1), nn.Tanh())
Result:
After running the training loop, the model will output a trained generator capable of performing
image edits.
The generator can take an input image, process it through the learned network, and produce
the transformed or edited version of the image (e.g., modifying facial features or changing the
style of a landscape).
The saved model files (generator.pth, discriminator.pth) can be used for inference in
future image editing tasks.