Deep Learning Lab Manual
Deep Learning Lab Manual
AIM:
Write a python program for solving XOR logic using DNN.
ALGORITHM:
Step 1 : Import required modules
Step 2 : Assign X(input) and y(output)
Step 3 : Assign the model to Sequential() function
Step 4 : Add hidden layer with the use of Dense() function
Step 5 : Compile and fit the model
Step 6 : Calculate the Loss and Accuracy
Step 7 : Print the Predicted output
Program:
#packages
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
#input and target
X=np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y=np.array([[0], [1], [1], [0]])
#building the model
model=Sequential()
#Adding the dense value for the hidden layer
model.add(Dense(8,input_dim=2,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
#compileing the model
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
#fitting the input and target into the model
model.fit(X,y,epochs=1000)
#calculating the loss and accuracy
loss,accuracy=model.evaluate(X,y)
print(f"Loss:{loss:.4f},Accuracy:{accuracy:.4f}")
#predicting the values
predictions=model.predict(X)
print("Predictions:")
for i in range(len(X)):
print(f"Input:{X[i]},Predicted Output:{predictions[i][0]:.4f}")
Output :
RESULT:
Thus the above python program to work with XOR logic using DNN has been executed
successfully and the output is displayed.
Ex.no: 1 B AND logic using DNN
Date:
AIM:
Write a python program for solving AND logic using DNN.
ALGORITHM:
Step 1 : Import required modules
Step 2 : Assign X(input) and y(output)
Step 3 : Assign the model to Sequential() function
Step 4 : Add hidden layer with the use of Dense() function
Step 5 : Compile and fit the model
Step 6 : Calculate the Loss and Accuracy
Step 7 : Print the Predicted output
Program:
#packages
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
#input and target
X=np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y=np.array([[0], [0], [0], [1]])
#building the model
model=Sequential()
#Adding the dense value for the hidden layer
model.add(Dense(8,input_dim=2,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
#compileing the model
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
#fitting the input and target into the model
model.fit(X,y,epochs=1000)
#calculating the loss and accuracy
loss,accuracy=model.evaluate(X,y)
print(f"Loss:{loss:.4f},Accuracy:{accuracy:.4f}")
#predicting the values
predictions=model.predict(X)
print("Predictions:")
for i in range(len(X)):
print(f"Input:{X[i]},Predicted Output:{predictions[i][0]:.4f}")
Output :
RESULT:
Thus the above python program to work with AND logic using DNN has been executed
successfully and the output is displayed.
Ex.no: 1 C OR logic using DNN
Date:
AIM:
Write a python program for solving OR logic using DNN.
ALGORITHM:
Step 1 : Import required modules
Step 2 : Assign X(input) and y(output)
Step 3 : Assign the model to Sequential() function
Step 4 : Add hidden layer with the use of Dense() function
Step 5 : Compile and fit the model
Step 6 : Calculate the Loss and Accuracy
Step 7 : Print the Predicted output
Program:
#packages
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
#input and target
X=np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y=np.array([[0], [1], [1], [1]])
#building the model
model=Sequential()
#Adding the dense value for the hidden layer
model.add(Dense(8,input_dim=2,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
#compileing the model
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
#fitting the input and target into the model
model.fit(X,y,epochs=1000)
#calculating the loss and accuracy
loss,accuracy=model.evaluate(X,y)
print(f"Loss:{loss:.4f},Accuracy:{accuracy:.4f}")
#predicting the values
predictions=model.predict(X)
print("Predictions:")
for i in range(len(X)):
print(f"Input:{X[i]},Predicted Output:{predictions[i][0]:.4f}")
Output :
RESULT:
Thus the above python program to work with OR logic using DNN has been executed
successfully and the output is displayed.
Ex.no: 2 Character Recognition using
CNN
Date:
AIM:
Write a python program for Character recognition using CNN.
ALGORITHM:
Step 1 : Import required modules
Step 2 : Load the training images
Step 3 : Assign the model to Sequential() function
Step 4 : Add hidden layer with the use of Dense() function
Step 5 : Compile and fit the model
Step 6 : Calculate the Loss and Accuracy
Step 7 : Print the Predicted output
Program:
#packages
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
import numpy as np
# Make predictions
predictions = model.predict(test_images)
predicted_labels = np.argmax(predictions, axis=1)
RESULT:
Thus the above python program for Character recognition using CNN has been executed
successfully and the output is displayed.
Ex.no: 3 Face Recognition using
CNN
Date:
AIM:
Write a python program for Face Recognition using CNN.
ALGORITHM:
Step 1 : Prepare the data
Step 2 : Model Architecture
Step 3 : Model compilation
Step 4 : Training the data
Step 5 : Evaluation and prediction
Program:
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
from keras.optimizers import Adam
from keras.callbacks import TensorBoard
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import accuracy_score
from keras.utils import np_utils
import itertools
cnn_model= Sequential([
Conv2D(filters=36, kernel_size=7, activation='relu', input_shape= im_shape),
MaxPooling2D(pool_size=2),
Conv2D(filters=54, kernel_size=5, activation='relu', input_shape= im_shape),
MaxPooling2D(pool_size=2),
Flatten(),
Dense(2024, activation='relu'),
Dropout(0.5),
Dense(1024, activation='relu'),
Dropout(0.5),
Dense(512, activation='relu'),
Dropout(0.5),
#20 is the number of outputs
Dense(20, activation='softmax')
])
cnn_model.compile(
loss='sparse_categorical_crossentropy',#'categorical_crossentropy',
optimizer=Adam(lr=0.0001),
metrics=['accuracy']
)
cnn_model.summary()
history=cnn_model.fit(
np.array(x_train), np.array(y_train), batch_size=512,
epochs=250, verbose=2,
validation_data=(np.array(x_valid),np.array(y_valid)),
)
scor = cnn_model.evaluate( np.array(x_test), np.array(y_test), verbose=0)
Acc=accuracy_score(y_test, ynew)
print("accuracy : ")
print(Acc)
#/tn, fp, fn, tp = confusion_matrix(np.array(y_test), ynew).ravel()
cnf_matrix=confusion_matrix(np.array(y_test), ynew)
AIM:
Write a python program for Language modelling using RNN.
ALGORITHM:
Step 1 : Import Libraries
Step 2 : Load and Preprocess Data
Step 3 : Build RNN Model
Step 4 : Train the Model
Step 5 : Generate Text
Program:
input_sequences = []
for line in text_data:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
# Generate Text
seed_text = "The quick brown fox"
next_words = 10
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_length-1, padding='pre')
predicted_probs = model.predict(token_list, verbose=0)
predicted_index = np.argmax(predicted_probs)
output_word = ""
print(seed_text)
Output :
RESULT:
Thus the above python program for Language Modelling using RNN has been executed
successfully and the output is displayed.
Ex.no: 5 Sentiment Analysis using LSTM
Date:
AIM:
Write a python program for Sentiment Analysis using LSTM.
ALGORITHM:
Step 1 : Import Libraries
Step 2 : Load and Preprocess Data
Step 3 : Tokenize and Pad Sequences
Step 4 : Build LSTM Model
Step 5 : Split Data and Train Model
Step 6 : Evaluate Model
Step 7 : Predict Sentiment on New Data
Program:
result = model.predict(X_validate[x].reshape(1,X_test.shape[1]),batch_size=1,verbose =
2)[0]
if np.argmax(result) == np.argmax(Y_validate[x]):
if np.argmax(Y_validate[x]) == 0:
neg_correct += 1
else:
pos_correct += 1
if np.argmax(Y_validate[x]) == 0:
neg_cnt += 1
else:
pos_cnt += 1
print("pos_acc", pos_correct/pos_cnt*100, "%")
print("neg_acc", neg_correct/neg_cnt*100, "%")
twt = ['Chris Christie is really standing out at the #GOPdebate']
#vectorizing the tweet by the pre-fitted tokenizer instance
twt = tokenizer.texts_to_sequences(twt)
#padding the tweet to have exactly the same shape as `embedding_2` input
twt = pad_sequences(twt, maxlen=28, dtype='int32', value=0)
print(twt)
sentiment = model.predict(twt,batch_size=1,verbose = 2)[0]
if(np.argmax(sentiment) == 0):
print("negative")
elif (np.argmax(sentiment) == 1):
print("positive")
Output :
RESULT:
Thus the above python program for Sentiment Analysis using LSTM has been executed
successfully and the output is displayed.
Ex.no: 6 Speech Tagging using sequence to sequence architecture
Date:
AIM:
Write a python program for Speech Tagging using sequence to sequence architecture.
ALGORITHM:
Step 1 : Import the required libraries
Step 2 : Define Example Data
Step 3 : Preprocess Data
Step 4 : Build Seq2Seq Model
Step 5 : Train the Model
Step 6 : Save the Trained Model
Step 7 : Use the Trained Model for Prediction
Program:
speech_data = [
("The quick brown fox jumps over the lazy dog.", ["DT", "JJ", "NN", "VBZ", "IN", "DT",
"JJ", "NN"]),
("A journey of a thousand miles begins with a single step.", ["DT", "NN", "IN", "DT",
"NN", "NNS", "VBZ", "IN", "DT", "JJ", "NN", "."]),
]
num_encoder_tokens = len(tokenizer_input.word_index) + 1
num_decoder_tokens = len(tokenizer_output.word_index) + 1
max_encoder_seq_length = max([len(seq) for seq in
tokenizer_input.texts_to_sequences(input_texts)])
max_decoder_seq_length = max([len(seq) for seq in
tokenizer_output.texts_to_sequences(target_texts)])
encoder_input_data = pad_sequences(tokenizer_input.texts_to_sequences(input_texts),
maxlen=max_encoder_seq_length)
decoder_input_data = pad_sequences(tokenizer_output.texts_to_sequences(target_texts),
maxlen=max_decoder_seq_length, padding='post')
decoder_target_data = pad_sequences(tokenizer_output.texts_to_sequences(target_texts),
maxlen=max_decoder_seq_length, padding='post')
embedding_dim = 50
latent_dim = 256
encoder_inputs = Input(shape=(None,))
encoder_embedding = Embedding(num_encoder_tokens, embedding_dim)(encoder_inputs)
encoder_lstm = LSTM(latent_dim, return_state=True)
_, state_h, state_c = encoder_lstm(encoder_embedding)
encoder_states = [state_h, state_c]
decoder_inputs = Input(shape=(None,))
decoder_embedding = Embedding(num_decoder_tokens, embedding_dim)(decoder_inputs)
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_embedding, initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
epochs = 50
batch_size = 32
decoder_target_one_hot = to_categorical(decoder_target_data, num_decoder_tokens)
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
model.fit(
[encoder_input_data, decoder_input_data],
decoder_target_one_hot,
epochs=epochs,
batch_size=batch_size,
validation_split=0.2,
callbacks=[early_stopping]
)
model.save("speech_tagging_model.h5")
loaded_model = load_model("speech_tagging_model.h5")
for i in range(max_decoder_seq_length):
predicted_probs = loaded_model.predict([new_encoder_input_data, decoder_input_data])
predicted_index = np.argmax(predicted_probs[0, i, :])
decoder_input_data[0, i] = predicted_index
RESULT:
Thus the above python program for Speech Tagging using sequence to sequence architecture
has been executed successfully and the output is displayed.
Ex.no: 7 Machine Translation using Encoder-Decoder model
Date:
AIM:
Write a python program for Machine Translation using Encoder-Decoder model.
ALGORITHM:
Step 1 : Import libraries
Step 2 : Data Preparation
Step 3 : Build the Encoder Model and Decoder Model
Step 4 : Add Attention Mechanism
Step 5 : Generate Output
Step 6 : Define the Model
Step 7 : Train the Model
Program:
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Embedding, LSTM, Dense, Attention
# Example Input Data
english_sentences = ['I love machine learning', 'Deep learning is fascinating', 'TensorFlow is
a powerful tool']
french_sentences = ['J\'aime l\'apprentissage automatique', 'L\'apprentissage profond est
fascinant', 'TensorFlow est un outil puissant']
# Tokenize and pad the sequences
tokenizer_eng = Tokenizer()
tokenizer_eng.fit_on_texts(english_sentences)
eng_sequences = tokenizer_eng.texts_to_sequences(english_sentences)
eng_sequences_padded = pad_sequences(eng_sequences, padding='post')
tokenizer_frn = Tokenizer()
tokenizer_frn.fit_on_texts(french_sentences)
frn_sequences = tokenizer_frn.texts_to_sequences(french_sentences)
frn_sequences_padded = pad_sequences(frn_sequences, padding='post')
# Define vocabulary sizes
vocab_size_eng = len(tokenizer_eng.word_index) + 1
vocab_size_frn = len(tokenizer_frn.word_index) + 1
RESULT:
Thus the above python program for Machine Translation using Encoder-Decoder model has
been executed successfully and the output is displayed.
Ex.no: 8 Image Augmentation using GANs
Date:
AIM:
Write a python program for Image Augmentation using GANs.
ALGORITHM:
Step 1 : Import Libraries
Step 2 : Define GAN Architecture
Step 3 : Load and Preprocess Dataset
Step 4 : Train the GAN
Step 5 : Generate Augmented Images
Step 6 : Display Generated Images
Step 7 : Adjust Hyperparameters and Iterate
Program:
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Reshape, Flatten
from tensorflow.keras.layers import BatchNormalization, Activation, LeakyReLU,
UpSampling2D, Conv2D
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
import matplotlib.pyplot as plt
def build_discriminator(img_shape):
model = Sequential()
model.add(Flatten(input_shape=img_shape))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(256))
model.add(LeakyReLU(alpha=0.2))
model.add(Dense(1, activation='sigmoid'))
return model
# Define parameters
img_rows, img_cols, channels = 28, 28, 1
img_shape = (img_rows, img_cols, channels)
latent_dim = 100