# -*- coding: utf-8 -*-
"""MobileNetV2.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1cVqTJDrIafvX5fVGEhNFIalhfpA4H-Pn
"""



"""**1**- Connect To Google Drive"""

from google.colab import drive
drive.mount('/content/drive')

"""2- Install Packages"""

!pip install tensorflow
!pip install opencv-python
!pip install scikit-image
!pip install numpy pandas
!pip install matplotlib seaborn
!pip install scikit-learn

"""3- Import Libraries"""

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, models
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import cv2
from PIL import Image
import glob
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.applications import MobileNetV2


"""4- Extract Training **Dataset**"""

train_path = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Training"
train_ds_raw = tf.keras.utils.image_dataset_from_directory(
    train_path,
    image_size=(224, 224),
    batch_size=16,
    shuffle=True
)

"""5- Save category names"""

class_names = train_ds_raw.class_names
print(class_names)

"""6- Extract Testing **Dataset**"""

test_path = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Testing"

test_ds_raw = tf.keras.utils.image_dataset_from_directory(
    test_path,
    image_size=(224, 224),
    batch_size=16,
    shuffle=False
)

"""7- To confirm GPU is enabled"""

tf.config.list_physical_devices('GPU')

""":8- **Preprocessing** (Normalization , Augmentation)

"""

#Normalization(Converting values ​​from 0–255 to 0–1)
normalization_layer = tf.keras.layers.Rescaling(1./255)
train_ds = train_ds_raw.map(lambda x, y: (normalization_layer(x), y))
test_ds = test_ds_raw.map(lambda x, y: (normalization_layer(x), y))

# Augmentation (to reduce overfitting)
data_augmentation = tf.keras.Sequential([
    tf.keras.layers.RandomFlip("horizontal"),
    tf.keras.layers.RandomRotation(0.1),
    tf.keras.layers.RandomZoom(0.1),
    tf.keras.layers.RandomContrast(0.1),

])

# Load MobileNetV2

from tensorflow.keras.applications import MobileNetV2

base_model = MobileNetV2(
    weights='imagenet',
    include_top=False,
    input_shape=(224, 224, 3)
)

base_model.trainable = False


# Build the model

model = models.Sequential([
    data_augmentation,
    layers.Rescaling(1./255),
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.4),
    layers.Dense(4, activation='softmax')
])

"""9- Display MRI"""

import matplotlib.pyplot as plt

images, labels = next(iter(train_ds_raw))

plt.figure(figsize=(10, 10))
for i in range(9):
    plt.subplot(3, 3, i + 1)
    plt.imshow(images[i].numpy().astype("uint8"))
    plt.title(class_names[labels[i]])
    plt.axis("off")

plt.show()

"""10- Count the number of images in each folder"""

import os
import matplotlib.pyplot as plt


train_path = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Training"

# Obtaining the names of categories (folders)
categories = os.listdir(train_path)

# Count the number of images in each category
counts = {}
for category in categories:
    folder_path = os.path.join(train_path, category)
    counts[category] = len(os.listdir(folder_path))

counts

"""11- drawing a diagram"""

plt.figure(figsize=(10, 6))
plt.bar(counts.keys(), counts.values(), color=['#4C72B0', '#55A868', '#C44E52', '#8172B2'])
plt.title("Number of images in training data")
plt.xlabel("Category")
plt.ylabel(" Number of images")
plt.xticks(rotation=45)
plt.show()

"""12- Count the number of images in each folder"""

test_path = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Testing"

categories_test = os.listdir(test_path)

test_counts = {}
for category in categories_test:
    folder_path = os.path.join(test_path, category)
    test_counts[category] = len(os.listdir(folder_path))

test_counts

"""13- drawing a diagram Testing data"""

plt.figure(figsize=(10, 6))
plt.bar(test_counts.keys(), test_counts.values(),
        color=['#4C72B0', '#55A868', '#C44E52', '#8172B2'])
plt.title("Number of images in testing data")
plt.xlabel("Category")
plt.ylabel("Number of image")
plt.xticks(rotation=45)
plt.show()

"""14- To make training faster and smoother"""

AUTOTUNE = tf.data.AUTOTUNE

train_ds = train_ds.shuffle(1000).prefetch(buffer_size=AUTOTUNE)
test_ds = test_ds.prefetch(buffer_size=AUTOTUNE)

"""15- Download MobileNetV2(Feature Extractor)"""

base_model = MobileNetV2(
    weights='imagenet',
    include_top=False,
    input_shape=(224, 224, 3)
)
#Freezing the layers
base_model.trainable = False

"""16- Building classification layers"""

model = models.Sequential([
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.4),
    layers.Dense(4, activation='softmax')
])


model.summary()

"""17- Compile"""

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

"""18- Training Model"""

import time

start_time = time.time()

history = model.fit(
    train_ds,
    validation_data=test_ds,
    epochs=4
)

end_time = time.time()

elapsed_time = end_time - start_time

minutes = elapsed_time // 60
seconds = elapsed_time % 60

print(f"Training time: {int(minutes)} min {int(seconds)} sec")

"""19- Drawing Accuracy and Loss Curves"""

import matplotlib.pyplot as plt

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(len(acc))

plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend()
plt.title('Accuracy MobileNetV2')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend()
plt.title('Loss MobileNetV2')

plt.show()

"""Evaluate Model"""

test_loss, test_acc = model.evaluate(test_ds)
print("Test Accuracy:", test_acc)

img_size = 224
batch_size = 16


test_dir = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Testing"   


test_datagen = ImageDataGenerator(rescale=1./255)

test_generator = test_datagen.flow_from_directory(
    test_dir,
    target_size=(img_size, img_size),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=False
)

"""21- Confusion Matrix"""

import numpy as np
import matplotlib.pyplot as plt
import itertools
from sklearn.metrics import confusion_matrix, classification_report

classes = list(test_generator.class_indices.keys())


y_pred_probs = model.predict(test_generator)
y_pred = np.argmax(y_pred_probs, axis=1)



y_true = test_generator.classes



cm = confusion_matrix(y_true, y_pred)

print("Classification Report:")
print(classification_report(y_true, y_pred, target_names=classes))



def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    if normalize:
        cm = cm.astype('float') / (cm.sum(axis=1)[:, np.newaxis] + 1e-8)

    plt.figure(figsize=(6, 6))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()


plot_confusion_matrix(cm, classes, normalize=False, title="Confusion Matrix MobileNetV2")
plt.show()

"""Classification Report"""



"""22- Prediction for one img"""

import cv2

img_path = "/content/drive/MyDrive/Te-no_107.jpg"

img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224))
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0

prediction = model.predict(img_array)
pred_class = class_names[np.argmax(prediction)]

print("Prediction:", pred_class)









part2 efficientnet

# -*- coding: utf-8 -*-
"""efficientnet.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1VJsqTJThst4GKJ8jEIwCVdU1EFm8QA_1
"""



"""Conncet to Google drive"""

from google.colab import drive
drive.mount('/content/drive')

"""Lib"""

import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory
from tensorflow.keras.applications import EfficientNetB0
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
import os

"""Dataset path"""

dataset_path = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)"

train_dir = os.path.join(dataset_path, "Training")
test_dir = os.path.join(dataset_path, "Testing")


img_size = (224, 224)
batch_size = 32

train_ds = image_dataset_from_directory(
    train_dir,
    validation_split=0.2,
    subset="training",
    seed=42,
    image_size=img_size,
    batch_size=batch_size
)

val_ds = image_dataset_from_directory(
    train_dir,
    validation_split=0.2,
    subset="validation",
    seed=42,
    image_size=img_size,
    batch_size=batch_size
)

test_ds = image_dataset_from_directory(
    test_dir,
    image_size=img_size,
    batch_size=batch_size
)
class_names = test_ds.class_names

"""Prefetching"""

AUTOTUNE = tf.data.AUTOTUNE

train_ds = train_ds.prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.prefetch(buffer_size=AUTOTUNE)
test_ds = test_ds.prefetch(buffer_size=AUTOTUNE)

"""Data augmentation"""

data_augmentation = tf.keras.Sequential([
    layers.RandomFlip("horizontal"),
    layers.RandomRotation(0.1),
    layers.RandomZoom(0.1),
    layers.RandomContrast(0.1),
])

"""Built EfficientNetB0

"""

base_model = EfficientNetB0(
    weights="imagenet",
    include_top=False,
    input_shape=(224, 224, 3)
)

base_model.trainable = False   
model = models.Sequential([
    data_augmentation,
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dropout(0.3),
    layers.Dense(4, activation="softmax")   
])

model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

model.summary()

"""Training model"""

import time

start_time = time.time()

history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=16
)

end_time = time.time()

elapsed_time = end_time - start_time

minutes = elapsed_time // 60
seconds = elapsed_time % 60

print(f"Training time: {int(minutes)} min {int(seconds)} sec")

"""Evaluatetion"""

test_loss, test_acc = model.evaluate(test_ds)
print("Test Accuracy:", test_acc)

test_ds = image_dataset_from_directory(
    test_dir,
    image_size=img_size,
    batch_size=batch_size
)


class_names = test_ds.class_names


class_names = test_ds.class_names

test_ds = test_ds.prefetch(tf.data.AUTOTUNE)

"""Accuracy and Loss"""

plt.figure(figsize=(12,5))

plt.subplot(1,2,1)
plt.plot(history.history["accuracy"], label="Train Acc")
plt.plot(history.history["val_accuracy"], label="Val Acc")
plt.legend()
plt.title("Accuracy")

plt.subplot(1,2,2)
plt.plot(history.history["loss"], label="Train Loss")
plt.plot(history.history["val_loss"], label="Val Loss")
plt.legend()
plt.title("Loss")

plt.show()

"""Confusion Matrix"""

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report



y_true = []
for images, labels in test_ds:
    y_true.extend(labels.numpy())
y_true = np.array(y_true)


y_pred = model.predict(test_ds)
y_pred = np.argmax(y_pred, axis=1)

import numpy as np
import matplotlib.pyplot as plt
import itertools
from sklearn.metrics import confusion_matrix, classification_report
import os

class_names = sorted(os.listdir(test_dir))
print(class_names)

y_true = []
y_pred = []

for images, labels in test_ds:
    preds = model.predict(images)
    y_pred.extend(np.argmax(preds, axis=1))
    y_true.extend(labels.numpy())  

y_true = np.array(y_true, dtype=int)
y_pred = np.array(y_pred, dtype=int)





cm = confusion_matrix(y_true, y_pred)
print("Classification Report:")
print(classification_report(y_true, y_pred, target_names=class_names))


def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):

    if normalize:
        cm = cm.astype('float') / (cm.sum(axis=1)[:, np.newaxis] + 1e-8)

    plt.figure(figsize=(6, 6))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()


plot_confusion_matrix(cm, class_names, normalize=False, title="Confusion Matrix")
plt.show()

""" Prediction for one img"""

import cv2

img_path = "/content/drive/MyDrive/Te-no_107.jpg"

img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224))
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0

prediction = model.predict(img_array)
pred_class = class_names[np.argmax(prediction)]

print("Prediction:", pred_class)










part3 InceptionV3

# -*- coding: utf-8 -*-
"""InceptionV3.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1vEZOy6pq7-7KvdZVJxtOF2kGMaeTS19z
"""



"""1- Connect To Google Drive"""

from google.colab import drive
drive.mount('/content/drive')

"""- Install Packages"""

!pip install tensorflow
!pip install opencv-python
!pip install scikit-image
!pip install numpy pandas
!pip install matplotlib seaborn
!pip install scikit-learn

"""3- Import Libraries"""

import os
import numpy as np
import matplotlib.pyplot as plt
import itertools

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import InceptionV3
from tensorflow.keras.applications.inception_v3 import preprocess_input
from tensorflow.keras import layers, models, optimizers
from sklearn.metrics import confusion_matrix, classification_report

"""Extract Training Dataset"""

train_dir = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Training"

img_height = 224
img_width = 224
batch_size = 32

train_datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input
)

train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode="categorical",
    shuffle=True
)

"""Save category names"""

class_indices = train_generator.class_indices
classes = list(class_indices.keys())
num_classes = len(classes)

print("Class indices:", class_indices)
print("Classes:", classes)

"""Extract Testing Dataset"""

test_dir = "/content/drive/MyDrive/Kaggle Brain Tumor Classification (MRI)/archive (1)/Testing"

test_datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input
)

test_generator = test_datagen.flow_from_directory(
    test_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode="categorical",
    shuffle=False
)

""" Preprocessing (Normalization, Augmentation)


"""

train_aug_datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input,
    rotation_range=15,
    width_shift_range=0.1,
    height_shift_range=0.1,
    zoom_range=0.1,
    horizontal_flip=True,
    fill_mode="nearest"
)

train_aug_generator = train_aug_datagen.flow_from_directory(
    train_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode="categorical",
    shuffle=True
)

"""To make training faster and smoother (GPU)"""

from tensorflow.keras import mixed_precision

policy = mixed_precision.Policy('mixed_float16')
mixed_precision.set_global_policy(policy)

print("Compute dtype:", policy.compute_dtype)
print("Variable dtype:", policy.variable_dtype)

"""Download InceptionV3 (base model)"""

base_model = InceptionV3(
    weights="imagenet",
    include_top=False,
    input_shape=(img_height, img_width, 3)
)

base_model.trainable = False
base_model.summary()

"""Building classification layers"""

inputs = tf.keras.Input(shape=(img_height, img_width, 3))
x = base_model(inputs, training=False)
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dropout(0.4)(x)
x = layers.Dense(256, activation="relu")(x)
x = layers.Dropout(0.3)(x)
outputs = layers.Dense(num_classes, activation="softmax", dtype="float32")(x)

model = models.Model(inputs, outputs)
model.summary()

"""Compile"""

learning_rate = 1e-4

model.compile(
    optimizer=optimizers.Adam(learning_rate=learning_rate),
    loss="categorical_crossentropy",
    metrics=["accuracy"]
)

"""Training Model"""

import time

start_time = time.time()

epochs = 8

history = model.fit(
    train_aug_generator,
    epochs=epochs,
    validation_data=test_generator
)

end_time = time.time()

elapsed_time = end_time - start_time

minutes = elapsed_time // 60
seconds = elapsed_time % 60

print(f"Training time: {int(minutes)} min {int(seconds)} sec")

"""Drawing Accuracy and Loss Curves


"""

acc = history.history["accuracy"]
val_acc = history.history["val_accuracy"]
loss = history.history["loss"]
val_loss = history.history["val_loss"]
epochs_range = range(len(acc))

plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label="Train Accuracy")
plt.plot(epochs_range, val_acc, label="Val Accuracy")
plt.legend()
plt.title("Accuracy")

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label="Train Loss")
plt.plot(epochs_range, val_loss, label="Val Loss")
plt.legend()
plt.title("Loss")

plt.tight_layout()
plt.show()

"""Evaluate"""

test_loss, test_acc = model.evaluate(test_generator)
print(f"Test Loss: {test_loss:.4f}")
print(f"Test Accuracy: {test_acc:.4f}")

"""Model Confusion Matrix"""



y_pred_probs = model.predict(test_generator)
y_pred = np.argmax(y_pred_probs, axis=1)
y_true = test_generator.classes

cm = confusion_matrix(y_true, y_pred)
print("Classification Report:")
print(classification_report(y_true, y_pred, target_names=classes))

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    if normalize:
        cm = cm.astype('float') / (cm.sum(axis=1)[:, np.newaxis] + 1e-8)

    plt.figure(figsize=(6, 6))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()

plot_confusion_matrix(cm, classes, normalize=False, title="Confusion Matrix")
plt.show()

"""Prediction for one img"""

from tensorflow.keras.preprocessing import image

img_path = "/content/drive/MyDrive/glioma.jpg"

img = image.load_img(img_path, target_size=(img_height, img_width))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)

pred_probs = model.predict(img_array)[0]
pred_class_idx = np.argmax(pred_probs)
pred_class_name = classes[pred_class_idx]
pred_conf = pred_probs[pred_class_idx]

print("Predicted class:", pred_class_name)
print("Confidence:", float(pred_conf))

plt.imshow(img)
plt.title(f"Prediction: {pred_class_name} ({pred_conf:.2f})")
plt.axis("off")
plt.show()