# ================================================================
# FEEDFORWARD NEURAL NETWORK ON MNIST (train.csv / test.csv)
# ================================================================

# a. Import the necessary packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import SGD

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

# b. Load the training and testing data
train_df = pd.read_csv(TRAIN_PATH)
test_df = pd.read_csv(TEST_PATH)

trainY = train_df["label"].values
testY = test_df["label"].values
trainX = train_df.drop(columns=["label"]).values    # 784 pixel columns
testX = test_df.drop(columns=["label"]).values

print("Train:", trainX.shape, " Test:", testX.shape)

# Scale pixels from 0-255 to 0-1
trainX = trainX.astype("float32") / 255.0
testX = testX.astype("float32") / 255.0

# Convert integer labels to one-hot vectors
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

# c. Define the network architecture using Keras
model = Sequential([
    Input(shape=(784,)),
    Dense(256, activation="sigmoid"),
    Dense(128, activation="sigmoid"),
    Dense(10, activation="softmax"),
])
model.summary()

# d. Train the model using SGD with 11 epochs
model.compile(optimizer=SGD(learning_rate=0.01),
              loss="categorical_crossentropy",
              metrics=["accuracy"])

H = model.fit(trainX, trainY,
              validation_split=0.1,
              epochs=11,
              batch_size=128,
              verbose=1)

# e. Evaluate the network
test_loss, test_acc = model.evaluate(testX, testY, verbose=0)
print(f"\nTest loss: {test_loss:.4f}   Test accuracy: {test_acc:.4f}")

predictions = model.predict(testX, verbose=0)
print("\nClassification Report:")
print(classification_report(testY.argmax(axis=1),
                            predictions.argmax(axis=1)))

# f. Plot the training loss and accuracy
epochs_range = range(1, len(H.history["loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

ax1.plot(epochs_range, H.history["loss"], label="train_loss")
ax1.plot(epochs_range, H.history["val_loss"], label="val_loss")
ax1.set_title("Loss")
ax1.set_xlabel("Epoch")
ax1.legend()
ax1.grid(True)

ax2.plot(epochs_range, H.history["accuracy"], label="train_acc")
ax2.plot(epochs_range, H.history["val_accuracy"], label="val_acc")
ax2.set_title("Accuracy")
ax2.set_xlabel("Epoch")
ax2.legend()
ax2.grid(True)

fig.suptitle("FNN Training History on MNIST")
plt.tight_layout()
plt.savefig("mnist_fnn_training.png", dpi=150)
plt.show()

from tensorflow.keras import datasets, backend as K

K.clear_session()

((trainX, trainY), (testX, testY)) = datasets.mnist.load_data()

print(trainY)

trainX = trainX.reshape((trainX.shape[0],784))
testX = testX.reshape((testX.shape[0],784))

trainX = trainX.astype("float32") / 255.0
testX = testX.astype("float32") / 255.0

from sklearn.preprocessing import LabelBinarizer

lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
model = Sequential([
  Input(shape=(784,)),
  Dense(256, activation="sigmoid"),
  Dense(128, activation="sigmoid"),
  Dense(10, activation="softmax")
])

from tensorflow.keras.optimizers import SGD
sgd = SGD(learning_rate=0.01)
model.compile(loss="categorical_crossentropy",
              optimizer=sgd,
              metrics=["accuracy"])

EPOCHS = 20
BATCH_SIZE = 128

H = model.fit(trainX, trainY,
              # validation_data=(testX, testY),
              validation_split=0.2,
              epochs=EPOCHS,
              batch_size=BATCH_SIZE,
              verbose=1);

test_loss, test_acc = model.evaluate(testX, testY, verbose=0)
print(f"Test Loss: {test_loss:.4f} Test accuracy: {test_acc:.4f}")

predictions = model.predict(testX, batch_size=BATCH_SIZE)

from sklearn.metrics import classification_report
print("Classification Report:")
print(classification_report(testY.argmax(axis=1),
                            predictions.argmax(axis=1),
                            target_names=[str(c) for c in lb.classes_]))

import numpy as np
import matplotlib.pyplot as plt

print(H.history)

N = np.arange(0, len(H.history["loss"]))
plt.style.use("ggplot")
plt.figure(figsize=(8,5))
plt.plot(N,H.history["loss"],label="train_loss")
plt.plot(N,H.history["val_loss"],label="val_loss")
plt.plot(N,H.history["accuracy"],label="train_acc")
plt.plot(N,H.history["val_accuracy"],label="val_acc")
plt.title("Training Loss and Accuracy on MNIST")
plt.xlabel("Epoch #")
plt.ylabel("Loss / Accuracy")
plt.legend()
plt.tight_layout()
plt.show()

# ================================================================
# FEEDFORWARD NEURAL NETWORK ON CIFAR-10 (cifar10.csv)
# ================================================================

# a. Import the necessary packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import SGD

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"]

# b. Load the data
df = pd.read_csv(CSV_PATH)
print("Dataset shape:", df.shape)

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")          # 3072 values per image
assert X.shape[1] == 3072, f"Expected 3072 pixel columns, found {X.shape[1]}"

# Split into train and test (80/20), 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)

# Scale pixels to 0-1
X_train = X_train / 255.0
X_test = X_test / 255.0

# One-hot encode labels
lb = LabelBinarizer()
y_train_cat = lb.fit_transform(y_train)
y_test_cat = lb.transform(y_test)

print("Train:", X_train.shape, " Test:", X_test.shape)

# c. Define the network architecture using Keras
model = Sequential([
    Input(shape=(3072,)),
    Dense(512, activation="relu"),
    Dense(256, activation="relu"),
    Dense(10, activation="softmax"),
])
model.summary()

# d. Train the model (SGD with momentum; swap in Adam if preferred)
model.compile(optimizer=SGD(learning_rate=0.01, momentum=0.9),
              loss="categorical_crossentropy",
              metrics=["accuracy"])

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

# e. Evaluate the network
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))

# f. Plot the training loss and accuracy
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("FNN Training History on CIFAR-10")
plt.tight_layout()
plt.savefig("cifar10_fnn_training.png", dpi=150)
plt.show()

from tensorflow.keras import datasets, backend as K

K.clear_session()

((trainX, trainY),(testX, testY)) = datasets.cifar10.load_data()

trainX = trainX.reshape((trainX.shape[0],3072)).astype("float32") / 255.0
testX = trainY.reshape((testX.shape[0],3072)).astype("float32") / 255.0

trainY = trainY.ravel()
testY = testY.ravel()

from sklearn.preprocessing import LabelBinarizer

lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input

model = Sequential([
    Input(shape=(3072,)),
    Dense(512, activation="relu"),
    Dense(256, activation="relu"),
    Dense(10, activation="softmax")
])

from tensorflow.keras.optimizers import SGD

sgd = SGD(learning_rate=0.01)
model.compile(loss="categorical_crossentropy",
              optimizer=sgd,
              metrics=["accuracy"])

EPOCHS = 20
BATCH_SIZE = 128

H=model.fit(trainX, trainY,
          validation_split=0.2,
          epochs=EPOCHS,
          batch_size=BATCH_SIZE,
          verbose=1)

test_loss, test_acc = model.evaluate(testX, testY, verbose=0)
print(f"Test loss: {test_loss:.4f} Test accuracy: {test_acc:.4f}")

predictions = model.predict(testX, batch_size=BATCH_SIZE)

from sklearn.metrics import classification_report
print("Classification Report:")
print(classification_report(testY.argmax(axis=1),
                            predictions.argmax(axis=1),
                            target_names=["airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"]))

N = np.arange(0, len(H.history["loss"]))
plt.style.use("ggplot")
plt.figure(figsize=(8,5))
plt.plot(N, H.history["loss"],label_name="train_loss")
plt.plot(N, H.history["val_loss"], label_name="val_loss")
plt.plot(N, H.history["acc"],label_name="train_acc")
plt.plot(N, H.history["val_acc"], label_name="val_acc")
plt.title("Training Loss and Accuracy on CIFAR-10")
plt.xlabel("Epoch #")
plt.ylabel("Loss / Accuracy")
plt.legend()
plt.tightlayout()
plt.show()

# ================================================================
# FEEDFORWARD NEURAL NETWORK ON FASHION-MNIST (CSV)
# ================================================================

# a. Import the necessary packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import SGD

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

TRAIN_PATH = "/content/fashion-mnist_train.csv"   # change to your path
TEST_PATH = "/content/fashion-mnist_test.csv"     # change to your path

CLASS_NAMES = ["T-shirt-top", "Trouser", "Pullover", "Dress", "Coat",
               "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]

# b. Load the training and testing data
train_df = pd.read_csv(TRAIN_PATH)
test_df = pd.read_csv(TEST_PATH)

trainY = train_df["label"].values
testY = test_df["label"].values
trainX = train_df.drop(columns=["label"]).values.astype("float32") / 255.0
testX = test_df.drop(columns=["label"]).values.astype("float32") / 255.0

lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

# c. Define the network architecture using Keras
model = Sequential([
    Input(shape=(784,)),
    Dense(256, activation="sigmoid"),
    Dense(128, activation="sigmoid"),
    Dense(10, activation="softmax"),
])
model.summary()

# d. Train the model using SGD
model.compile(optimizer=SGD(learning_rate=0.01),
              loss="categorical_crossentropy",
              metrics=["accuracy"])

H = model.fit(trainX, trainY,
              validation_split=0.1,
              epochs=10,
              batch_size=128,
              verbose=1)

# e. Evaluate the network
test_loss, test_acc = model.evaluate(testX, testY, verbose=0)
print(f"\nTest loss: {test_loss:.4f}   Test accuracy: {test_acc:.4f}")

predictions = model.predict(testX, verbose=0).argmax(axis=1)
print("\nClassification Report:")
print(classification_report(testY.argmax(axis=1), predictions,
                            target_names=CLASS_NAMES))

# f. Plot the training loss and accuracy
epochs_range = range(1, len(H.history["loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

ax1.plot(epochs_range, H.history["loss"], label="train_loss")
ax1.plot(epochs_range, H.history["val_loss"], label="val_loss")
ax1.set_title("Loss"); ax1.set_xlabel("Epoch"); ax1.legend(); ax1.grid(True)

ax2.plot(epochs_range, H.history["accuracy"], label="train_acc")
ax2.plot(epochs_range, H.history["val_accuracy"], label="val_acc")
ax2.set_title("Accuracy"); ax2.set_xlabel("Epoch"); ax2.legend(); ax2.grid(True)

fig.suptitle("FNN Training History on Fashion-MNIST")
plt.tight_layout()
plt.savefig("fashion_mnist_fnn_training.png", dpi=150)
plt.show()

# ================================================================
# FEEDFORWARD NEURAL NETWORK ON SIGN LANGUAGE MNIST (train.csv / test.csv)
# ================================================================

# a. Import the necessary packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import SGD

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

# b. Load the training and testing data
train_df = pd.read_csv(TRAIN_PATH)
test_df = pd.read_csv(TEST_PATH)

trainY_raw = train_df["label"].values
testY_raw = test_df["label"].values
trainX = train_df.drop(columns=["label"]).values.astype("float32") / 255.0
testX = test_df.drop(columns=["label"]).values.astype("float32") / 255.0

# Labels are not continuous (9 and 25 are missing), so use LabelBinarizer
# and read the number of classes from the data, not a fixed number
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY_raw)
testY = lb.transform(testY_raw)
NUM_CLASSES = len(lb.classes_)                       # should be 24

# Map each class position back to its letter.
# lb.classes_ holds the original label values, e.g. [0,1,...,8,10,...,24]
LETTERS = "ABCDEFGHIKLMNOPQRSTUVWXY"                 # no J or Z
label_to_letter = dict(zip(lb.classes_, LETTERS))
class_names = [label_to_letter[c] for c in lb.classes_]

print("Train:", trainX.shape, " Test:", testX.shape)
print("Number of classes:", NUM_CLASSES)

# c. Define the network architecture using Keras
model = Sequential([
    Input(shape=(784,)),
    Dense(256, activation="sigmoid"),
    Dense(128, activation="sigmoid"),
    Dense(NUM_CLASSES, activation="softmax"),
])
model.summary()

# d. Train the model using SGD
model.compile(optimizer=SGD(learning_rate=0.01),
              loss="categorical_crossentropy",
              metrics=["accuracy"])

H = model.fit(trainX, trainY,
              validation_split=0.1,
              epochs=10,
              batch_size=128,
              verbose=1)

# e. Evaluate the network
test_loss, test_acc = model.evaluate(testX, testY, verbose=0)
print(f"\nTest loss: {test_loss:.4f}   Test accuracy: {test_acc:.4f}")

predictions = model.predict(testX, verbose=0).argmax(axis=1)
print("\nClassification Report:")
print(classification_report(testY.argmax(axis=1), predictions,
                            target_names=class_names))

# f. Plot the training loss and accuracy
epochs_range = range(1, len(H.history["loss"]) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

ax1.plot(epochs_range, H.history["loss"], label="train_loss")
ax1.plot(epochs_range, H.history["val_loss"], label="val_loss")
ax1.set_title("Loss"); ax1.set_xlabel("Epoch"); ax1.legend(); ax1.grid(True)

ax2.plot(epochs_range, H.history["accuracy"], label="train_acc")
ax2.plot(epochs_range, H.history["val_accuracy"], label="val_acc")
ax2.set_title("Accuracy"); ax2.set_xlabel("Epoch"); ax2.legend(); ax2.grid(True)

fig.suptitle("FNN Training History on Sign Language MNIST")
plt.tight_layout()
plt.savefig("sign_mnist_fnn_training.png", dpi=150)
plt.show()