DL Problem
DL Problem
Train a Deep Neural Network on the MNIST dataset using the Adam optimizer with a learning
rate of 0.001, and generate a classification report and ROC AUC plot.
# Compile the model using Adam optimizer with learning rate 0.001
optimizer = Adam(learning_rate=0.001)
model.compile(optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
# Predict classes
y_pred_probs = model.predict(x_test)
y_pred_classes = np.argmax(y_pred_probs, axis=1)
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred_classes))
Statement 2
Train a DNN using the SGD optimizer with a learning rate of 0.0001 on the MNIST dataset
and analyze the model's performance.
# Compile the model with SGD optimizer and low learning rate
optimizer = SGD(learning_rate=0.0001)
model.compile(optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Val Accuracy')
plt.title('Accuracy over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True)
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Loss over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Statement 3
Train a Deep Neural Network on the MNIST dataset using RMSprop optimizer with a learning
rate of 0.0001, and compare results using an accuracy table and ROC curve.
# Import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
# Plotting
metrics_df.plot(kind='bar', figsize=(8, 6), colormap='viridis')
plt.title('Precision, Recall & F1-Score for Wildfire Detection')
plt.xlabel('Class (0 = No Fire, 1 = Fire)')
plt.ylabel('Score')
plt.ylim(0, 1)
plt.grid(True)
plt.xticks(rotation=0)
plt.legend(loc='lower right')
plt.tight_layout()
plt.show()
Statement 5
Train a DNN on the Forest Fire dataset using RMSprop optimizer with a learning rate of 0.01.
Report training and validation accuracy
# Import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.utils import to_categorical
# Assuming the last column is the binary class (0: no fire, 1: fire)
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
# Feature scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Normalize features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Train-test split
x_train, x_test, y_train, y_test = train_test_split(X_scaled, y_cat, test_size=0.2, random_state=42)
# Define a function to build the model
def build_model(optimizer):
model = Sequential([
Dense(64, activation='relu', input_shape=(X.shape[1],)),
Dense(32, activation='relu'),
Dense(2, activation='softmax') # Binary classification
])
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
return model
for lr in learning_rates:
print(f"\nTraining model with learning rate = {lr}")
model = build_model()
optimizer = SGD(learning_rate=lr)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(x_train, y_train_cat, epochs=15, batch_size=128, validation_split=0.1, verbose=2)
histories[lr] = history
# Plot Loss
plt.subplot(1, 2, 1)
for lr, history in histories.items():
plt.plot(history.history['loss'], label=f'Train Loss (lr={lr})')
plt.plot(history.history['val_loss'], linestyle='--', label=f'Val Loss (lr={lr})')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
# Plot Accuracy
plt.subplot(1, 2, 2)
for lr, history in histories.items():
plt.plot(history.history['accuracy'], label=f'Train Acc (lr={lr})')
plt.plot(history.history['val_accuracy'], linestyle='--', label=f'Val Acc (lr={lr})')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Statement 8
Evaluating DNN on CIFAR-10 Using Batch Size Variation
● Load CIFAR-10 dataset
● Use a feed-forward network with BatchNormalization
● Train with batch sizes 32 and 64, keeping other parameters constant
● Use Adam optimizer and train for 10 epochs
● Compare accuracy and plot graphs
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, BatchNormalization, Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
histories[batch_size] = history
plt.subplot(1, 2, 1)
for bs, history in histories.items():
plt.plot(history.history['accuracy'], label=f'Train Acc (batch={bs})')
plt.plot(history.history['val_accuracy'], linestyle='--', label=f'Val Acc (batch={bs})')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Statement 9
Train a DNN on the UCI dataset using batch size 32 and a learning rate of 0.0001. Evaluate
training time and accuracy
import time
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
# Because quality values are integers from 3-8, we will treat this as a classification problem
# Convert target to categorical classes
# First encode labels to consecutive integers starting from 0
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
num_classes = len(np.unique(y_encoded))
y_cat = to_categorical(y_encoded, num_classes)
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y_cat, test_size=0.2, random_state=42,
stratify=y_cat)
# Feature scaling
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Build simple DNN model
def build_model():
model = Sequential([
Dense(64, input_shape=(X_train.shape[1],), activation='relu'),
Dense(32, activation='relu'),
Dense(num_classes, activation='softmax')
])
return model
# Parameters
batch_size = 32
learning_rate = 0.0001
# Compile model
model = build_model()
optimizer = SGD(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
Statement 10
Preprocess the Alphabet CSV dataset using label encoding and standard scaling, then train a
simple DNN using batch size 32 and learning rate 0.0001
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_cat, test_size=0.2, random_state=42,
stratify=y_cat)
# Parameters
batch_size = 32
learning_rate = 0.0001
# Compile model
model = build_model()
optimizer = SGD(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
# Train model
history = model.fit(X_train, y_train, epochs=30, batch_size=batch_size, validation_split=0.1,
verbose=2)
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
# Check for categorical features in X and label encode if any (usually numeric, but just in case)
for col in X.columns:
if X[col].dtype == 'object':
le = LabelEncoder()
X[col] = le.fit_transform(X[col])
# Parameters
batch_size = 64
learning_rate = 0.001
# Compile model
model = build_model()
optimizer = SGD(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
# Evaluate on test set
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"\nTest Accuracy: {test_accuracy*100:.2f}%")
Statement 12
Preprocess the Alphabet dataset and train a CNN with the architecture using Adam optimizer,
20 epochs, batch size 64, and learning rate 0.001.
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
def reshape_for_cnn(X):
n = X.shape[1]
sq = int(math.ceil(np.sqrt(n))) # smallest square side >= n
padded_size = sq*sq
X_cnn = reshape_for_cnn(X_scaled)
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X_cnn, y_cat, test_size=0.2, random_state=42,
stratify=y_cat)
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(num_classes, activation='softmax')
])
# Compile
learning_rate = 0.001
optimizer = Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
# Train
history = model.fit(X_train, y_train, epochs=20, batch_size=64, validation_split=0.1, verbose=2)
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
import time
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import History
# Load CIFAR-10
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# Normalize data
X_train = X_train.astype('float32') / 255.0
X_test = X_test.astype('float32') / 255.0
# Training parameters
batch_size = 64
epochs = 15
learning_rate = 0.001
optimizer = Adam(learning_rate=learning_rate)
# Evaluate DNN
dnn_loss, dnn_acc = dnn.evaluate(X_test, y_test_cat, verbose=0)
# Evaluate CNN
cnn_loss, cnn_acc = cnn.evaluate(X_test, y_test_cat, verbose=0)
# Print results
print(f"DNN Test Accuracy: {dnn_acc*100:.2f}% | Training time: {dnn_time:.2f} seconds")
print(f"CNN Test Accuracy: {cnn_acc*100:.2f}% | Training time: {cnn_time:.2f} seconds")
# Normalize
X_train = X_train.astype('float32') / 255.0
X_test = X_test.astype('float32') / 255.0
# Train model
history = model.fit(X_train, y_train_cat, epochs=20, batch_size=64, validation_split=0.1, verbose=2)
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 15
Implement a DNN using RMSprop with learning rates 0.01 and 0.0001 on the Wildfire dataset.
Compare training and validation performance.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.utils import to_categorical
# Split data
X_train, X_val, y_train, y_val = train_test_split(X, y_cat, test_size=0.2, random_state=42)
# Training params
batch_size = 32
epochs = 30
# Train with RMSprop lr=0.01
model_high_lr = build_model(X_train.shape[1], num_classes)
model_high_lr.compile(optimizer=RMSprop(learning_rate=0.01),
loss='categorical_crossentropy', metrics=['accuracy'])
# Plot training and validation accuracy and loss for both learning rates
plt.figure(figsize=(14, 6))
plt.subplot(1, 2, 1)
plt.plot(history_high_lr.history['accuracy'], label='Train Acc (lr=0.01)')
plt.plot(history_high_lr.history['val_accuracy'], label='Val Acc (lr=0.01)')
plt.plot(history_low_lr.history['accuracy'], label='Train Acc (lr=0.0001)')
plt.plot(history_low_lr.history['val_accuracy'], label='Val Acc (lr=0.0001)')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history_high_lr.history['loss'], label='Train Loss (lr=0.01)')
plt.plot(history_high_lr.history['val_loss'], label='Val Loss (lr=0.01)')
plt.plot(history_low_lr.history['loss'], label='Train Loss (lr=0.0001)')
plt.plot(history_low_lr.history['val_loss'], label='Val Loss (lr=0.0001)')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 16
Multiclass classification using Deep Neural Networks: Example: Use the OCR letter
recognition dataset/Alphabet.csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.metrics import classification_report
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
# Train/test split
X_train, X_test, y_train, y_test = train_test_split(X, y_cat, test_size=0.2, random_state=42)
# Standardize features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Compile model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Train model
history = model.fit(X_train, y_train, epochs=30, batch_size=64, validation_split=0.1, verbose=2)
# Classification report
print("\nClassification Report:\n")
print(classification_report(y_true, y_pred, target_names=le.classes_))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 17
Implement the training of a DNN using Adam and SGD optimizers with a learning rate of
0.001 on the Wildfire dataset. Provide comparative plots.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.utils import to_categorical
num_classes = len(np.unique(y))
y_cat = to_categorical(y, num_classes)
# Split data
X_train, X_val, y_train, y_val = train_test_split(X, y_cat, test_size=0.2, random_state=42)
# Standardize features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
# Accuracy plot
plt.subplot(1, 2, 1)
plt.plot(history_adam.history['accuracy'], label='Adam Train Acc')
plt.plot(history_adam.history['val_accuracy'], label='Adam Val Acc')
plt.plot(history_sgd.history['accuracy'], label='SGD Train Acc')
plt.plot(history_sgd.history['val_accuracy'], label='SGD Val Acc')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
# Loss plot
plt.subplot(1, 2, 2)
plt.plot(history_adam.history['loss'], label='Adam Train Loss')
plt.plot(history_adam.history['val_loss'], label='Adam Val Loss')
plt.plot(history_sgd.history['loss'], label='SGD Train Loss')
plt.plot(history_sgd.history['val_loss'], label='SGD Val Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 18
Implement a DNN using batch sizes 32 and 64 with a fixed learning rate of 0.001 on the UCI
dataset. Compare model loss and performance.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
num_classes = len(np.unique(y))
y_cat = to_categorical(y, num_classes)
# Train/test split
X_train, X_val, y_train, y_val = train_test_split(X, y_cat, test_size=0.2, random_state=42)
# Standardize features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
plt.subplot(1, 2, 1)
plt.plot(history_32.history['loss'], label='Batch Size 32 - Train Loss')
plt.plot(history_32.history['val_loss'], label='Batch Size 32 - Val Loss')
plt.plot(history_64.history['loss'], label='Batch Size 64 - Train Loss')
plt.plot(history_64.history['val_loss'], label='Batch Size 64 - Val Loss')
plt.title('Loss Comparison')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 19
Preprocess the Alphabet dataset and train both a DNN and a CNN. Use Adam optimizer with a
batch size of 64. Compare accuracy across 20 epochs.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
# Encode labels
le = LabelEncoder()
y_encoded = le.fit_transform(y)
num_classes = len(np.unique(y_encoded))
y_cat = to_categorical(y_encoded, num_classes)
# Train-test split
X_train, X_val, y_train, y_val = train_test_split(X, y_cat, test_size=0.2, random_state=42)
# Parameters
batch_size = 64
epochs = 20
learning_rate = 0.001
# Train DNN
dnn = build_dnn(X_train_scaled.shape[1], num_classes)
dnn.compile(optimizer=Adam(learning_rate=learning_rate),
loss='categorical_crossentropy', metrics=['accuracy'])
history_dnn = dnn.fit(X_train_scaled, y_train,
validation_data=(X_val_scaled, y_val),
epochs=epochs, batch_size=batch_size, verbose=2)
# Train CNN
cnn = build_cnn(X_train_cnn.shape[1:], num_classes)
cnn.compile(optimizer=Adam(learning_rate=learning_rate),
loss='categorical_crossentropy', metrics=['accuracy'])
history_cnn = cnn.fit(X_train_cnn, y_train,
validation_data=(X_val_cnn, y_val),
epochs=epochs, batch_size=batch_size, verbose=2)
dataset/
train/
class1/
class2/
...
validation/
class1/
class2/
...
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
# Image parameters
img_height, img_width = 150, 150
batch_size = 32
epochs = 10
learning_rate = 0.001
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical'
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical'
)
num_classes = len(train_generator.class_indices)
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(num_classes, activation='softmax')
])
model.compile(optimizer=Adam(learning_rate=learning_rate),
loss='categorical_crossentropy',
metrics=['accuracy'])
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 21
Implement a CNN on Tomato dataset using batch sizes of 32 and 64 separately. Keep the learning
tomato_dataset/
train/
class1/
class2/
validation/
class1/
class2/
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
def create_data_generators(batch_size):
train_datagen = ImageDataGenerator(rescale=1./255)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=True
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=False
)
return train_generator, val_generator
history_32 = model_32.fit(
train_gen_32,
validation_data=val_gen_32,
epochs=epochs,
verbose=2
)
plt.subplot(1,2,1)
plt.plot(history_32.history['val_accuracy'], label='Batch size 32')
plt.plot(history_64.history['val_accuracy'], label='Batch size 64')
plt.title('Validation Accuracy Comparison')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history_32.history['val_loss'], label='Batch size 32')
plt.plot(history_64.history['val_loss'], label='Batch size 64')
plt.title('Validation Loss Comparison')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 22
Implement CNNs using Adam and RMSprop optimizers with a learning rate of 0.001 on Peach
images. Record validation loss and accuracy.
peach_dataset/
train/
ripe/
img_001.jpg
img_002.jpg
...
unripe/
img_001.jpg
img_002.jpg
...
validation/
ripe/
img_101.jpg
img_102.jpg
...
unripe/
img_101.jpg
img_102.jpg
...
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam, RMSprop
import matplotlib.pyplot as plt
def create_data_generators(batch_size):
train_datagen = ImageDataGenerator(rescale=1./255)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=True
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=False
)
return train_generator, val_generator
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(num_classes, activation='softmax')
])
return model
history_adam = model_adam.fit(
train_gen,
validation_data=val_gen,
epochs=epochs,
verbose=2
)
history_rmsprop = model_rmsprop.fit(
train_gen,
validation_data=val_gen,
epochs=epochs,
verbose=2
)
plt.subplot(1,2,1)
plt.plot(history_adam.history['val_accuracy'], label='Adam')
plt.plot(history_rmsprop.history['val_accuracy'], label='RMSprop')
plt.title('Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history_adam.history['val_loss'], label='Adam')
plt.plot(history_rmsprop.history['val_loss'], label='RMSprop')
plt.title('Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 23
Build and train a CNN model for Apple image classification that includes Dropout layers. Train
using 15 epochs and evaluate performance.
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
import matplotlib.pyplot as plt
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=True
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=False
)
num_classes = len(train_generator.class_indices)
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5), # Dropout layer to reduce overfitting
Dense(num_classes, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Val Accuracy')
plt.title('Training & Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Training & Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 24
Split Grape image data into 70% train, 15% validation, and 15% test. Train a CNN for 10
epochs using a fixed learning rate of 0.001.
path_to_dataset/
class1/
img1.jpg
img2.jpg
class2/
img3.jpg
...
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import os
# Parameters
img_height, img_width = 150, 150
batch_size = 32
learning_rate = 0.001
epochs = 15
validation_split = 0.15 # for validation set
test_split = 0.15 # test set will be created separately below
val_test_dataset = tf.keras.utils.image_dataset_from_directory(
dataset_dir,
shuffle=True,
image_size=(img_height, img_width),
batch_size=batch_size,
validation_split=validation_split + test_split,
subset="validation",
seed=123
)
# Split val_test_dataset into validation and test sets manually
val_batches = int(len(val_test_dataset)*validation_split/(validation_split + test_split))
val_dataset = val_test_dataset.take(val_batches)
test_dataset = val_test_dataset.skip(val_batches)
model = models.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=(img_height, img_width, 3)),
layers.MaxPooling2D(2,2),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Conv2D(128, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes, activation='softmax')
])
# Compile model
model.compile(
optimizer=Adam(learning_rate=learning_rate),
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train model
history = model.fit(
full_dataset,
validation_data=val_dataset,
epochs=epochs
)
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Acc')
plt.plot(history.history['val_accuracy'], label='Val Acc')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 25
Use LeNet architecture to classify the Cats and Dogs dataset, and plot training loss and
accuracy curves.
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
import os
# Parameters
img_height, img_width = 32, 32 # LeNet input size is 32x32 grayscale; we keep RGB and resize to
32x32
batch_size = 32
epochs = 15
learning_rate = 0.001
val_ds = tf.keras.utils.image_dataset_from_directory(
dataset_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size
)
model = LeNet()
# Compile model
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train model
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Acc')
plt.plot(history.history['val_accuracy'], label='Val Acc')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 26
Use MobileNet architecture perform transfer learning on the Cats and Dogs dataset, and
evaluate model performance using a classification report.
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.applications import MobileNet
from tensorflow.keras.applications.mobilenet import preprocess_input
from tensorflow.keras.preprocessing import image_dataset_from_directory
from sklearn.metrics import classification_report
import numpy as np
import os
# Parameters
img_height, img_width = 224, 224 # MobileNet default input size
batch_size = 32
epochs = 10
learning_rate = 0.0001
val_ds = image_dataset_from_directory(
dataset_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size
)
# Load MobileNet base model with pretrained weights, exclude top layers
base_model = MobileNet(input_shape=(img_height, img_width, 3),
include_top=False,
weights='imagenet')
# Compile model
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Continue training
fine_tune_epochs = 5
total_epochs = epochs + fine_tune_epochs
history_fine = model.fit(train_ds,
validation_data=val_ds,
epochs=total_epochs,
initial_epoch=history.epoch[-1])
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
# Flatten labels
y_train = y_train.flatten()
y_test = y_test.flatten()
num_classes = 10
# Train CNN
cnn_model = build_cnn()
print("Training CNN model...")
cnn_history = compile_and_train(cnn_model)
# Train DNN
dnn_model = build_dnn()
print("\nTraining DNN model...")
dnn_history = compile_and_train(dnn_model)
# Accuracy plot
plt.subplot(1,2,1)
plt.plot(cnn_history.history['accuracy'], label='CNN Train Acc')
plt.plot(cnn_history.history['val_accuracy'], label='CNN Val Acc')
plt.plot(dnn_history.history['accuracy'], label='DNN Train Acc')
plt.plot(dnn_history.history['val_accuracy'], label='DNN Val Acc')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
# Loss plot
plt.subplot(1,2,2)
plt.plot(cnn_history.history['loss'], label='CNN Train Loss')
plt.plot(cnn_history.history['val_loss'], label='CNN Val Loss')
plt.plot(dnn_history.history['loss'], label='DNN Train Loss')
plt.plot(dnn_history.history['val_loss'], label='DNN Val Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
Statement 28
Implement an RNN on the GOOGL.csv dataset and compare its training time and loss curve
with an LSTM model.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, LSTM, Dense
from tensorflow.keras.optimizers import Adam
# Load the GOOGL.csv dataset (make sure it's in the working directory)
data = pd.read_csv('GOOGL.csv')
# Assuming dataset has 'Date' and 'Close' columns; focus on 'Close' prices
close_prices = data['Close'].values.reshape(-1, 1)
SEQ_LENGTH = 20
X, y = create_sequences(scaled_close, SEQ_LENGTH)
# Train RNN
print("Training Simple RNN model...")
rnn_model = build_rnn()
rnn_history, rnn_time = train_model(rnn_model)
# Train LSTM
print("\nTraining LSTM model...")
lstm_model = build_lstm()
lstm_history, lstm_time = train_model(lstm_model)
cats_and_dogs/
├── train/
│ ├── cats/
│ └── dogs/
├── validation/
│ ├── cats/
│ └── dogs/
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import VGG16
from tensorflow.keras.layers import Flatten, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np
import os
# Parameters
IMG_SIZE = (224, 224)
BATCH_SIZE = 32
EPOCHS = 10
LEARNING_RATE = 0.0001
# Data Generators
train_datagen = ImageDataGenerator(
rescale=1./255,
horizontal_flip=True,
rotation_range=15,
zoom_range=0.1
)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode='binary'
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode='binary',
shuffle=False
)
# Compile model
model.compile(optimizer=Adam(learning_rate=LEARNING_RATE),
loss='binary_crossentropy',
metrics=['accuracy'])
# Train model
history = model.fit(
train_generator,
epochs=EPOCHS,
validation_data=val_generator
)
# Predict on validation data
val_generator.reset()
preds = model.predict(val_generator)
predicted_classes = (preds > 0.5).astype(int).reshape(-1)
# True classes
true_classes = val_generator.classes
# Classification report
target_names = list(train_generator.class_indices.keys())
print(classification_report(true_classes, predicted_classes, target_names=target_names))
potato_dataset/
├── class1/
├── class2/
└── ...
# Define dataset path - update this to your local Potato dataset directory
dataset_dir = 'potato_dataset' # should contain subfolders for each class
# Parameters
IMG_SIZE = (128, 128)
BATCH_SIZE = 32
EPOCHS = 5
# Data generators with simple augmentation for training, rescale only for validation
train_datagen = ImageDataGenerator(
rescale=1./255,
validation_split=0.2
)
train_generator = train_datagen.flow_from_directory(
dataset_dir,
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode='categorical',
subset='training',
shuffle=True
)
val_generator = train_datagen.flow_from_directory(
dataset_dir,
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode='categorical',
subset='validation',
shuffle=False
)
plot_sample_images(train_generator)
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(train_generator.num_classes, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train model
history = model.fit(
train_generator,
epochs=EPOCHS,
validation_data=val_generator
)
Statement 31
Implement LSTM models on GOOGL.csv with learning rates 0.001 and 0.0001 for 20 and 50
epochs. Compare accuracy and convergence.
your_project_folder/
├── GOOGL.csv
├── lstm_googl.py # (your code file, if saving separately)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
# Load dataset
df = pd.read_csv('GOOGL.csv') # Ensure file is in your working directory
df = df[['Date', 'Close']]
df['Date'] = pd.to_datetime(df['Date'])
df.sort_values('Date', inplace=True)
df.dropna(inplace=True)
time_steps = 60
X, y = create_sequences(scaled_data, time_steps)
histories = []
project_folder/
├── tomato_data/
│ ├── train/
│ │ ├── class1/
│ │ └── class2/
│ ├── val/
│ │ ├── class1/
│ │ └── class2/
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
# Constants
IMG_SIZE = (128, 128)
EPOCHS = 10
LEARNING_RATE = 0.0001
DATA_DIR = 'tomato_data' # Adjust path if needed
# Data preparation
datagen = ImageDataGenerator(rescale=1./255)
train_batches = {}
val_batches = {}
val_batches[batch_size] = datagen.flow_from_directory(
DATA_DIR + '/val',
target_size=IMG_SIZE,
batch_size=batch_size,
class_mode='categorical',
shuffle=False
)
# Plot results
for metric in ['loss', 'accuracy']:
plt.figure(figsize=(8, 5))
for batch_size in [32, 64]:
plt.plot(histories[batch_size].history[metric], label=f'Train {metric} (BS={batch_size})')
plt.plot(histories[batch_size].history['val_' + metric], linestyle='--', label=f'Val {metric}
(BS={batch_size})')
plt.title(f'CNN {metric.capitalize()} Comparison')
plt.xlabel('Epochs')
plt.ylabel(metric.capitalize())
plt.legend()
plt.grid(True)
plt.show()
Statement 34
Implement CNN model on Potato leaf images using the Adam optimizer and i Use a learning rate
of
project_folder/
├── potato_data/
│ ├── train/
│ │ ├── class1/
│ │ └── class2/
│ └── val/
│ ├── class1/
│ └── class2/
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np
# Constants
IMG_SIZE = (128, 128)
BATCH_SIZE = 32
EPOCHS = 10
LEARNING_RATE = 0.001
DATA_DIR = 'potato_data' # change to your dataset path
# Image preprocessing
datagen = ImageDataGenerator(rescale=1./255)
train_gen = datagen.flow_from_directory(
DATA_DIR + '/train',
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode='categorical',
shuffle=True
)
val_gen = datagen.flow_from_directory(
DATA_DIR + '/val',
target_size=IMG_SIZE,
batch_size=BATCH_SIZE,
class_mode='categorical',
shuffle=False
)
# Classification Report
val_gen.reset()
y_pred = model.predict(val_gen)
y_pred_classes = np.argmax(y_pred, axis=1)
y_true = val_gen.classes
class_labels = list(val_gen.class_indices.keys())
print("\nClassification Report:")
print(classification_report(y_true, y_pred_classes, target_names=class_labels))
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
Statement 35
Build a Deep Neural Network for Fashion MNIST Classification
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
# Accuracy plot
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Acc')
plt.plot(history.history['val_accuracy'], label='Val Acc')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
# Loss plot
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()