AIML Lab 3
AIML Lab 3
import
os
import
cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
images.append(img)
labels.append(label_fold
er)
2. Label Encoding
def label_encoding(data_labels):
# ('glioma': 0 / 'meningioma': 1 / 'notumor': 2 / 'pituitary': 3)
general_labels = ['glioma', 'meningioma', 'notumor',
'pituitary']
new_data_labels =
[] for label in
data_labels:
new_data_labels.append(general_labels.index(label))
return np.array(new_data_labels)
3. Data Augmentation
figsize=(15, 15)):
fig, ax = plt.subplots(nrows=1, ncols=ncols,
figsize=figsize) for i, (img, title) in
enumerate(zip(images, titles)):
ax[i].imshow(i
mg)
ax[i].set_title(ti
tle)
ax[i].axis('off')
plt.show()
if seed != None:
np.random.seed(seed)
sample_indices = np.random.choice(len(X_train), 3,
replace=False) samples = X_train[sample_indices]
plot_images(images, titles)
if augment:
plot_augmented_samples(X_train, train_datagen)
4. Model Architectures
for f in filters[1:]:
model.add(Conv2D(filters=f, kernel_size=kernel_size, activation='relu',
padding='same')) model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten()
) for n in n_hidden:
model.add(Dense(units=n,
activation='relu'))
model.add(Dropout(dropout_rate))
model.add(Dense(units=4,
activation='softmax'))
print(model.summary())
return model
def get_model(model_type,
params): if model_type ==
'basic_cnn':
return create_basic_cnn(
input_shape=params['input_shape'],
filters=params['filters'],
kernel_size=params['kernel_size'],
pool_size=params['pool_size'],
dropout_rate=params['dropout_rate'
], n_hidden=params['n_hidden']
)
else:
raise ValueError(f"Unknown model type: {model_type}")
5. Model Evaluation
def
plot_results(history):
plt.figure(figsize=(12
, 5))
# Plot loss
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='train_loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.legend()
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Loss over
Epochs')
# Plot accuracy
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='train_accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.legend()
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Accuracy over
Epochs')
plt.tight_layout()
plt.show()
conf_matrix = confusion_matrix(encoded_y_test,
predicted_classes)
plt.figure(figsize=(8, 6))
plt.imshow(conf_matrix, cmap='Blues',
interpolation='nearest') plt.title('Confusion Matrix')
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes,
rotation=45) plt.yticks(tick_marks,
classes)
for i in range(len(classes)):
for j in range(len(classes)):
plt.text(i, j, str(conf_matrix[i, j]), ha='center', va='center')
plt.xlabel('True Labels')
plt.ylabel('Predicted
Labels') plt.show()
'pituitary']
classes]
recall = [metrics[label]['recall'] for label in
classes] f1_score = [metrics[label]['f1-score'] for
label in classes]
data = {
'Precision':
precision, 'Recall':
recall,
'F1-Score': f1_score
}
df = pd.DataFrame(data,
index=classes) plt.figure(figsize=(10,
6))
sns.heatmap(df, annot=True, cmap='Blues', fmt=".2f", linewidths=0.5)
plt.title('Classification Report')
plt.xlabel('Metrics')
plt.ylabel('Classes')
plt.show()
def evaluate_model(model,
test_generator): evaluation =
model.evaluate(test_generator)
test_loss = evaluation[0]
test_accuracy =
evaluation[1] return
test_loss, test_accuracy
6. Experiment Execution
result = {
'Model': model,
'Model Type': params['model_type'],
'With Augmentation': 'Yes' if params['augment'] else
'No', 'Input Shape': params['input_shape'],
'Epochs': params['epochs'],
'Batch Size':
params['batch_size'], 'Test
Loss': loss,
'Test Accuracy': accuracy
}
return result
7. Main Execution
experiments = [
{
'model_type':
'basic_cnn',
'dropout_rate': 0.5,
'filters': [32, 64, 128, 256, 512],
'input_shape': (224, 224, 3),
'epochs': 5,
'batch_size': 32,
'kernel_size': (3, 3),
'pool_size': (2, 2),
'n_hidden': [512],
'augment': True,
'image_size': (224,
224)
}
]
brain_dataset_training_path = '/kaggle/input/brain-tumor-mri-dataset/Training'
brain_dataset_testing_path = '/kaggle/input/brain-tumor-mri-dataset/Testing'
basic_cnn_experiments =
[] for params in
experiments:
print(f"Running experiment with parameters: {params}")
encoded_y_train = label_encoding(y_train)
encoded_y_val = label_encoding(y_val)
encoded_y_test = label_encoding(y_test)
high_epochs_experiments = pd.DataFrame(basic_cnn_experiments)
high_epochs_experiments.to_csv('/kaggle/working/basic_cnn_high_epochs_experime
nt.csv', index=False)
High_epochs_experiments
Output:
Colab Notebook Link :
https://colab.research.google.com/drive/1Y84Qce9seGr6dePfsiSZkDpSMs4g9HAR?usp=d
rive_link
1311 images of brain tumors that are used to test the model.
1.Glioma 2.meningioma 3. notumor 4. pitutary