0% found this document useful (0 votes)
21 views60 pages

DL Lab - Merged

Uploaded by

Moshika Vetrivel
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)
21 views60 pages

DL Lab - Merged

Uploaded by

Moshika Vetrivel
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
You are on page 1/ 60

Sri Manakula Vinayagar Engineering College

(Approved by AICTE. New Delhi, Affiliated to Pondicherry U niversity,


Accredited by N BA-AICTE, New Delhi,Accredited by NAAC with ‘A' Grade &
An ISO 9001 : 2000 Certified Institution)
Ph: O413-2ó42O0O/ 2ó41151, Fax: 0413-2ó4J13ó/ email: [email protected] web:www.smvec ac.in

Register Number :
Name :
Subject Name/Subject Code :

Branch :
Year/Semester :

Certificate
Certified that this is the bonafide record of Practical work done by

the above student in the .........................................................

…………………….Laboratory during the academic year ...................

Staff in-charge Head of the Department

Submitted for the End Semester practical Examination held on.........

Internal Examiner External Examiner


Page |0

TABLE OF CONTENTS

S.NO DATE TITLE PAGE MARK SIGN


NO

1. Build a Simple Neural


Network

2. Classification of Dog or Cat


using CNN

Stock Price Prediction using


3. RNN

4. Sales Prediction using LSTM

Movie Box Office Prediction


5. using GRU

6. Sports Result Prediction


using RNN and LSTM

7. Cardiovascular Disease
Prediction using ANN

8. Style Transfer Technique

9. Traffic Sign Prediction

10. Fashion Recommendation


System
Page |1

Exp No : 01 Simple Neural Network


Date :

Aim:
To build a simple Neural Network using python.

Algorithm:
1. Import the required packages.
2. Define the neural network architecture, such as the number of layers, the
number of neurons in each layer, and the activation function for each layer.
3. Initialize the weights and biases of the network using random values or a pre-
defined initialization method.
4. Feed the input data through the network, using the initialized weights and biases
to make predictions.
5. Calculate the error or loss between the predicted output and the actual output.
6. Use an optimization algorithm, such as stochastic gradient descent, to update the
weights and biases in order to reduce the error.
7. Repeat steps 3-5 for a number of iterations or until the error is below a certain
threshold.
8. Use the trained network to make predictions on new data.
Program:
#import required packages

import numpy as np

#the random number generator

class NeuralNetwork():

def __init__(self):
np.random.seed(1)
self.synaptic_weights = 2 * np.random.random((3, 1)) - 1
Page |2
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))

def sigmoid_derivative(self, x):


return x * (1 - x)

def train(self, training_inputs, training_outputs, training_iterations):


for iteration in range(training_iterations):
# Pass training set through the neural network
output = self.think(training_inputs)

# Calculate the error rate


error = training_outputs - output

# Multiply error by input and gradient of the sigmoid function


# Less confident weights are adjusted more through the nature of the function
adjustments = np.dot(training_inputs.T, error * self.sigmoid_derivative(output))

# Adjust synaptic weights


self.synaptic_weights += adjustments

if __name__ == "__main__":

# Initialize the single neuron neural network


neural_network = NeuralNetwork()

print("Random starting synaptic weights: ")


print(neural_network.synaptic_weights)

# The training set, with 4 examples consisting of 3


# input values and 1 output value
training_inputs = np.array([[0,0,1],
[1,1,1],
[1,0,1],
[0,1,1]])

training_outputs = np.array([[0,1,1,0]]).T

# Train the neural network


neural_network.train(training_inputs, training_outputs, 10000)

#Pass inputs through the neural network to get output

def think(self, inputs):


inputs = inputs.astype(float)
output = self.sigmoid(np.dot(inputs, self.synaptic_weights))
return output
Page |3
print("Synaptic weights after training: ")
print(neural_network.synaptic_weights)

A = str(input("Input 1: "))
B = str(input("Input 2: "))
C = str(input("Input 3: "))

print("New situation: input data = ", A, B, C)


print("Output data: ")
print(neural_network.think(np.array([A, B, C])))

Output:
Page |4

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and 15
Output
Viva 05
Total 25

Result:
Thus, the Python program to build a simple Neural Network was implemented successfully and
the output is verified.
Page |5

Exp No : 02 Dog Cat Classification


Date :

AIM:

To Write a Python program to implement Classification of Cat and Dog using CNN.

ALGORITHM:

1. Import basic numpy,matplotlib and pandas packages.


2. Import tensorflow and keras packages for building the model.
3. Import cv2 packages to handle processing of image data.
4. Import Dataset containing dataset of images of dogs and cats, and label them accordingly.
5. Preprocess the images by resizing and normalizing them.
6. Generate and split classes from the labelled images.
7. Perform model training and validation to adjust the parameters of the network so that it can
accurately classify new images
8. Build the Model comprising multiple neural layers to be used for prediction.
9. Fit the model with trained data to classify new images by feeding them through the network.
10. Implement model testing using test dataset to make predictions on new unseen images of
dogs and cats.
11. Perform prediction over unseen images of dogs and cats, and compare the predicted labels to
the true labels.
Page |6

PROGRAM:
#import required packages

import os
import pandas as pd

import tensorflow as tf
from tensorflow import keras
from keras import Model
from keras.layers import Dense, GlobalAveragePooling2D, Input
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import load_img, img_to_array
from keras.applications.vgg16 import preprocess_input, decode_predictions, VGG16
from keras.models import load_model

import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow

#loading dataset

train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)

train_generator = train_datagen.flow_from_directory('DOG_CAT',

target_size=(224,224),

color_mode='rgb',

batch_size=32,

class_mode='categorical',

shuffle=True)

#splitting classes

train_generator.class_indices.values()
NO_CLASSES = len(train_generator.class_indices.values())
train_generator.class_indices.values()
Page |7

# model building

model = VGG16(include_top=False, input_shape=(224, 224, 3))


x = model.output
x = GlobalAveragePooling2D()(x)

x = Dense(1024, activation='relu')(x)
x = Dense(1024, activation='relu')(x)
x = Dense(512, activation='relu')(x)

# final layer with softmax activation


preds = Dense(NO_CLASSES, activation='softmax')(x)
model = Model(model.input, preds)

# don't train first 19 layers


for layer in model.layers[:19]:
layer.trainable = False
# train rest of the layers - 19 onwards
for layer in model.layers[19:]:
layer.trainable = True

#model compilation

model.compile(optimizer='Adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
Page |8

#model fitting

model.fit(x=train_generator,
batch_size = 1,
verbose = 1,
epochs = 20)
Page |9

# model testing

class_dictionary = {0:'Cat', 1:'Dog'}


imgtest = cv2.imread(' dog.481.jpg',cv2.IMREAD_UNCHANGED)
size = (224, 224)
imgtest = cv2.resize(imgtest, size)

# prepare the image for prediction


x = imgtest
x = np.expand_dims(x, axis=0)
x = tf.keras.applications.imagenet_utils.preprocess_input(x)

# making prediction
cv2_imshow(imgtest)
predicted_prob = model.predict(x)
print(predicted_prob)
print(predicted_prob[0].argmax())
print("Predicted : " + class_dictionary[predicted_prob[0].argmax()])
print("============================\n")
P a g e | 10

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Classification of Cat Dog in CNN was
implemented successfully and the output is verified.
P a g e | 11

Exp No : 03 Stock Price Prediction


Date :

AIM:

To write a Python program to implement Stock Price Predicion


using deep learning.

ALGORITHM:

1. Collect historical stock data and pre-process it to clean and format it for use in a machine
learning model.
2. Divide the data into training and testing sets.
3. Build an LSTM model using the training data.
4. Train the model on the training data.
5. Use the trained model to make predictions on the testing data.

PROGRAM:
#import required packages

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, Bidirectional

#import dataset

google_stock_data = pd.read_csv('goog.csv')
P a g e | 12

#Understading the data

data.describe()
google_stock_data.info()

google_stock_data.shape

# Extracting required data and setting index

google_stock_data = google_stock_data[['Date','Open','Close']] # Extracting


required columns
google_stock_data['date'] = pd.to_datetime(google_stock_data['Date'].apply(lambda
x: x.split()[0])) # Selecting only date
google_stock_data.set_index('date',drop=True,inplace=True) # Setting date column
as index

# Scale the data

MMS = MinMaxScaler()
google_stock_data[google_stock_data.columns] =
MMS.fit_transform(google_stock_data)

#Split data into Train and Test dataset

training_size = round(len(google_stock_data) * 0.80) # Selecting 80 %


for training and 20 % for testing
training_size
P a g e | 13

train_data = google_stock_data[:training_size]
test_data = google_stock_data[training_size:]

train_data.shape, test_data.shape

#Function to create sequence of data for training and testing

def create_sequence(dataset):
sequences = []
labels = []

start_idx = 0

for stop_idx in range(50,len(dataset)): # Selecting 50 rows at a time


sequences.append(dataset.iloc[start_idx:stop_idx])
labels.append(dataset.iloc[stop_idx])
start_idx += 1
return (np.array(sequences),np.array(labels))

#Passing the train and test data to the create_sequence function

train_seq, train_label = create_sequence(train_data)


test_seq, test_label = create_sequence(test_data)

train_seq.shape, train_label.shape, test_seq.shape, test_label.shape


P a g e | 14

#Building the Model

model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape =
(train_seq.shape[1], train_seq.shape[2])))

model.add(Dropout(0.1))
model.add(LSTM(units=50))

model.add(Dense(2))

model.compile(loss='mean_squared_error', optimizer='adam',
metrics=['mean_absolute_error'])

model.summary()

#Fitting the Model

model.fit(train_seq, train_label, epochs=80,validation_data=(test_seq,


test_label), verbose=1)
P a g e | 15

#Performing prediction and rescaling

test_predicted = model.predict(test_seq)
test_predicted[:5]

test_inverse_predicted = MMS.inverse_transform(test_predicted) #
Inversing scaling on predicted data
test_inverse_predicted[:5]
P a g e | 16

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Stock Prediction using Deep Learning was
implemented successfully and the output is verified.
P a g e | 17

Exp No : 04 Forecast Sales using LSTM


Date :

AIM:
To write a Python program to implement Forecast sales using LSTM.

ALGORITHM:

1. Prepare the data: Gather historical sales data and organize it into a format that can be
used to train the LSTM model.

2. Define the LSTM model: Use Keras or TensorFlow to define the architecture of the
LSTM model.

3. Train the model: Use the prepared data to train the LSTM model. This process may
require multiple epochs and may involve tuning the model's hyperparameters to
optimize performance.

4. Make predictions: Use the trained model to make predictions on new data. This can
be done by inputting a sequence of historical sales data and having the model predict
the next value in the sequence.
P a g e | 18

Program:

#import required package

import os
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

from matplotlib import pylab as plt


import matplotlib.dates as mdates
plt.rcParams['figure.figsize'] = (15.0, 8.0)
import seaborn as sns

#importing the Dataset

sub = pd.read_csv('sample_submission.csv')
sub.head()

train = pd.read_csv('sales_train.csv')
print ('number of shops: ', train['shop_id'].max())
print ('number of items: ', train['item_id'].max())
num_month = train['date_block_num'].max()
print ('number of month: ', num_month)
print ('size of train: ', train.shape)
train.head()
P a g e | 19

test = pd.read_csv('test.csv')
test.head()

items = pd.read_csv('items.csv')
print ('number of categories: ', items['item_category_id'].max()) # the maximun number of
category id
items.head()

train_clean = train.drop(labels = ['date', 'item_price'], axis = 1)


train_clean.head()

# Change the item count per day to item count per month by using group
P a g e | 20
\\\

train_clean = train_clean.groupby(["item_id","shop_id","date_block_num"]).sum().reset_index()
train_clean = train_clean.rename(index=str, columns = {"item_cnt_day":"item_cnt_month"})
train_clean = train_clean[["item_id","shop_id","date_block_num","item_cnt_month"]]
train_clean

check = train_clean[["shop_id","item_id","date_block_num","item_cnt_month"]]
check = check.loc[check['shop_id'] == 5]
check = check.loc[check['item_id'] == 5037]
check

plt.figure(figsize=(10,4))
plt.title('Check - Sales of Item 5037 at Shop 5')
plt.xlabel('Month')
plt.ylabel('Sales of Item 5037 at Shop 5')
plt.plot(check["date_block_num"],check["item_cnt_month"]);
P a g e | 21

month_list=[i for i in range(num_month+1)]


shop = []
for i in range(num_month+1):
shop.append(5)
item = []
for i in range(num_month+1):
item.append(5037)
months_full = pd.DataFrame({'shop_id':shop, 'item_id':item,'date_block_num':month_list})
months_full

sales_33month = pd.merge(check, months_full, how='right',


on=['shop_id','item_id','date_block_num'])
sales_33month = sales_33month.sort_values(by=['date_block_num'])

sales_33month.fillna(0.00,inplace=True)
sales_33month
P a g e | 22

plt.figure(figsize=(10,4))

plt.title('Check - Sales of Item 5037 at Shop 5 for whole period')


plt.xlabel('Month')
plt.ylabel('Sales of Item 5037 at Shop 5')
plt.plot(sales_33month["date_block_num"],sales_33month["item_cnt_month"]);

for i in range(1,6):
sales_33month["T_" + str(i)] = sales_33month.item_cnt_month.shift(i)
sales_33month.fillna(0.0, inplace=True)
sales_33month

df = sales_33month[['shop_id','item_id','date_block_num','T_1','T_2','T_3','T_4','T_5',
'item_cnt_month']].reset_index()
df = df.drop(labels = ['index'], axis = 1)
df
P a g e | 23

train_df = df[:-3]
val_df = df[-3:]
x_train,y_train = train_df.drop(["item_cnt_month"],axis=1),train_df.item_cnt_month
x_val,y_val = val_df.drop(["item_cnt_month"],axis=1),val_df.item_cnt_month
x_train

y_train
P a g e | 24
#Importing relevant Libraries to Perform LSTM

from keras.models import Sequential


from keras.layers import Dense
from keras.layers import LSTM
model_lstm = Sequential()
model_lstm.add(LSTM(15, input_shape=(1,8)))
model_lstm.add(Dense(1))
model_lstm.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])

# Reshape the data between -1 and 1 and to 3D

from sklearn.preprocessing import StandardScaler,MinMaxScaler


scaler = StandardScaler()
scaler = MinMaxScaler(feature_range=(-1, 1))
x_train_scaled = scaler.fit_transform(x_train)
x_valid_scaled = scaler.fit_transform(x_val)

x_train_reshaped = x_train_scaled.reshape((x_train_scaled.shape[0], 1,
x_train_scaled.shape[1]))
x_val_resaped = x_valid_scaled.reshape((x_valid_scaled.shape[0], 1, x_valid_scaled.shape[1]))

history = model_lstm.fit(x_train_reshaped, y_train, validation_data=(x_val_resaped,


y_val),epochs=70, batch_size=12, verbose=2, shuffle=False)
y_pre = model_lstm.predict(x_val_resaped)
P a g e | 25

fig, ax = plt.subplots()
ax.plot(x_val['date_block_num'], y_val, label='Actual')
ax.plot(x_val['date_block_num'], y_pre, label='Predicted')
plt.title('LSTM Prediction vs Actual Sales for last 3 months')
plt.xlabel('Month')
plt.xticks(x_val['date_block_num'])
plt.ylabel('Sales of Item 5037 at Shop 5')
ax.legend()
plt.show()

#Calculating RMSE

from sklearn.metrics import mean_squared_error


from numpy import sqrt
rmse = sqrt(mean_squared_error(y_val,y_pre))
print('Val RMSE: %.3f' % rmse)
P a g e | 26

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Sales Forecast was implemented successfully
and the output is verified.
P a g e | 27

Exp No : 05 Movie Box Office Prediction


Date :

Aim :
To write a Python program to implement Movie Box Office Prediction using GRU.

Algorithm:

1. Collect data: Gather historical data on movies, such as box office revenue, budget,
cast, genre, release date, and other relevant information.

2. Pre-processing: Clean and preprocess the data by handling missing values, converting
categorical variables, and scaling numerical variables.

3. Feature engineering: Create new features by combining or transforming the existing


features that may be useful in predicting the box office revenue.

4. Data preparation: Prepare the data for use in a GRU (gated recurrent unit) model, by
formatting it into sequences and padding as necessary.

5. Model selection: Choose an appropriate GRU model for the task, such as a simple
GRU or a stacked GRU.

6. Training: Train the model using the pre-processed and prepared data and features.

7. Validation: Evaluate the model's performance using a validation dataset, and adjust
the model or features as needed.

8. Testing: Test the model on unseen data and evaluate its performance to determine
its accuracy in predicting box office revenue.
P a g e | 28

Program:
#import packages

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from keras.layers import Input, Embedding, GRU, Dense
from keras.models import Model
from keras.callbacks import EarlyStopping

#import dataset

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from keras.layers import Input, Embedding, GRU, Dense
from keras.models import Model
from keras.callbacks import EarlyStopping

#load the dataset

# Load the data


df = pd.read_csv("/content/bollywood_box_clean.csv")
df

#x split,y split

x = df[["movie_opening","movie_weekend","movie_firstweek"]]
y = df["movie_total_worldwide"]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
P a g e | 29

#model building

input_shape = (x_train.shape[1], 1)
input_layer = Input(shape=input_shape)
gru_layer = GRU(64, return_sequences=True, dropout=0.2,
recurrent_dropout=0.2)(input_layer)
gru_layer = GRU(32, return_sequences=True, dropout=0.2,
recurrent_dropout=0.2)(gru_layer)
gru_layer = GRU(16, dropout=0.2, recurrent_dropout=0.2)(gru_layer)
output_layer = Dense(1, activation='linear')(gru_layer)
model = Model(input_layer, output_layer)
model.compile(loss='mean_squared_error', optimizer='adam',
metrics=['mean_absolute_error'])

#model fit

early_stopping = EarlyStopping(monitor='val_loss', patience=5)


model.fit(x_train, y_train, epochs=100, batch_size=32, validation_data=(x_test,
y_test), callbacks=[early_stopping])
P a g e | 30

#model loss

test_loss = model.evaluate(x_test, y_test)


print(f'Test loss: {test_loss}')

#prediction

y_pred = model.predict([[171.50 ,123,234]])

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Box Office Prediction using GRU was
implemented successfully and the output is verified.
P a g e | 31

Exp No : 06 Sports result Prediction


Date :

AIM:
To write a deep learning model to predict Sports result Prediction using RNN and LSTM

ALGORITHM:

1. Gather historical data on the teams or players involved in the event, including statistics
such as wins, losses, points scored, and other relevant information.

2. Clean and preprocess the data by handling missing values, converting categorical
variables, and scaling numerical variables.

3. Create new features by combining or transforming the existing features that may be
useful in predicting the outcome of the event.

4. Choose an appropriate machine learning model for the task, such as logistic regression,
decision trees, or neural networks.

5. Training: Train the model using the pre-processed data and features.

6. Evaluate the model's performance using a validation dataset, and adjust the model or
features as needed.

7. Test the model on unseen data and evaluate its performance to determine its accuracy in
predicting the outcome of the event.

PROGRAM:
#import required packages

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import pandas as pd
P a g e | 32

#import datasets

dataTrain=pd.read_csv("allAtt_onehot_large_train.csv")
dataTest=pd.read_csv("allAtt_onehot_large_test.csv")
print(dataTrain.head())
print(dataTrain.shape)

FTR HTGS ATGS HTGC ATGC HTP ATP HM1 HM2 HM3 ... ATWinStreak5 \
0 0 0.0 0.0 0.0 0.0 0.0 0.0 2 2 2 ... 0
1 0 0.0 0.0 0.0 0.0 0.0 0.0 2 2 2 ... 0
2 1 0.0 0.0 0.0 0.0 0.0 0.0 2 2 2 ... 0
3 0 0.0 0.0 0.0 0.0 0.0 0.0 2 2 2 ... 0
4 1 0.0 0.0 0.0 0.0 0.0 0.0 2 2 2 ... 0

ATLossStreak3 ATLossStreak5 HTGD ATGD DiffPts DiffFormPts DiffLP \


0 0 0 0.0 0.0 0.0 0.0 -11.0
1 0 0 0.0 0.0 0.0 0.0 2.0
2 0 0 0.0 0.0 0.0 0.0 2.0
3 0 0 0.0 0.0 0.0 0.0 -17.0
4 0 0 0.0 0.0 0.0 0.0 4.0

final1 final2
0 1.0 0.0
1 1.0 0.0
2 0.0 1.0
3 1.0 0.0
4 0.0 1.0

[5 rows x 30 columns]

(1860, 30)

#building RNN model

batch_size = 64
# Each MNIST image batch is a tensor of shape (batch_size, 28, 1).
# Each input sequence will be of size (28, 1).
input_dim = 27

units = 64
output_size = 2 # labels are from Win or Loss

# Build the RNN model


def build_model():

lstm_layer = keras.layers.RNN(
keras.layers.LSTMCell(units), input_shape=(input_dim,1)
)
model = keras.models.Sequential(
[
lstm_layer,
keras.layers.BatchNormalization(),
keras.layers.Dense(output_size),
]
)
return model
P a g e | 33

#Splitting Data into Train-Test Split

x_train, y_train = dataTrain.iloc[:,1:28].values,dataTrain.iloc[:,28:].values


x_train=np.reshape(x_train,(1860,27,1))
x_test, y_test = dataTest.iloc[:,1:28].values,dataTest.iloc[:,28:].values
x_test=np.reshape(x_test,(800,27,1))

model = build_model()
model.compile(
loss=keras.losses.CategoricalCrossentropy(from_logits=True),
optimizer="Adam",
metrics=["categorical_accuracy"],
)
model.summary()
P a g e | 34

model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=10
)

model.save('LSTM-footballMatchWinner')

model1=tf.keras.models.load_model('LSTM-footballMatchWinner')

model1.predict(np.expand_dims(x_test[0], 0))
P a g e | 35

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement deep learning model to predict Sports
result Prediction using RNN and LSTM was implemented successfully and the output
is verified.
P a g e | 36

Exp No : 07 Cardiovascular Disease Detection


Date :

AIM:

To write a Python program to implement Cardiovascular Disease Detection


using deep learning

ALGORITHM:

1. Import basic numpy,matplotlib and pandas packages


2. Import tensorflow and keras packages for building the model.
3. Import the dataset containing different attributes such as sex, age, cholesterol level, etc
4. Assign Dependent and Independent variables to the dataset using iloc().
5. Split data into Train and Test dataset using train_test_split().
6. Scale the data using StandardScaler function from sklearn.preprocessing module.
7. Build the Model comprising multiple neural layers to be used for prediction.
8. Perform prediction and rescaling over unseen data.
9. Compute the accuracy and print the confusion matrix to evaluate the model’s
performance.

PROGRAM:
#import required packages

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense
from sklearn.metrics import confusion_matrix

#import dataset

data = pd.read_csv('heart.csv')
data.head()
P a g e | 37

#data description

data.describe()
data.describe()

# Assign Dependent and Independent variable

X = data.iloc[:,:13].values
y = data["target"].values

#Split data into Train and Test dataset

X_train,X_test,y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0 )


P a g e | 38

# Scale the data

from sklearn.preprocessing import StandardScaler


sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

#Building the Model


classifier = Sequential()

classifier.add(Dense(activation = "relu", input_dim = 13,

units = 8, kernel_initializer = "uniform"))

classifier.add(Dense(activation = "relu", units = 14,

kernel_initializer = "uniform"))

classifier.add(Dense(activation = "sigmoid", units = 1,

kernel_initializer = "uniform"))

classifier.compile(optimizer = 'adam' , loss = 'binary_crossentropy',

metrics = ['accuracy'] )
P a g e | 39

#Fitting the Model

classifier.fit(X_train , y_train , batch_size = 8 ,epochs = 100 )

#Performing prediction and rescaling

y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)

#Confusion Matrix

cm = confusion_matrix(y_test,y_pred)
cm

#Accuracy

accuracy = (cm[0][0]+cm[1][1])/(cm[0][1] + cm[1][0] +cm[0][0] +cm[1][1])


print(accuracy*100)
P a g e | 40

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Cardiovascular Disease detection using Deep
Learning was implemented successfully and the output is verified.
P a g e | 41
Exp No : 08 Style Transfer Technique
Date :

AIM:
To Write a Python program to create an art using Style Transfer Technique.

ALGORITHM:

1. Start by importing the necessary libraries and modules, including TensorFlow and any
image processing libraries.

2. Next, load the content and style images, convert them to the Tensor image format for
processing.

3. Visualize the content and style image using opencv’s imshow function.

4. Load the hub model then implement Style transfer, and convert the Tensor image into
numpy Image.

5. Visualize the final Stylized image.

PROGRAM:
#import required packages

import tensorflow as tf
import cv2
from google.colab.patches import cv2_imshow
import tensorflow_hub as hub
import numpy as np
import PIL
import matplotlib.pyplot as plt

#loading dataset
content_path = "/content/dog.jpg"
style_path = "/content/style.jpg"

dog_image = load_img(content_path)
style_image = load_img(style_path)

dog = cv2.imread(content_path)
style = cv2.imread(style_path)
P a g e | 42

#changing to tensor image

def load_img(path_to_img):
img = tf.io.read_file(path_to_img)
img = tf.image.decode_image(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32)
img = img[tf.newaxis, :]
return img

# visualizing images

cv2_imshow(dog)
cv2_imshow(style)

#tensor to image

def tensor_to_image(tensor):
tensor = tensor*255
tensor = np.array(tensor, dtype=np.uint8)
if np.ndim(tensor)>3:
assert tensor.shape[0] == 1
tensor = tensor[0]
return PIL.Image.fromarray(tensor)
P a g e | 43

#performing style transfer

hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-
256/2')
stylized_image = hub_model(tf.constant(dog_image), tf.constant(style_image))[0]
op = tensor_to_image(stylized_image)
op
P a g e | 44

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to create an art using Style Transfer Technique was
implemented successfully and the output is verified.
P a g e | 45

Exp No : 09 Traffic Sign Detection


Date :

AIM:
To Write a Python Program to implement traffic sign detection using deep learning

ALGORITHM:

1. Dataset exploration
2. CNN model building
3. Model training and validation
4. Model testing

PROGRAM:
#import required packages

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from PIL import Image
import os
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout
P a g e | 46

data = []
labels = []
classes = 43
cur_path = os.getcwd()
for i in range(classes):
path = os. path.join(cur_path,'train', str(i))
images = os.listdir(path)
for a in images:
try:
image = Image.open(path + "/" + a)
image = image.resize((30,30))
image = np.array(image)
data.append(image)
labels.append(i)
except:
print("Error loading image")
data = np.array(data)
labels = np.array(labels)
P a g e | 47

#splitting train test data

X_t1, X_t2, y_t1, y_t2 = train_test_split(data, labels, test_size=0.2,


random_state=42)
print(X_t1.shape, X_t2.shape, y_t1.shape, y_t2.shape)

#converting labels into one hot encoded array

y_t1 = to_categorical(y_t1, 43)


y_t2 = to_categorical(y_t2, 43)

#Model Building

model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu',
input_shape=X_t1.shape[1:]))
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(43, activation='softmax'))
#Compilation of the model
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
P a g e | 48

#Model fitting and loss plotting

eps = 15
anc = model.fit(X_t1, y_t1, batch_size=32, epochs=eps, validation_data=(X_t2, y_t2))

plt.figure(0)
plt.plot(anc.history['accuracy'], label='training accuracy')
plt.plot(anc.history['val_accuracy'], label='val accuracy')
plt.title('Accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()
plt.figure(1)
plt.plot(anc.history['loss'], label='training loss')
plt.plot(anc.history['val_loss'], label='val loss')
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.show()
P a g e | 49

# Model testing

y_test = pd.read_csv('Test.csv')
labels = y_test["ClassId"].values
imgs = y_test["Path"].values
data=[]
for img in imgs:
image = Image.open(img)
image = image.resize((30,30))
data.append(np.array(image))
X_test=np.array(data)
pred = np.argmax(model.predict(X_test),axis=-1)
print(accuracy_score(labels, pred))
P a g e | 50

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Traffic Sign detection was implemented
successfully and the output is verified.
P a g e | 51

Exp No : 10 Fashion Recommendation System


Date :

AIM:

To write a Python program to implement fashion recommendation system


using deep learning

ALGORITHM:

1. Import basic numpy,matplotlib and pandas packages


2. Import tensorflow and keras packages for building the model.
3. Import the dataset
4. The model can be built using TensorFlow's library .
5. The model can be trained using model functions .
6. The model can be evaluated on the test data using the model.evaluate function to determine
its performance.

PROGRAM:
#import required packages

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import keras
from tensorflow import keras
from tensorflow.keras import layers

#import dataset

# Load the Fashion MNIST dataset


(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()

# Pre-process and normalize the data


x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
P a g e | 52
for i in range(1, 10):
# Create a 3x3 grid and place the
# image in ith position of grid
plt.subplot(3, 3, i)
# Insert ith image with the color map 'grap'
plt.imshow(x_train[i], cmap=plt.get_cmap('gray'))
# Display the entire plot
plt.show()

# build the model

model = keras.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28
, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
P a g e | 53
#compile the model

Model.compile(optimizer=’adam’,
Loss=’sparse_categorical_crossentropy’,
Metrics=[‘accuracy’])

#train the model

Model.fit(x_train , y_train, epochs=10

1875/1875 [==============================] - 47s 25ms/step - loss: 0.4670 - accuracy: 0.8321


Epoch 2/10
1875/1875 [==============================] - 46s 25ms/step - loss: 0.3106 - accuracy: 0.8876
Epoch 3/10
1875/1875 [==============================] - 46s 24ms/step - loss: 0.2623 - accuracy: 0.9045
Epoch 4/10
1875/1875 [==============================] - 47s 25ms/step - loss: 0.2321 - accuracy: 0.9147
Epoch 5/10
1875/1875 [==============================] - 46s 24ms/step - loss: 0.2082 - accuracy: 0.9231
Epoch 6/10
1875/1875 [==============================] - 46s 24ms/step - loss: 0.1840 - accuracy: 0.9317
Epoch 7/10
1875/1875 [==============================] - 45s 24ms/step - loss: 0.1661 - accuracy: 0.9379
Epoch 8/10
1875/1875 [==============================] - 47s 25ms/step - loss: 0.1521 - accuracy: 0.9420
Epoch 9/10
1875/1875 [==============================] - 46s 24ms/step - loss: 0.1350 - accuracy: 0.9495
Epoch 10/10
1875/1875 [==============================] - 47s 25ms/step - loss: 0.1210 - accuracy: 0.9543
<keras.callbacks.History at 0x7fe768786eb0>

#Testing the model

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)


print('\nTest accuracy:', test_acc)

313/313 - 2s - loss: 0.2712 - accuracy: 0.9140 - 2s/epoch - 7ms/step

Test accuracy: 0.9139999747276306

#Performing prediction

preds = model.predict(x_test)

313/313 [==============================] - 2s 7ms/step


P a g e | 54

preds

array([[5.21710626e-11, 4.38785225e-14, 5.41233378e-11, ...,


4.16331568e-06, 5.73813053e-10, 9.99995768e-01],
[1.22869635e-04, 5.41403267e-14, 9.99857187e-01, ...,
3.82869917e-20, 3.92373952e-14, 4.03190164e-18],
[9.56766444e-10, 9.99999940e-01, 1.16273614e-11, ...,
4.80054906e-13, 4.28643835e-14, 1.08521583e-16],
...,
[1.05394915e-10, 4.88345017e-18, 4.71877849e-11, ...,
5.04024097e-16, 9.99999940e-01, 6.66639578e-15],
[6.14252693e-09, 9.99999940e-01, 1.34258493e-09, ...,
2.87600933e-12, 3.29104625e-12, 2.78573258e-12],
[1.75850637e-05, 1.76399801e-08, 1.03879202e-05, ...,
1.14196492e-02, 7.01214478e-04, 2.56649564e-05]], dtype=float32)

Criteria Maximum Marks Marks Obtained

Aim and Algorithm 05


Program and Output 15
Viva 05
Total 25

RESULT:
Thus, the Python program to implement Fashion Recommendation System using Deep
Learning was implemented successfully and the output is verified.

You might also like