import tensorflow as tf
import matplotlib.pyplot as plt
import time
import pandas as pd  # For MNIST CSV loading
# Load CIFAR-10 dataset
train_ds = tf.keras.utils.image_dataset_from_directory(
    "dataset/cifar/cifar10/train",
    image_size=(32,32), batch_size=64,
    validation_split=0.1, subset="training", seed=42
)
val_ds = tf.keras.utils.image_dataset_from_directory(
    "dataset/cifar/cifar10/train",
    image_size=(32,32), batch_size=64,
    validation_split=0.1, subset="validation", seed=42
)
test_ds = tf.keras.utils.image_dataset_from_directory(
    "dataset/cifar/cifar10/test",
    image_size=(32,32), batch_size=64
)
print("Classes:",train_ds.class_names)
# For MNIST: Replace the above CIFAR-10 loading section with:
# train = pd.read_csv("mnist_train(1).csv")
# test = pd.read_csv("mnist_test(1).csv")
# x_train = train.iloc[:,1:].values.astype('float32')/255.0
# y_train = train.iloc[:,0].values
# x_test = test.iloc[:,1:].values.astype('float32')/255.0
# y_test = test.iloc[:,0].values
# x_train_cnn = x_train.reshape(-1,28,28,1)
# x_test_cnn = x_test.reshape(-1,28,28,1)
# Prepare MLP data
mlp_train = train_ds.map(lambda x,y:(tf.reshape(x/255.0,[-1,3072]),y)).prefetch(1)
mlp_val = val_ds.map(lambda x,y:(tf.reshape(x/255.0,[-1,3072]),y)).prefetch(1)
mlp_test = test_ds.map(lambda x,y:(tf.reshape(x/255.0,[-1,3072]),y)).prefetch(1)
# Prepare CNN data
cnn_train = train_ds.map(lambda x,y:(x/255.0,y)).prefetch(1)
cnn_val = val_ds.map(lambda x,y:(x/255.0,y)).prefetch(1)
cnn_test = test_ds.map(lambda x,y:(x/255.0,y)).prefetch(1)
# For MNIST: No map() or prefetch() required.
# Use x_train and y_train directly for MLP.
# Use x_train_cnn and y_train directly for CNN.
# Build MLP model
mlp = tf.keras.Sequential([
    tf.keras.layers.Input((3072,)), # MNIST: Input((784,))
    tf.keras.layers.Dense(256,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
])
# Build CNN model with data augmentation
cnn = tf.keras.Sequential([
    tf.keras.layers.Input((32,32,3)), # MNIST: Input((28,28,1))
    tf.keras.layers.RandomFlip("horizontal"),
    tf.keras.layers.RandomRotation(0.1), # MNIST: RandomRotation(0.05)
    tf.keras.layers.Conv2D(32,(3,3),activation='relu'),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Conv2D(64,(3,3),activation='relu'),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
])
for model in [mlp,cnn]:
    model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
# Train MLP
start = time.time()
h1 = mlp.fit(mlp_train,epochs=5,validation_data=mlp_val,verbose=0)
mlp_time = time.time()-start
mlp_loss,mlp_acc = mlp.evaluate(mlp_test,verbose=0)
print("MLP Accuracy:",mlp_acc*100,"%")
print("MLP Training Time:",round(mlp_time,2),"seconds")
# For MNIST MLP training:
# h1 = mlp.fit(x_train,y_train,epochs=5,batch_size=64,validation_split=0.1)
# mlp_loss,mlp_acc = mlp.evaluate(x_test,y_test,verbose=0)
# Train CNN
start = time.time()
h2 = cnn.fit(cnn_train,epochs=5,validation_data=cnn_val,verbose=0)
cnn_time = time.time()-start
cnn_loss,cnn_acc = cnn.evaluate(cnn_test,verbose=0)
print("CNN Accuracy:",cnn_acc*100,"%")
print("CNN Training Time:",round(cnn_time,2),"seconds")
# For MNIST CNN training:
# h2 = cnn.fit(x_train_cnn,y_train,epochs=5,batch_size=64,validation_split=0.1)
# cnn_loss,cnn_acc = cnn.evaluate(x_test_cnn,y_test,verbose=0)
# Compare accuracy
plt.bar(['MLP','CNN'],[mlp_acc*100,cnn_acc*100])
plt.title("MLP vs CNN Accuracy")
plt.ylabel("Accuracy (%)")
plt.show()
# Compare training time
plt.bar(['MLP','CNN'],[mlp_time,cnn_time])
plt.title("Training Time Comparison")
plt.ylabel("Time (seconds)")
plt.show()
# Plot validation accuracy
plt.plot(h1.history['val_accuracy'],label='MLP')
plt.plot(h2.history['val_accuracy'],label='CNN')
plt.title("Validation Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
# Plot validation loss
plt.plot(h1.history['val_loss'],label='MLP')
plt.plot(h2.history['val_loss'],label='CNN')
plt.title("Validation Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()
