{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "colab": {
   "name": "flower_classification_mobilenetv2.ipynb",
   "provenance": [],
   "gpuType": "T4"
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU"
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# 🌻 Flower Classification with MobileNetV2\n**Dataset:** [Kaggle · Flowers Recognition](https://www.kaggle.com/datasets/alxmamaev/flowers-recognition) (~4.3k photos, 5 classes: daisy · dandelion · rose · sunflower · tulip)\n\n**What this notebook does**\n1. Downloads the dataset with `kagglehub` (no API key needed for public datasets)\n2. Builds a `tf.data` pipeline with an **on-model data-augmentation** stage\n3. **Transfer learning**: frozen MobileNetV2 (ImageNet) + a small classification head\n4. **Fine-tuning**: unfreezes the top of the backbone at a low learning rate\n5. **Evaluation**: accuracy/loss curves, classification report, confusion matrix, misclassified gallery\n6. **Inference** on your own uploaded photo + optional **TFLite export**\n\n> ⚡ Runtime → Change runtime type → **GPU (T4)** before running. Full run ≈ 10–15 min on a T4.\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1 · Setup"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "!pip -q install kagglehub"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import os, pathlib, random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nSEED = 42\nrandom.seed(SEED); np.random.seed(SEED); tf.random.set_seed(SEED)\n\nprint(\"TensorFlow:\", tf.__version__)\nprint(\"GPU:\", tf.config.list_physical_devices('GPU') or \"none — enable it in Runtime > Change runtime type\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2 · Download the dataset\n`kagglehub` fetches public Kaggle datasets without credentials and caches them locally."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import kagglehub\n\nroot = kagglehub.dataset_download(\"alxmamaev/flowers-recognition\")\nprint(\"Dataset downloaded to:\", root)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "CLASSES = ['daisy', 'dandelion', 'rose', 'sunflower', 'tulip']\n\ndef find_data_dir(root):\n    \"\"\"Locate the directory that directly contains the 5 class folders\n    (the archive sometimes nests flowers/flowers/...).\"\"\"\n    for dirpath, dirnames, _ in os.walk(root):\n        if all(c in dirnames for c in CLASSES):\n            return pathlib.Path(dirpath)\n    raise FileNotFoundError(\"Could not find the 5 class folders under \" + str(root))\n\ndata_dir = find_data_dir(root)\nprint(\"Class folders live in:\", data_dir)\n\nfor c in CLASSES:\n    n = len(list((data_dir / c).glob('*.jpg')))\n    print(f\"  {c:<10} {n:>5} images \" + \"█\" * (n // 40))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### A first look"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "fig, axes = plt.subplots(3, 5, figsize=(14, 8))\nfor col, c in enumerate(CLASSES):\n    picks = random.sample(list((data_dir / c).glob('*.jpg')), 3)\n    for row, p in enumerate(picks):\n        ax = axes[row, col]\n        ax.imshow(plt.imread(p)); ax.axis('off')\n        if row == 0: ax.set_title(c, fontsize=13)\nplt.suptitle(\"Random samples per class\", y=1.02)\nplt.tight_layout(); plt.show()"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3 · tf.data pipeline\n80/20 train/validation split. The validation set is loaded with `shuffle=False` so predictions stay aligned with labels for the confusion matrix later."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "IMG_SIZE = (224, 224)\nBATCH = 32\n\ntrain_ds = tf.keras.utils.image_dataset_from_directory(\n    data_dir, validation_split=0.2, subset='training', seed=SEED,\n    image_size=IMG_SIZE, batch_size=BATCH, label_mode='int')\n\nval_ds = tf.keras.utils.image_dataset_from_directory(\n    data_dir, validation_split=0.2, subset='validation', seed=SEED,\n    image_size=IMG_SIZE, batch_size=BATCH, label_mode='int', shuffle=False)\n\nclass_names = train_ds.class_names\nprint(\"Classes:\", class_names)\n\nAUTOTUNE = tf.data.AUTOTUNE\ntrain_ds = train_ds.cache().shuffle(1000, seed=SEED).prefetch(AUTOTUNE)\nval_ds = val_ds.cache().prefetch(AUTOTUNE)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4 · Data augmentation\nAugmentation lives **inside the model** as Keras layers — it runs on the GPU and is automatically disabled at inference time."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "data_augmentation = tf.keras.Sequential([\n    tf.keras.layers.RandomFlip('horizontal'),\n    tf.keras.layers.RandomRotation(0.12),\n    tf.keras.layers.RandomZoom(0.15),\n    tf.keras.layers.RandomTranslation(0.08, 0.08),\n    tf.keras.layers.RandomContrast(0.15),\n], name='augmentation')\n\n# visualize: one image, eight augmented views\nfor images, _ in train_ds.take(1):\n    plt.figure(figsize=(14, 4))\n    ax = plt.subplot(1, 9, 1)\n    plt.imshow(images[0].numpy().astype('uint8')); plt.title('original'); plt.axis('off')\n    for i in range(8):\n        aug = data_augmentation(tf.expand_dims(images[0], 0), training=True)\n        ax = plt.subplot(1, 9, i + 2)\n        plt.imshow(tf.clip_by_value(aug[0], 0, 255).numpy().astype('uint8'))\n        plt.title(f'aug {i+1}', fontsize=9); plt.axis('off')\n    plt.tight_layout(); plt.show()"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 5 · Transfer learning — MobileNetV2\nThe ImageNet-pretrained backbone is **frozen**; we only train a small head on top.\n`preprocess_input` (scales pixels to −1…1, what MobileNetV2 expects) is part of the graph, so the saved model accepts raw 0–255 images."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "base = tf.keras.applications.MobileNetV2(\n    input_shape=IMG_SIZE + (3,), include_top=False, weights='imagenet')\nbase.trainable = False\n\ninputs = tf.keras.Input(shape=IMG_SIZE + (3,))\nx = data_augmentation(inputs)\nx = tf.keras.applications.mobilenet_v2.preprocess_input(x)\nx = base(x, training=False)          # training=False also freezes BatchNorm statistics\nx = tf.keras.layers.GlobalAveragePooling2D()(x)\nx = tf.keras.layers.Dropout(0.25)(x)\noutputs = tf.keras.layers.Dense(len(class_names), activation='softmax')(x)\n\nmodel = tf.keras.Model(inputs, outputs, name='flower_mobilenetv2')\nmodel.compile(optimizer=tf.keras.optimizers.Adam(1e-3),\n              loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.summary(show_trainable=True)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 6 · Train the head"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "EPOCHS_HEAD = 10\n\ncallbacks = [\n    tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=3,\n                                     restore_best_weights=True, verbose=1),\n    tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.4,\n                                         patience=2, min_lr=1e-6, verbose=1),\n]\n\nhistory = model.fit(train_ds, validation_data=val_ds,\n                    epochs=EPOCHS_HEAD, callbacks=callbacks)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 7 · Fine-tune the top of the backbone\nUnfreeze everything from layer 100 up (~55 of 154 layers) and train at a **much lower** learning rate so we nudge, not destroy, the pretrained features."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "base.trainable = True\nFINE_TUNE_AT = 100\nfor layer in base.layers[:FINE_TUNE_AT]:\n    layer.trainable = False\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(1e-5),\n              loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\nEPOCHS_FT = 8\ntotal_epochs = len(history.epoch) + EPOCHS_FT\n\nhistory_ft = model.fit(train_ds, validation_data=val_ds,\n                       epochs=total_epochs, initial_epoch=len(history.epoch),\n                       callbacks=callbacks)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 8 · Evaluation — learning curves"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "acc  = history.history['accuracy'] + history_ft.history['accuracy']\nvacc = history.history['val_accuracy'] + history_ft.history['val_accuracy']\nloss = history.history['loss'] + history_ft.history['loss']\nvloss = history.history['val_loss'] + history_ft.history['val_loss']\nft_start = len(history.history['accuracy'])\n\nfig, (a1, a2) = plt.subplots(1, 2, figsize=(13, 4.5))\na1.plot(acc, label='train'); a1.plot(vacc, label='validation')\na1.axvline(ft_start - 0.5, ls='--', c='gray'); a1.text(ft_start, min(acc), ' fine-tune →', fontsize=9)\na1.set_title('Accuracy'); a1.set_xlabel('epoch'); a1.legend(); a1.grid(alpha=0.3)\na2.plot(loss, label='train'); a2.plot(vloss, label='validation')\na2.axvline(ft_start - 0.5, ls='--', c='gray')\na2.set_title('Loss'); a2.set_xlabel('epoch'); a2.legend(); a2.grid(alpha=0.3)\nplt.show()\n\nval_loss, val_acc = model.evaluate(val_ds, verbose=0)\nprint(f\"Final validation accuracy: {val_acc:.2%}   (loss {val_loss:.4f})\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Classification report & confusion matrix"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "from sklearn.metrics import classification_report, confusion_matrix\n\ny_true = np.concatenate([y.numpy() for _, y in val_ds])\ny_prob = model.predict(val_ds, verbose=0)\ny_pred = y_prob.argmax(axis=1)\n\nprint(classification_report(y_true, y_pred, target_names=class_names, digits=3))\n\ncm = confusion_matrix(y_true, y_pred)\nfig, ax = plt.subplots(figsize=(6.5, 5.5))\nim = ax.imshow(cm, cmap='Greens')\nax.set_xticks(range(len(class_names)), class_names, rotation=30, ha='right')\nax.set_yticks(range(len(class_names)), class_names)\nfor i in range(cm.shape[0]):\n    for j in range(cm.shape[1]):\n        ax.text(j, i, cm[i, j], ha='center', va='center',\n                color='white' if cm[i, j] > cm.max() / 2 else 'black')\nax.set_xlabel('predicted'); ax.set_ylabel('true'); ax.set_title('Confusion matrix (validation)')\nfig.colorbar(im, shrink=0.8); plt.tight_layout(); plt.show()"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Where does it fail? — misclassified gallery"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "val_images = np.concatenate([x.numpy() for x, _ in val_ds]).astype('uint8')\nwrong = np.where(y_pred != y_true)[0]\nprint(f\"{len(wrong)} / {len(y_true)} validation images misclassified\")\n\nshow = wrong[np.argsort(-y_prob[wrong].max(axis=1))][:12]   # most confident mistakes first\nif len(show):\n    fig, axes = plt.subplots(2, 6, figsize=(16, 6))\n    for ax, idx in zip(axes.flat, show):\n        ax.imshow(val_images[idx]); ax.axis('off')\n        ax.set_title(f\"true: {class_names[y_true[idx]]}\\npred: {class_names[y_pred[idx]]} \"\n                     f\"({y_prob[idx].max():.0%})\", fontsize=9)\n    for ax in axes.flat[len(show):]: ax.axis('off')\n    plt.suptitle('Most confident mistakes', y=1.03); plt.tight_layout(); plt.show()"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 9 · Try your own photo\nRun the cell, pick a flower photo from your device, get the top-3 guesses."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "try:\n    from google.colab import files\n    uploaded = files.upload()\n    for name in uploaded:\n        img = tf.keras.utils.load_img(name, target_size=IMG_SIZE)\n        arr = tf.keras.utils.img_to_array(img)[None, ...]\n        probs = model.predict(arr, verbose=0)[0]\n        top3 = probs.argsort()[::-1][:3]\n        plt.figure(figsize=(3.2, 3.2)); plt.imshow(img); plt.axis('off')\n        plt.title(\"\\n\".join(f\"{class_names[i]}: {probs[i]:.1%}\" for i in top3), fontsize=10)\n        plt.show()\nexcept ImportError:\n    print(\"Not running in Colab — point `name` at a local file instead.\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 10 · Save & export\nSaves the full Keras model and converts to **TFLite** (MobileNetV2's natural habitat — phones and edge devices)."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "model.save('flower_mobilenetv2.keras')\nprint(\"Saved flower_mobilenetv2.keras \"\n      f\"({os.path.getsize('flower_mobilenetv2.keras') / 1e6:.1f} MB)\")\n\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\ntflite_model = converter.convert()\nwith open('flower_mobilenetv2.tflite', 'wb') as f:\n    f.write(tflite_model)\nprint(f\"Saved flower_mobilenetv2.tflite ({len(tflite_model) / 1e6:.1f} MB, quantized)\")\n\n# In Colab: download via the files panel on the left, or:\n# from google.colab import files; files.download('flower_mobilenetv2.tflite')"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "---\n### Ideas to push further\n- Swap the backbone: `EfficientNetV2B0` usually adds a couple of points\n- Class weights or oversampling (dandelion has the most images, rose the fewest)\n- `tf.keras.layers.RandomBrightness` for tougher lighting robustness\n- Grad-CAM to see *where* the model looks before it says \"tulip\"\n\n*Notebook crafted at sloppy.live — vibecoded live with chat 🌻*"
  }
 ]
}