================================================================================
# Architecture 5: Convolutional Neural Networks (CNN) vs Multi-Layer Perceptron (MLP)
# Library: keres | Framework: PyTorch / Torchvision | Total Cells: 10
================================================================================


# --------------------------------------------------------------------------------
# [CELL 1 / 10] : Imports (PyTorch, Torchvision, DataLoader)
# --------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader


# --------------------------------------------------------------------------------
# [CELL 2 / 10] : Device Configuration (CUDA GPU vs CPU)
# --------------------------------------------------------------------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Device:", device)


# --------------------------------------------------------------------------------
# [CELL 3 / 10] : CIFAR-10 / Image Data Preprocessing & Augmentation
# --------------------------------------------------------------------------------
train_transform = transforms.Compose([
    transforms.RandomRotation(10), 
    transforms.ToTensor()
])

test_transform = transforms.ToTensor()

train_data = datasets.MNIST(
    root="./data",
    train=True,
    download=True,
    transform=train_transform
)

test_data = datasets.MNIST(
    root="./data",
    train=False,
    download=True,
    transform=test_transform
)

train_loader = DataLoader(train_data, batch_size=128, shuffle=True)
test_loader = DataLoader(test_data, batch_size=128)


# --------------------------------------------------------------------------------
# [CELL 4 / 10] : Convolutional Neural Network (CNN) Architecture Definition
# --------------------------------------------------------------------------------
class CNN(nn.Module):
    def __init__(self):
        super().__init__()

        self.conv1 = nn.Conv2d(1, 16, 3)
        self.conv2 = nn.Conv2d(16, 32, 3)
        self.pool = nn.MaxPool2d(2)

        self.fc1 = nn.Linear(32 * 5 * 5, 64)
        self.fc2 = nn.Linear(64, 10)

    def forward(self, x):
        x = self.pool(torch.relu(self.conv1(x)))
        x = self.pool(torch.relu(self.conv2(x)))

        x = x.view(x.size(0), -1)

        x = torch.relu(self.fc1(x))
        x = self.fc2(x)

        return x


# --------------------------------------------------------------------------------
# [CELL 5 / 10] : Multi-Layer Perceptron (MLP) Architecture Definition
# --------------------------------------------------------------------------------
class MLP(nn.Module):
    def __init__(self):
        super().__init__()

        self.fc1 = nn.Linear(28 * 28, 128)
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):
        x = x.view(x.size(0), -1)

        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)

        return x


# --------------------------------------------------------------------------------
# [CELL 6 / 10] : Model Training Loop with Cross-Entropy & Adam
# --------------------------------------------------------------------------------
def train(model, epochs=3):

    model = model.to(device)

    loss_function = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    for epoch in range(epochs):

        model.train()
        total_loss = 0

        for images, labels in train_loader:

            images = images.to(device)
            labels = labels.to(device)

            optimizer.zero_grad()

            output = model(images)

            loss = loss_function(output, labels)

            loss.backward()
            optimizer.step()

            total_loss += loss.item()

        print(
            f"Epoch {epoch+1}/{epochs} "
            f"Loss: {total_loss/len(train_loader):.4f}"
        )

    return model


# --------------------------------------------------------------------------------
# [CELL 7 / 10] : Model Evaluation Routine & Accuracy Computation
# --------------------------------------------------------------------------------
def test(model):

    model.eval()

    correct = 0
    total = 0

    with torch.no_grad():

        for images, labels in test_loader:

            images = images.to(device)
            labels = labels.to(device)

            output = model(images)

            _, predicted = torch.max(output, 1)

            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    return 100 * correct / total


# --------------------------------------------------------------------------------
# [CELL 8 / 10] : CNN Training Execution & Benchmarking
# --------------------------------------------------------------------------------
print("\nTraining CNN...")

cnn = CNN()
cnn = train(cnn)

cnn_accuracy = test(cnn)

print("CNN Accuracy:", round(cnn_accuracy, 2), "%")


# --------------------------------------------------------------------------------
# [CELL 9 / 10] : MLP Training Execution & Benchmarking
# --------------------------------------------------------------------------------
print("\nTraining MLP...")

mlp = MLP()
mlp = train(mlp)

mlp_accuracy = test(mlp)

print("MLP Accuracy:", round(mlp_accuracy, 2), "%")


# --------------------------------------------------------------------------------
# [CELL 10 / 10] : Comparative Summary: CNN vs MLP Parameter Efficiency & Accuracy
# --------------------------------------------------------------------------------
print("       COMPARISON")

print("MLP Accuracy :", round(mlp_accuracy, 2), "%")
print("CNN Accuracy :", round(cnn_accuracy, 2), "%")

================================================================================
💡 CUSTOMIZATION & ADAPTATION RECIPES FOR ARCHITECTURE 5 (CNN vs MLP on Images in PyTorch):
================================================================================
1. SWITCH TO CIFAR-10 OR FASHION-MNIST:
   # Fashion-MNIST (1 channel, 28x28):
   train_data = datasets.FashionMNIST(root=./data, train=True, download=True, transform=train_transform)
   # CIFAR-10 (3 color channels RGB, 32x32):
   # Note: update CNN conv1 in_channels from 1 to 3: self.conv1 = nn.Conv2d(3, 16, 3)
   train_data = datasets.CIFAR10(root=./data, train=True, download=True, transform=train_transform)

2. SWITCH OPTIMIZERS:
   # Replace: optimizer = optim.Adam(model.parameters(), lr=0.001)
   # With SGD:
   optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)

3. ENHANCE CNN ARCHITECTURE:
   # Increase channels (16 -> 32 -> 64) and add BatchNorm:
   self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
   self.bn1 = nn.BatchNorm2d(32)
   self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
   self.bn2 = nn.BatchNorm2d(64)
   self.dropout = nn.Dropout2d(0.25)

4. DATA AUGMENTATION TWEAKS:
   train_transform = transforms.Compose([
       transforms.RandomRotation(15),
       transforms.RandomHorizontalFlip(),
       transforms.ColorJitter(brightness=0.2),
       transforms.ToTensor()
   ])
================================================================================
