# ================================================================
# CNN ON HANDWRITTEN MNIST (train.csv / test.csv)
# ================================================================

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import classification_report, confusion_matrix

SEED = 42
np.random.seed(SEED)
tf.random.set_seed(SEED)

TRAIN_PATH = "/content/train.csv"     # change to your path
TEST_PATH = "/content/test.csv"       # change to your path
CLASS_NAMES = [str(d) for d in range(10)]
NUM_CLASSES = len(CLASS_NAMES)

# ================================================================
# STAGE A: LOADING AND PREPROCESSING THE IMAGE DATA
# ================================================================
train_df = pd.read_csv(TRAIN_PATH)
test_df = pd.read_csv(TEST_PATH)

def prepare(df):
    y = df["label"].values
    X = df.drop(columns=["label"]).values.astype("float32") / 255.0
    X = X.reshape((-1, 28, 28, 1))                     # rows -> 28x28 grayscale images
    return X, to_categorical(y, NUM_CLASSES), y

x_train, y_train, _ = prepare(train_df)
x_test, y_test, y_test_idx = prepare(test_df)

print("Train:", x_train.shape, " Test:", x_test.shape)

# Sample images
plt.figure(figsize=(10, 4))
for i in range(10):
    plt.subplot(2, 5, i + 1)
    plt.imshow(x_train[i].reshape(28, 28), cmap="gray")
    plt.title(f"Label: {train_df['label'].iloc[i]}")
    plt.axis("off")
plt.suptitle("Sample MNIST digits")
plt.tight_layout()
plt.show()

# ================================================================
# STAGE B: DEFINING THE MODEL'S ARCHITECTURE
# ================================================================
model = models.Sequential([
    layers.Input(shape=(28, 28, 1)),
    layers.Conv2D(32, (3, 3), activation="relu", padding="same"),
    layers.MaxPooling2D((2, 2)),                       # 28x28 -> 14x14
    layers.Conv2D(64, (3, 3), activation="relu", padding="same"),
    layers.MaxPooling2D((2, 2)),                       # 14x14 -> 7x7
    layers.Flatten(),
    layers.Dense(128, activation="relu"),
    layers.Dropout(0.5),
    layers.Dense(NUM_CLASSES, activation="softmax"),
])
model.summary()

# ================================================================
# STAGE C: TRAINING THE MODEL
# ================================================================
model.compile(optimizer="adam",
              loss="categorical_crossentropy",
              metrics=["accuracy"])

history = model.fit(x_train, y_train,
                    validation_split=0.1,
                    epochs=10,
                    batch_size=128,
                    verbose=1)

# ================================================================
# STAGE D: ESTIMATING THE MODEL'S PERFORMANCE
# ================================================================
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest loss: {test_loss:.4f}   Test accuracy: {test_acc:.4f}")

y_pred = model.predict(x_test, verbose=0).argmax(axis=1)
print("\nClassification Report:")
print(classification_report(y_test_idx, y_pred, target_names=CLASS_NAMES))

# Confusion matrix
cm = confusion_matrix(y_test_idx, y_pred)
plt.figure(figsize=(7, 6))
plt.imshow(cm, cmap="Blues")
plt.colorbar()
plt.xticks(range(NUM_CLASSES), CLASS_NAMES)
plt.yticks(range(NUM_CLASSES), CLASS_NAMES)
plt.xlabel("Predicted"); plt.ylabel("True")
plt.title("Confusion Matrix (MNIST CNN)")
plt.tight_layout()
plt.savefig("mnist_cnn_confusion.png", dpi=150)
plt.show()

# Training curves
epochs_range = range(1, len(history.history["loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
ax1.plot(epochs_range, history.history["loss"], label="train_loss")
ax1.plot(epochs_range, history.history["val_loss"], label="val_loss")
ax1.set_title("Loss"); ax1.set_xlabel("Epoch"); ax1.legend(); ax1.grid(True)
ax2.plot(epochs_range, history.history["accuracy"], label="train_acc")
ax2.plot(epochs_range, history.history["val_accuracy"], label="val_acc")
ax2.set_title("Accuracy"); ax2.set_xlabel("Epoch"); ax2.legend(); ax2.grid(True)
fig.suptitle("CNN Training History on MNIST")
plt.tight_layout()
plt.savefig("mnist_cnn_training.png", dpi=150)
plt.show()

# ================================================================
# CNN ON CIFAR-10 (cifar10.csv)
# ================================================================

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix

SEED = 42
np.random.seed(SEED)
tf.random.set_seed(SEED)

CSV_PATH = "/content/cifar10.csv"     # change to your path
CLASS_NAMES = ["airplane", "automobile", "bird", "cat", "deer",
               "dog", "frog", "horse", "ship", "truck"]
NUM_CLASSES = len(CLASS_NAMES)

# ================================================================
# STAGE A: LOADING AND PREPROCESSING THE IMAGE DATA
# ================================================================
df = pd.read_csv(CSV_PATH)
label_col = "label" if "label" in df.columns else df.columns[0]
y = df[label_col].values.astype("int64")
pixel_cols = [c for c in df.columns if c != label_col and c.lower() != "id"]
X = df[pixel_cols].values.astype("float32")
assert X.shape[1] == 3072, f"Expected 3072 pixel columns, found {X.shape[1]}"

# Each row is 1024 red, 1024 green, 1024 blue -> (32, 32, 3) image
X = X.reshape((-1, 3, 32, 32)).transpose(0, 2, 3, 1) / 255.0

# 80/20 split, keeping class proportions
x_train, x_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=SEED)

y_train_cat = to_categorical(y_train, NUM_CLASSES)
y_test_cat = to_categorical(y_test, NUM_CLASSES)

print("Train:", x_train.shape, " Test:", x_test.shape)

# Sample images
plt.figure(figsize=(10, 4))
for i in range(10):
    plt.subplot(2, 5, i + 1)
    plt.imshow(x_train[i])
    plt.title(CLASS_NAMES[y_train[i]], fontsize=9)
    plt.axis("off")
plt.suptitle("Sample CIFAR-10 images")
plt.tight_layout()
plt.show()

# ================================================================
# STAGE B: DEFINING THE MODEL'S ARCHITECTURE
# ================================================================
model = models.Sequential([
    layers.Input(shape=(32, 32, 3)),
    layers.Conv2D(32, (3, 3), activation="relu", padding="same"),
    layers.MaxPooling2D((2, 2)),                       # 32x32 -> 16x16
    layers.Conv2D(64, (3, 3), activation="relu", padding="same"),
    layers.MaxPooling2D((2, 2)),                       # 16x16 -> 8x8
    layers.Flatten(),
    layers.Dense(128, activation="relu"),
    layers.Dropout(0.5),
    layers.Dense(NUM_CLASSES, activation="softmax"),
])
model.summary()

# ================================================================
# STAGE C: TRAINING THE MODEL
# ================================================================
model.compile(optimizer="adam",
              loss="categorical_crossentropy",
              metrics=["accuracy"])

history = model.fit(x_train, y_train_cat,
                    validation_split=0.1,
                    epochs=20,
                    batch_size=64,
                    verbose=1)

# ================================================================
# STAGE D: ESTIMATING THE MODEL'S PERFORMANCE
# ================================================================
test_loss, test_acc = model.evaluate(x_test, y_test_cat, verbose=0)
print(f"\nTest loss: {test_loss:.4f}   Test accuracy: {test_acc:.4f}")

y_pred = model.predict(x_test, verbose=0).argmax(axis=1)
print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=CLASS_NAMES))

# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(8, 7))
plt.imshow(cm, cmap="Blues")
plt.colorbar()
plt.xticks(range(NUM_CLASSES), CLASS_NAMES, rotation=45)
plt.yticks(range(NUM_CLASSES), CLASS_NAMES)
plt.xlabel("Predicted"); plt.ylabel("True")
plt.title("Confusion Matrix (CIFAR-10 CNN)")
plt.tight_layout()
plt.savefig("cifar10_cnn_confusion.png", dpi=150)
plt.show()

# Training curves
epochs_range = range(1, len(history.history["loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
ax1.plot(epochs_range, history.history["loss"], label="train_loss")
ax1.plot(epochs_range, history.history["val_loss"], label="val_loss")
ax1.set_title("Loss"); ax1.set_xlabel("Epoch"); ax1.legend(); ax1.grid(True)
ax2.plot(epochs_range, history.history["accuracy"], label="train_acc")
ax2.plot(epochs_range, history.history["val_accuracy"], label="val_acc")
ax2.set_title("Accuracy"); ax2.set_xlabel("Epoch"); ax2.legend(); ax2.grid(True)
fig.suptitle("CNN Training History on CIFAR-10")
plt.tight_layout()
plt.savefig("cifar10_cnn_training.png", dpi=150)
plt.show()

# ================================================================
# CNN ON SIGN LANGUAGE MNIST (train.csv / test.csv)
# ================================================================

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import classification_report, confusion_matrix

SEED = 42
np.random.seed(SEED)
tf.random.set_seed(SEED)

TRAIN_PATH = "/content/train.csv"     # change to your path
TEST_PATH = "/content/test.csv"       # change to your path

LETTERS = "ABCDEFGHIKLMNOPQRSTUVWXY"  # no J or Z

# ================================================================
# STAGE A: LOADING AND PREPROCESSING THE IMAGE DATA
# ================================================================
train_df = pd.read_csv(TRAIN_PATH)
test_df = pd.read_csv(TEST_PATH)

# Labels skip 9 (J) and 25 (Z), so map them to 0..23 for to_categorical
unique_labels = sorted(train_df["label"].unique())
label_to_idx = {v: i for i, v in enumerate(unique_labels)}
NUM_CLASSES = len(unique_labels)                       # should be 24
class_names = [LETTERS[i] for i in range(NUM_CLASSES)]

def prepare(df):
    y = df["label"].map(label_to_idx).values
    X = df.drop(columns=["label"]).values.astype("float32") / 255.0
    X = X.reshape((-1, 28, 28, 1))                     # rows -> 28x28 grayscale images
    return X, to_categorical(y, NUM_CLASSES)

x_train, y_train = prepare(train_df)
x_test, y_test = prepare(test_df)
y_test_idx = y_test.argmax(axis=1)                     # integer labels for reports

print("Train:", x_train.shape, " Test:", x_test.shape)
print("Number of classes:", NUM_CLASSES)

# Sample images
plt.figure(figsize=(10, 4))
for i in range(10):
    plt.subplot(2, 5, i + 1)
    plt.imshow(x_train[i].reshape(28, 28), cmap="gray")
    plt.title(class_names[y_train[i].argmax()])
    plt.axis("off")
plt.suptitle("Sample Sign Language MNIST images")
plt.tight_layout()
plt.show()

# ================================================================
# STAGE B: DEFINING THE MODEL'S ARCHITECTURE
# ================================================================
model = models.Sequential([
    layers.Input(shape=(28, 28, 1)),
    layers.Conv2D(32, (3, 3), activation="relu", padding="same"),
    layers.MaxPooling2D((2, 2)),                       # 28x28 -> 14x14
    layers.Conv2D(64, (3, 3), activation="relu", padding="same"),
    layers.MaxPooling2D((2, 2)),                       # 14x14 -> 7x7
    layers.Flatten(),
    layers.Dense(128, activation="relu"),
    layers.Dropout(0.5),
    layers.Dense(NUM_CLASSES, activation="softmax"),
])
model.summary()

# ================================================================
# STAGE C: TRAINING THE MODEL
# ================================================================
model.compile(optimizer="adam",
              loss="categorical_crossentropy",
              metrics=["accuracy"])

history = model.fit(x_train, y_train,
                    validation_split=0.1,
                    epochs=15,
                    batch_size=128,
                    verbose=1)

# ================================================================
# STAGE D: ESTIMATING THE MODEL'S PERFORMANCE
# ================================================================
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest loss: {test_loss:.4f}   Test accuracy: {test_acc:.4f}")

y_pred = model.predict(x_test, verbose=0).argmax(axis=1)
print("\nClassification Report:")
print(classification_report(y_test_idx, y_pred, target_names=class_names))

# Confusion matrix
cm = confusion_matrix(y_test_idx, y_pred)
plt.figure(figsize=(9, 8))
plt.imshow(cm, cmap="Blues")
plt.colorbar()
plt.xticks(range(NUM_CLASSES), class_names)
plt.yticks(range(NUM_CLASSES), class_names)
plt.xlabel("Predicted"); plt.ylabel("True")
plt.title("Confusion Matrix (Sign Language MNIST CNN)")
plt.tight_layout()
plt.savefig("sign_mnist_cnn_confusion.png", dpi=150)
plt.show()

# Training curves
epochs_range = range(1, len(history.history["loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
ax1.plot(epochs_range, history.history["loss"], label="train_loss")
ax1.plot(epochs_range, history.history["val_loss"], label="val_loss")
ax1.set_title("Loss"); ax1.set_xlabel("Epoch"); ax1.legend(); ax1.grid(True)
ax2.plot(epochs_range, history.history["accuracy"], label="train_acc")
ax2.plot(epochs_range, history.history["val_accuracy"], label="val_acc")
ax2.set_title("Accuracy"); ax2.set_xlabel("Epoch"); ax2.legend(); ax2.grid(True)
fig.suptitle("CNN Training History on Sign Language MNIST")
plt.tight_layout()
plt.savefig("sign_mnist_cnn_training.png", dpi=150)
plt.show()

import tensorflow as tf

print("Tensorflow version: "+ tf.__version__)

import pandas as pd

df = pd.read_csv("/content/drive/MyDrive/SEM7/cifar-10.csv")

df.shape

label_col = "label"
y = df[label_col].values.astype("int64")
pixel_cols = [ c for c in df.columns if c!=label_col]
X = df[pixel_cols].values.astype("uint8")

X = X.reshape((-1,3,32,32)).transpose(0,2,3,1)

from sklearn.model_selection import 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)

X_train = X_train.astype("float32") / 255.0
X_test = X_test.astype("float32") / 255.0

from tensorflow.keras.utils import to_categorical

NUM_CLASSES = 10
y_train_cat = to_categorical(y_train,NUM_CLASSES)
y_test_cat = to_categorical(y_test,NUM_CLASSES)

from tensorflow.keras import layers, models

model = models.Sequential([
  layers.Input(shape=(32,32,3)),

  layers.RandomFlip("horizontal"),
  layers.RandomTranslation(0.1,0.1),

  layers.Conv2D(32, (3,3), padding="same", activation="relu"),
  layers.Conv2D(32, (3,3), padding="same", activation="relu"),
  layers.MaxPooling2D((2,2)),
  layers.Dropout(0.25),

  layers.Conv2D(64, (3,3), padding="same", activation="relu"),
  layers.Conv2D(64, (3,3), padding="same", activation="relu"),
  layers.MaxPooling2D((2,2)),
  layers.Dropout(0.25),

  layers.Flatten(),
  layers.Dense(256, activation="relu"),
  layers.Dropout(0.5),
  layers.Dense(NUM_CLASSES, activation="softmax")
])

model.summary()

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

history = model.fit(X_train, y_train_cat,
                    validation_split=0.1,
                    epochs=10,
                    batch_size=128,
                    verbose=1)

test_loss, test_acc = model.evaluate(X_test, y_test_cat,verbose=0)
print(f"Test loss: {test_loss:.4f} Test acc: {test_acc:.4f}")

predictions = model.predict(X_test, verbose=0)
y_pred = predictions.argmax(axis=1)

from sklearn.metrics import classification_report
CLASS_NAMES=["airplane", "automobile", "bird", "cat", "deer",
               "dog", "frog", "horse", "ship", "truck"]
print(classification_report(y_test, y_pred, target_names=CLASS_NAMES))

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

import matplotlib.pyplot as plt

plt.figure(figsize=(8,7))
plt.imshow(cm, cmap="Blues")
plt.colorbar()
plt.xticks(range(NUM_CLASSES), CLASS_NAMES, rotation=45)
plt.yticks(range(NUM_CLASSES),CLASS_NAMES)
for i in range(NUM_CLASSES):
  for j in range(NUM_CLASSES):
    plt.text(j,i,cm[i,j], ha="center", va="center", color="white" if cm[i,j] > cm.max()/2 else "black")
plt.xlabel("Predicted")
plt.ylabel("True")
plt.title("Confusion Matrix - CIFAR10")
plt.tight_layout()
plt.show()

epochs_range = range(1,len(history.history["loss"])+1)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,5))
ax1.plot(epochs_range, history.history["loss"], label="Train Loss")
ax1.plot(epochs_range, history.history["val_loss"], label="Val Loss")
ax1.legend();ax1.set_title("Loss / Validation Loss");ax1.set_xlabel("Epochs #");ax1.grid(True);
ax2.plot(epochs_range, history.history["accuracy"], label="Train Acc")
ax2.plot(epochs_range, history.history["val_accuracy"], label="Val Acc")
ax2.legend();ax2.set_title("Loss / Validation Accuracy");ax2.set_xlabel("Epochs #");ax2.grid(True);
fig.suptitle("CIFAR10 CNN Training Stats")
plt.tight_layout()
plt.show()