================================================================================
# Architecture 9: Transfer Learning for Cats vs Dogs with Pretrained ResNet50
# Library: keres | Framework: TensorFlow / Keras | Total Cells: 8
================================================================================

# --------------------------------------------------------------------------------
# [CELL 1 / 8] : Imports & Environment Setup
# --------------------------------------------------------------------------------
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input

print("TensorFlow version:", tf.__version__)
print("GPU available:", tf.config.list_physical_devices('GPU'))

# --------------------------------------------------------------------------------
# [CELL 2 / 8] : Download and Slice Cats vs Dogs Dataset (TFDS)
# --------------------------------------------------------------------------------
import tensorflow_datasets as tfds

# Download Cats vs Dogs dataset
dataset, info = tfds.load(
    'cats_vs_dogs',
    with_info=True,
    as_supervised=True,
    download=True
)

print("Total images:", info.splits['train'].num_examples)
print("Class names:", info.features['label'].names)  # ['cat', 'dog']

# Shuffle and take a 2,500 image subset for fast training
dataset = dataset['train'].shuffle(buffer_size=1000, seed=42, reshuffle_each_iteration=False)
small_dataset = dataset.take(2500)

train_size = 2000
train_data = small_dataset.take(train_size)
validation_data = small_dataset.skip(train_size)

print("Training samples:", train_size)
print("Validation samples:", 500)

# --------------------------------------------------------------------------------
# [CELL 3 / 8] : Image Preprocessing, Resizing & Batched Pipeline
# --------------------------------------------------------------------------------
IMG_SIZE = (224, 224)
BATCH_SIZE = 32

def preprocess_image(image, label):
    # Resize to ResNet50 standard input dimensions
    image = tf.image.resize(image, IMG_SIZE)
    # Apply ResNet50-specific scaling (caffe-style mean subtraction)
    image = preprocess_input(tf.cast(image, tf.float32))
    return image, label

# Map and prefetch for GPU performance
train_data = train_data.map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)
validation_data = validation_data.map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)

train_data = train_data.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
validation_data = validation_data.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)

print("Preprocessing complete | Image size:", IMG_SIZE, "| Batch size:", BATCH_SIZE)

# --------------------------------------------------------------------------------
# [CELL 4 / 8] : Pretrained ResNet50 Feature Extractor Loading & Layer Freezing
# --------------------------------------------------------------------------------
# Load ResNet50 pretrained on ImageNet without top dense classification head
base_model = ResNet50(
    weights='imagenet',
    include_top=False,
    input_shape=(224, 224, 3)
)

# Freeze all backbone layers for Phase 1 feature extraction
base_model.trainable = False

print(f"ResNet50 loaded with {len(base_model.layers)} layers (All Frozen).")

# --------------------------------------------------------------------------------
# [CELL 5 / 8] : Binary Classification Head Construction
# --------------------------------------------------------------------------------
# Build transfer learning model with custom binary head
model = models.Sequential([
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.5),
    layers.Dense(1, activation='sigmoid')  # 1 output neuron for binary classification
])

model.summary()

# --------------------------------------------------------------------------------
# [CELL 6 / 8] : Phase 1 Training: Feature Extraction (Frozen Backbone)
# --------------------------------------------------------------------------------
# Compile for binary classification
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
    loss='binary_crossentropy',
    metrics=['accuracy']
)

# Train only the top classification head
history_frozen = model.fit(
    train_data,
    validation_data=validation_data,
    epochs=3
)

loss_frozen, accuracy_frozen = model.evaluate(validation_data)
print(f"Frozen Model Validation Accuracy: {accuracy_frozen * 100:.2f}%")

# --------------------------------------------------------------------------------
# [CELL 7 / 8] : Phase 2 Training: Fine-Tuning Top 20 Layers with Low Learning Rate
# --------------------------------------------------------------------------------
# Unfreeze top layers for fine-tuning
base_model.trainable = True

# Freeze all layers except the last 20
for layer in base_model.layers[:-20]:
    layer.trainable = False

# Recompile with a 10x smaller learning rate to prevent catastrophic forgetting
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.00001),
    loss='binary_crossentropy',
    metrics=['accuracy']
)

# Fine-tune the model
history_finetune = model.fit(
    train_data,
    validation_data=validation_data,
    epochs=3
)

loss_finetune, accuracy_finetune = model.evaluate(validation_data)
print(f"Fine-Tuned Model Validation Accuracy: {accuracy_finetune * 100:.2f}%")

# --------------------------------------------------------------------------------
# [CELL 8 / 8] : Inference Pipeline on Sample Images
# --------------------------------------------------------------------------------
# Inference demonstration on a sample batch
for images, labels in validation_data.take(1):
    preds = model.predict(images)
    for i in range(5):
        prob = float(preds[i][0])
        pred_label = "Dog" if prob >= 0.5 else "Cat"
        true_label = "Dog" if labels[i].numpy() == 1 else "Cat"
        print(f"Sample {i+1} | True: {true_label:<4} | Predicted: {pred_label:<4} (Confidence: {prob:.4f})")


================================================================================
💡 CUSTOMIZATION & ADAPTATION RECIPES FOR ARCHITECTURE 9 (Cats vs Dogs Transfer Learning):
================================================================================
1. SWITCH FROM TFDS TO LOCAL DIRECTORY VIA PANDAS / FOLDER:
   # Structure: data/cats/*.jpg and data/dogs/*.jpg
   train_data = tf.keras.utils.image_dataset_from_directory(
       'data/train',
       image_size=(224, 224),
       batch_size=32,
       label_mode='binary'
   )
   val_data = tf.keras.utils.image_dataset_from_directory(
       'data/val',
       image_size=(224, 224),
       batch_size=32,
       label_mode='binary'
   )

2. SWITCH PRETRAINED BACKBONE (MobileNetV2 or EfficientNetB0):
   # MobileNetV2 (Faster, lightweight):
   base_model = tf.keras.applications.MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
   # EfficientNetB0 (Modern state-of-the-art accuracy):
   base_model = tf.keras.applications.EfficientNetB0(weights='imagenet', include_top=False, input_shape=(224, 224, 3))

3. ADD DATA AUGMENTATION (Prevent Overfitting):
   data_augmentation = tf.keras.Sequential([
       layers.RandomFlip("horizontal"),
       layers.RandomRotation(0.1),
       layers.RandomZoom(0.1),
   ])
   # Insert before base_model in Sequential

4. ADAPT TO MULTI-CLASS (e.g., Cats vs Dogs vs Birds):
   # Change final layer to:
   layers.Dense(num_classes, activation='softmax')
   # And loss to:
   loss='sparse_categorical_crossentropy'
================================================================================