================================================================================
# Architecture 3: Regularization Techniques in Deep Neural Networks (L2 vs Dropout)
# Library: keres | Framework: TensorFlow / Keras | Total Cells: 6
================================================================================


# --------------------------------------------------------------------------------
# [CELL 1 / 6] : Imports (TensorFlow, Keras, NumPy, Matplotlib)
# --------------------------------------------------------------------------------
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt


# --------------------------------------------------------------------------------
# [CELL 2 / 6] : Dataset Loading & Normalization (MNIST)
# --------------------------------------------------------------------------------

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()


x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0

x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)

print(f"x_train shape: {x_train.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"x_test shape: {x_test.shape}")
print(f"y_test shape: {y_test.shape}")


# --------------------------------------------------------------------------------
# [CELL 3 / 6] : Baseline Model Definition (Unregularized Overfitting Model)
# --------------------------------------------------------------------------------
def build_baseline_model():
    model = keras.Sequential([
        keras.Input(shape=(784,)),
        layers.Dense(256, activation="relu"),
        layers.Dense(128, activation="relu"),
        layers.Dense(10, activation="softmax"),
    ])
    model.compile(
        optimizer="adam",
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model

print("Building baseline model...")
baseline_model = build_baseline_model()
baseline_model.summary()

print("\nTraining baseline model...")
history_baseline = baseline_model.fit(
    x_train, y_train,
    batch_size=128,
    epochs=20,
    validation_split=0.2,
    verbose=0
)
print("Baseline model training complete.")


# --------------------------------------------------------------------------------
# [CELL 4 / 6] : L2 Weight Regularization Model Definition (Weight Decay)
# --------------------------------------------------------------------------------
def build_l2_regularized_model(l2_lambda=0.001):
    model = keras.Sequential([
        keras.Input(shape=(784,)),
        layers.Dense(256, activation="relu", kernel_regularizer=keras.regularizers.l2(l2_lambda)),
        layers.Dense(128, activation="relu"),
        layers.Dense(10, activation="softmax"),
    ])
    model.compile(
        optimizer="adam",
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model

print("Building L2 regularized model...")
l2_model = build_l2_regularized_model(l2_lambda=0.001)
l2_model.summary()

print("\nTraining L2 regularized model...")
history_l2 = l2_model.fit(
    x_train, y_train,
    batch_size=128,
    epochs=20,
    validation_split=0.2,
    verbose=0
)
print("L2 regularized model training complete.")


# --------------------------------------------------------------------------------
# [CELL 5 / 6] : Dropout Regularization Model Definition
# --------------------------------------------------------------------------------
def build_dropout_model(dropout_rate=0.3):
    model = keras.Sequential([
        keras.Input(shape=(784,)),
        layers.Dense(256, activation="relu"),
        layers.Dropout(dropout_rate),
        layers.Dense(128, activation="relu"),
        layers.Dropout(dropout_rate),
        layers.Dense(10, activation="softmax"),
    ])
    model.compile(
        optimizer="adam",
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model

print("Building Dropout model...")
dropout_model = build_dropout_model(dropout_rate=0.3)
dropout_model.summary()

print("\nTraining Dropout model...")
history_dropout = dropout_model.fit(
    x_train, y_train,
    batch_size=128,
    epochs=20,
    validation_split=0.2,
    verbose=0
)
print("Dropout model training complete.")


# --------------------------------------------------------------------------------
# [CELL 6 / 6] : Training History Comparison & Overfitting Mitigation Plots
# --------------------------------------------------------------------------------
def plot_history(history_list, titles, metric='loss'):
    plt.figure(figsize=(15, 5))
    plt.subplot(1, 2, 1)
    for i, history in enumerate(history_list):
        plt.plot(history.history[metric], label=f'{titles[i]} Train {metric.capitalize()}')
        plt.plot(history.history[f'val_{metric}'], label=f'{titles[i]} Val {metric.capitalize()}', linestyle='--')
    plt.title(f'Training and Validation {metric.capitalize()}')
    plt.xlabel('Epochs')
    plt.ylabel(metric.capitalize())
    plt.legend()
    plt.grid(True)

    plt.subplot(1, 2, 2)
    for i, history in enumerate(history_list):
        plt.plot(history.history['accuracy'], label=f'{titles[i]} Train Accuracy')
        plt.plot(history.history['val_accuracy'], label=f'{titles[i]} Val Accuracy', linestyle='--')
    plt.title('Training and Validation Accuracy')
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()


history_list = [history_baseline, history_l2, history_dropout]
titles = ['Baseline', 'L2 Regularization', 'Dropout']

plot_history(history_list, titles, metric='loss')

================================================================================
💡 CUSTOMIZATION & ADAPTATION RECIPES FOR ARCHITECTURE 3 (L2 vs Dropout Regularization in Keras):
================================================================================
1. SWITCH TO LOCAL CSV VIA PANDAS:
   import pandas as pd
   df = pd.read_csv('mnist_data.csv')
   x_train = df.drop('label', axis=1).values.astype('float32') / 255.0
   y_train = df['label'].values

2. SWITCH OPTIMIZERS:
   # Inside model.compile():
   # Replace: optimizer='adam'
   # With SGD:
   optimizer=tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)
   # With RMSprop:
   optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.001)
   # With AdamW (Explicit weight decay):
   optimizer=tf.keras.optimizers.AdamW(learning_rate=0.001, weight_decay=0.004)

3. SWITCH REGULARIZERS:
   # L1 Regularization (creates sparse weights / feature selection):
   kernel_regularizer=keras.regularizers.l1(0.001)
   # ElasticNet (L1 + L2 combined):
   kernel_regularizer=keras.regularizers.l1_l2(l1=1e-4, l2=1e-3)

4. ADD EARLY STOPPING (Stop training before overfitting begins):
   early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
   reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=2)
   history = model.fit(x_train, y_train, epochs=30, validation_split=0.2, callbacks=[early_stop, reduce_lr])
================================================================================
