DL Practical PROGRAM
DL Practical PROGRAM
Task 6 –
Write a program to develop optimized ANN model, then print the
Accuracy plot of the Mushroom dataset downloaded from Kaggle.
Program –
import pandas as pd
import numpy as np
df = pd.read_csv('mushroom_cleaned.csv')
#REMOVING DUPLICATES
df1 = df.drop_duplicates()
#LABEL ENCODING
label_encoder = LabelEncoder()
for column in df1.columns:
df1.loc[:, column] = label_encoder.fit_transform(df1[column])
#STANDARD SCALING
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(x_train)
x_train = sc.transform(x_train)
x_test = sc.transform(x_test)
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout
model = Sequential()
model.add(Dense(128,activation='relu',input_dim= x_train.shape[1]))
model.add(Dropout(0.3))
model.summary() #1
#COMPILING MODEL
from tensorflow.keras.optimizers import Adam
optimizer = Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=optimizer,
metrics=['accuracy'])
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
#ACCURACY
from sklearn.metrics import accuracy_score
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
#3
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 7 –
Write a Program to develop a ANN model, then print the accuracy
plot of TITANIC dataset.
Program –
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
df["Age"].fillna(df["Age"].median(), inplace=True)
df["Embarked"].fillna(df["Embarked"].mode()[0], inplace=True)
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
random_state=42)
# Standardize features
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
# Build model
model = Sequential([
Dense(64, activation='relu', input_dim=x_train.shape[1]),
Dropout(0.3),
Dense(32, activation='relu'),
Dense(y.shape[1], activation='softmax')
])
# Compile model
optimizer = Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy',
optimizer=optimizer, metrics=['accuracy'])
# Train model
history = model.fit(x_train, y_train, epochs=50, batch_size=32,
validation_data=(x_test, y_test), verbose=1)
# Evaluate model
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
print(f"Test Accuracy: {test_accuracy:.3f}") #1
# Plot accuracy
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Training and Validation Accuracy')
plt.show() #2
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 8 –
Print the Confusion Matrix and Loss Plot of PIMA dataset and write
the value of the matrix such as precision, recall, F1 score.
Program –
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score,
recall_score, f1_score, roc_auc_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping
# Data preprocessing
df[columns] = df[columns].apply(pd.to_numeric, errors='coerce')
df.dropna(inplace=True)
# Standardize features
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y,
test_size=0.2, random_state=42)
# Build model
model = Sequential([
Dense(16, input_dim=8, activation='relu'),
Dropout(0.3),
Dense(12, activation='relu'),
Dense(8, activation='relu'),
Dense(1, activation='sigmoid')
])
# Compile model
optimizer = Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=optimizer,
metrics=['accuracy'])
# Train model
history = model.fit(X_train, y_train, epochs=150, batch_size=32,
validation_split=0.2, verbose=0, callbacks=[early_stopping])
# Predictions
y_pred = (model.predict(X_test) > 0.5).astype("int32")
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix')
plt.xlabel('Predicted')
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
plt.ylabel('True')
plt.show()
# Plot Loss
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss Plot')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# Evaluation Metrics
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_pred)
print(f"Precision: {precision:0.3F}")
print(f"Recall: {recall:0.3F}")
print(f"F1-Score: {f1:0.3F}")
print(f"ROC-AUC: {roc_auc:0.3F}")
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 9 –
Print the accuracy of ANN model using PIMA dataset with dataset
with different values of Optimizers.
List of Optimizers: Adam, RMSprop, SGD, Adadelta, Adagrad,
Nadam.
Program –
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import Adam, SGD, RMSprop,
Adadelta, Adagrad, Nadam
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42, stratify=y)
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
'RMSprop': RMSprop(),
"Adadelta": Adadelta(),
"Adagrad": Adagrad(),
"Nadam": Nadam()
results = {}
for name, optimizer in optimizers.items():
accuracy, history = create_and_train_model(optimizer)
results[name] = accuracy
print(f"Optimizer: {name}, Test Accuracy: {accuracy:.3f}")
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 10 –
Object detection with pre – trained RetinaNet with Kerras.
Program –
pip install keras-retinanet opencv-python
import numpy as np
import cv2
import matplotlib.pyplot as plt
from keras_retinanet import models
from keras_retinanet.utils.image import preprocess_image,
resize_image
from keras_retinanet.utils.visualization import draw_box,
draw_caption
from keras_retinanet.utils.colors import label_color
# Load image
image_path = r"K:\market.jpg" # Path to the image
image = cv2.imread(image_path)
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
image = preprocess_image(image)
image, scale = resize_image(image)
# Run detection
boxes, scores, labels =
model.predict_on_batch(np.expand_dims(image, axis=0))
# Visualize detections
for box, score, label in zip(boxes[0], scores[0], labels[0]):
if score < 0.5: # Adjust threshold as needed
continue
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 11 –
NEURAL RECOMMENDATION SYSTEM.
Program –
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Embedding, Flatten, Input, Dot
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
def build_model(self):
# Input layers for user, positive item, and negative item
user_input = Input(shape=(1,), name="user_input")
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
pos_item_input = Input(shape=(1,),
name="positive_item_input")
neg_item_input = Input(shape=(1,),
name="negative_item_input")
# User embedding
user_embedded = Flatten()(user_embedding(user_input))
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
epochs=epochs,
batch_size=batch_size
)
return history
# Simulate data
num_users = 1000
num_items = 1000
embedding_dim = 32
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 12 -
Implementation of Backpropagation in neural network using numpy.
Program -
import numpy as np
import matplotlib.pyplot as plt
def sigmoid_derivative(x):
return x * (1 - x)
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
self.backpropagate(X, y)
# Calculate and store loss
loss = mse_loss(y, self.output)
self.loss_history.append(loss)
# Print loss every 1000 epochs
if epoch % 1000 == 0:
print(f"Epoch {epoch}, Loss: {loss}")
def plot_loss(self):
plt.plot(self.loss_history)
plt.xlabel("Epochs")
plt.ylabel("Mean Squared Error Loss")
plt.title("Loss Over Epochs")
plt.show()
# Example usage
if __name__ == "__main__": # Corrected __name__ check
# XOR dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
Task 13 –
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
def build_model(self):
# Input layers for user, positive item, and negative item
user_input = Input(shape=(1,), name="user_input")
pos_item_input = Input(shape=(1,),
name="positive_item_input")
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
neg_item_input = Input(shape=(1,),
name="negative_item_input")
# User embedding
user_embedded = Flatten()(user_embedding(user_input))
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
batch_size=batch_size
)
return history
# Simulate data
num_users = 1000
num_items = 1000
embedding_dim = 32
Task 14 –
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 15 –
Write a program to print the accuracy of CNN using average pooling
technique.
Program –
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, AveragePooling2D,
Flatten, Dense
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
Task 16 –
Write a program to print the accuracy of CNN using global pooling
technique.
Program –
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,
GlobalAveragePooling2D, Dense
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt
2128709 SIGNATURE
BTCS - 705 Deep Learning Lab
2128709 SIGNATURE