--- language: en tags: - vision - image-classification - flowers - mobilenetv2 - transfer-learning - keras - tensorflow datasets: - oxford_flowers metrics: - accuracy license: mit pipeline_tag: image-classification --- # 🌸 MobileNetV2 Flower Classifier: Model Registry & Technical Specification [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Model%20Hub-yellow.svg)](https://huggingface.co/) [![TensorFlow](https://img.shields.io/badge/TensorFlow-2.x-orange.svg?logo=tensorflow&logoColor=white)](https://www.tensorflow.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![MLflow](https://img.shields.io/badge/MLflow-Experiment%20Tracking-0194E2.svg?logo=mlflow&logoColor=white)](https://mlflow.org/) [![Python](https://img.shields.io/badge/Python-3.10%2B-blue.svg?logo=python&logoColor=white)](https://www.python.org/) This directory serves as the centralized **Model Registry** module within the **`MLOpsPortfolioExercise`** production system. When synchronized with the Hugging Face Hub, this document acts as the official **Model Card** and operational manual for model governance, consumption, deployment, and optimization. --- ## 📑 Table of Contents 1. [Model Architecture & Specifications](#1-model-architecture--specifications) 2. [Quickstart: Download & Inference](#2-quickstart-download--inference) 3. [Model Registry & MLOps Architecture](#3-model-registry--mlops-architecture) - [Beginner Intuition & Analogy](#beginner-friendly-intuition) - [Enterprise MLOps Definition & 5 Core Pillars](#enterprise-mlops-architecture) - [The 3-Repository System](#the-3-repository-system) 4. [Directory Structure & Artifact Manifest](#4-directory-structure--artifact-manifest) 5. [Publishing Guide to Hugging Face Model Hub](#5-publishing-guide-to-hugging-face-model-hub) - [Prerequisites & Access Token](#prerequisites-get-your-hugging-face-token) - [Publishing Methods (A, B, C, D)](#publishing-methods) - [Verification & Smoke Testing](#verification-script) 6. [Model Improvement Strategies & Roadmap](#6-model-improvement-strategies--roadmap) - [Baseline vs. Target Performance Matrix](#baseline-vs-target-performance) - [The 7 Concrete Improvement Pillars](#the-7-concrete-improvement-pillars) - [Roadmap & Action Item Matrix](#implementation-roadmap--action-matrix) --- ## 1. Model Architecture & Specifications ### 🏛️ Architecture Overview The production model utilizes transfer learning using a lightweight convolutional backbone optimized for real-time mobile and web inference. * **Base Architecture**: MobileNetV2 (pre-trained on ImageNet, top classification layers omitted, `include_top=False`, `pooling="avg"`). * **Classification Head**: `Dense(512, activation="relu")` $\to$ `Dropout(0.2)` $\to$ `Dense(5, activation="softmax")`. * **Target Classes (5)**: `daisy`, `dandelion`, `roses`, `sunflowers`, `tulips`. * **Input Resolution**: `(180, 180, 3)` RGB. * **Input Scaling**: Pixel values scaled to the range $[-1, 1]$ via $x_{\text{norm}} = \frac{x}{127.5} - 1.0$. * **Serialized Model Weights**: `flower_model.keras` (~13.6 MB). * **Metadata & Config**: `classes.json`, `config.json`. * **Experiment Run**: Tracked in MLflow under `Flower_Classification_DAI6`. ### 🎯 Intended Use & Scope * **Primary Use Case**: Real-time identification of flower species from consumer photographs via the FastAPI serving layer (`src/flower_web.py`). * **Intended Users**: Educational applications, botanical cataloging tools, and automated floriculture classification services. * **Limitations & Out-of-Scope**: * Unopened flower buds or wilted flowers with unexposed petals may exhibit lower confidence. * Inputs significantly cropped, heavily obscured, or lacking botanical features will trigger degraded predictions. * The current model supports only the 5 target species; out-of-domain flora will be mapped to the closest matching class. --- ## 2. Quickstart: Download & Inference ### Method 1: Load Directly from Hugging Face Hub (Recommended for Remote Serving) ```python import cv2 import json import numpy as np import tensorflow as tf from huggingface_hub import hf_hub_download # 1. Download model weights and class labels from Hugging Face Hub REPO_ID = "nina357/flower-classification-model" model_path = hf_hub_download(repo_id=REPO_ID, filename="flower_model.keras") classes_path = hf_hub_download(repo_id=REPO_ID, filename="classes.json") # 2. Load model and class names model = tf.keras.models.load_model(model_path) with open(classes_path, "r", encoding="utf-8") as f: class_names = json.load(f) # 3. Preprocess input image (180x180 RGB, normalized to [-1, 1]) image = cv2.imread("sample_flower.jpg") image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_resized = cv2.resize(image_rgb, (180, 180)) image_normalized = (image_resized / 127.5) - 1.0 input_batch = np.expand_dims(image_normalized, axis=0) # 4. Run prediction probabilities = model.predict(input_batch)[0] predicted_index = int(np.argmax(probabilities)) confidence = float(probabilities[predicted_index]) print(f"Predicted Flower: {class_names[predicted_index]} ({confidence * 100:.2f}%)") ``` ### Method 2: Load from Local Repository Artifacts ```python import json import numpy as np import tensorflow as tf # Load directly from the models/ directory model = tf.keras.models.load_model("models/flower_model.keras") with open("models/classes.json", "r", encoding="utf-8") as f: class_names = json.load(f) # Batch inference sample_batch = np.random.uniform(-1.0, 1.0, size=(1, 180, 180, 3)).astype(np.float32) preds = model.predict(sample_batch) print("Output logits shape:", preds.shape) ``` --- ## 3. Model Registry & MLOps Architecture ### Beginner-Friendly Intuition When training deep learning models over several weeks, practitioners often end up with disorganized artifacts: * `flower_model.keras` * `flower_model_final.keras` * `flower_model_final_v2.keras` * `flower_model_best_accuracy_final.keras` When deploying to production, critical questions emerge: * *Which exact dataset and train/test split was this model trained on?* * *What hyperparameters and learning rate schedule were used?* * *Which code commit generated these weights?* * *What was the validation accuracy on ambiguous classes like roses vs. tulips?* Without a system of record, binary weights are anonymous blobs. **The Analogy**: * **GitHub** stores, reviews, and versions your **Code**. * **DVC / Cloud Object Stores** version and snapshot your **Data**. * **Model Registry** governs, versions, audits, and delivers your **Trained Models**. Just as modern app marketplaces provide version tags, system dependencies, changelogs, and release stages, a Model Registry maintains immutable lineage and transition rules for models moving from experimentation to production. --- ### Enterprise MLOps Architecture > **A Model Registry is a centralized, governed metadata store and artifact repository that manages the complete lifecycle of machine learning models from experimentation and validation to production serving, monitoring, and retirement.** ```mermaid flowchart LR subgraph Dev["1. Training & Lineage"] Code["Code Repo
(Git Commit SHA)"] --> Train["Training Run"] Data["Data Repo
(DVC Version Hash)"] --> Train Hyper["Hydra Config
(Hyperparameters)"] --> Train end subgraph Registry["2. Model Registry (Hugging Face / MLflow)"] Train --> Artifacts["Model Artifacts
(Weights, classes.json, Model Card)"] Artifacts --> Versioning["Version Tracking
(v1.0.0, v1.1.0)"] Versioning --> Lifecycle["Stage Transitions
(Staging ➔ Production ➔ Archived)"] end subgraph Prod["3. Production Serving"] Lifecycle -->|CI/CD Automated Pull| API["FastAPI Web Service
(Docker Container)"] end ``` #### The 5 Core Pillars of a Model Registry 1. **Artifact Storage**: Securely stores serialized weights (`.keras`, `.safetensors`, `.onnx`), label mappings (`classes.json`), and architecture configurations (`config.json`). 2. **Lineage & Provenance**: Links every registered model to its originating Git commit, DVC dataset hash, training duration, and author. 3. **Stage & Lifecycle Governance**: Enforces clear environment boundaries: * `Experimental` $\to$ Exploratory runs and prototyping. * `Staging` $\to$ Validated against integration tests, awaiting QA approval. * `Production` $\to$ Actively serving live consumer requests. * `Archived` $\to$ Deprecated models preserved for audit trails and zero-downtime rollback. 4. **Governance & Model Cards**: Structured documentation capturing assumptions, performance metrics, data distribution, and ethical considerations. 5. **Serving Integration**: Decouples API services from static file paths, allowing microservices to query for active production tags dynamically. --- ### The 3-Repository System To follow production-grade MLOps best practices, responsibilities are cleanly separated into three independent repositories: | Repository | Host Platform | Technology | Primary Responsibility | Key Contents | | :--- | :--- | :--- | :--- | :--- | | **1. Code Repository** | GitHub | Git, Python, Docker | Orchestration, pipelines, API serving, tests | `src/`, `conf/`, `tests/`, `Dockerfile`, CI/CD workflows | | **2. Model Registry** | Hugging Face Hub | Git LFS, Hugging Face API | Model versioning, weights storage, model cards | `flower_model.keras`, `classes.json`, `config.json`, `README.md` | | **3. Data Repository** | GitHub / DVC Remote | DVC, S3 / Cloud Storage | Raw images, preprocessed splits, versioning pointers | `data/flower_photos/`, `.dvc`, data download & verification scripts | --- ## 4. Directory Structure & Artifact Manifest Below is the current layout of the `models/` directory in this repository: ```text MLOpsPortfolioExercise/models/ ├── .gitattributes # Git LFS tracking rules for binary weights (*.keras, *.h5, *.tflite) ├── .gitkeep # Directory preservation anchor ├── README.md # Official Hugging Face Model Card & technical reference ├── Running Training Locally.md # Local training, SQLite MLflow & FastAPI guide (excluded from HF) ├── Running Training in Google Cloud.md # Cloud Run Jobs, Neon Postgres MLflow & GCS guide (excluded from HF) ├── Dockerfile.train # Cloud Run Job training container (excluded from HF) ├── Dockerfile.mlflow # Cloud Run MLflow server with psycopg v3 + GCS (excluded from HF) ├── entrypoint_train.sh # DVC pull + remote MLflow training launcher (excluded from HF) ├── deploy_mlflow.sh # 1-command Cloud Run MLflow deploy via .env (excluded from HF) ├── cloudbuild.yaml # Google Cloud Build config for trainer image (excluded from HF) ├── cloudbuild.mlflow.yaml # Google Cloud Build config for MLflow server image (excluded from HF) ├── publish_to_huggingface.py # Automated 1-click deployment script to Hugging Face Hub ├── flower_model.keras # Promoted Champion weights (~13.6 MB, git-ignored / uploaded to HF) ├── classes.json # Champion target class label array (uploaded to HF) ├── config.json # Champion architecture, lineage & evaluation metadata (uploaded to HF) ├── runs/ # Per-run Challenger archives (git-ignored & excluded from HF) ├── mlflow.db # Local SQLite MLflow tracking DB (git-ignored & excluded from HF) └── mlartifacts/ # Local MLflow artifact store (git-ignored & excluded from HF) ``` ### Artifact Manifest | File / Folder | Uploaded to HF? | Description | | :--- | :---: | :--- | | **`flower_model.keras`** | **Yes** | Promoted Champion MobileNetV2 weights (~13.6 MB). Auto-downloaded on boot by `src/flower_web.py`. | | **`classes.json`** | **Yes** | JSON array of ordered class names: `["daisy", "dandelion", "roses", "sunflowers", "tulips"]`. | | **`config.json`** | **Yes** | Champion architecture specs, Git/DVC lineage, hyperparameters, and validation accuracy. | | **`README.md`** | **Yes** | Official Hugging Face Model Card with YAML metadata frontmatter. | | **`publish_to_huggingface.py`** | No *(ignored)* | 1-click upload utility using `huggingface_hub` (`ignore_patterns` filters out all infra/local files). | | **`Dockerfile.*` / `*.sh` / `cloudbuild*.yaml`** | No *(ignored)* | Cloud Run & Cloud Build infrastructure files kept organized inside `models/`. | | **`Running Training *.md`** | No *(ignored)* | Local and Google Cloud operational runbooks. | | **`runs/` / `mlflow.db` / `mlartifacts/`** | No *(ignored)* | Local Challenger run archives and local SQLite MLflow tracking store. | --- ## 5. Publishing Guide to Hugging Face Model Hub ### Prerequisites: Get Your Hugging Face Token 1. Sign up or log in at [Hugging Face](https://huggingface.co/). 2. Navigate to **Settings** $\to$ **Access Tokens**: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens). 3. Click **Create new token**: * **Token Type**: `Write` (required for artifact uploads). * **Token Name**: `mlops-model-token`. 4. Copy your generated token (format `hf_...`). --- ### Publishing Methods #### Method A: Automated Python Utility (Recommended) The repository provides a deployment script [`models/publish_to_huggingface.py`](./publish_to_huggingface.py) that automatically creates the remote repository (if not already existing), filters development checkpoints, and uploads the required production artifacts: ```bash # 1. Authenticate with Hugging Face CLI huggingface-cli login # (Paste your 'hf_...' write token when prompted; select 'n' for git credential helper if unsure) # 2. Run the deployment script from the project root python models/publish_to_huggingface.py --repo-id "nina357/flower-classification-model" ``` To create a **private** repository, add the `--private` flag: ```bash python models/publish_to_huggingface.py --repo-id "nina357/flower-classification-model" --private ``` > [!NOTE] > **What happens if you re-run `publish_to_huggingface.py`?** > * It safely reuses your existing Hugging Face repository (`exist_ok=True`) and creates a **new Git commit on `main`** with only the updated files (`README.md`, and any newly promoted `flower_model.keras`, `classes.json`, `config.json`). > * It is **additive** — it will **not** delete existing weights already hosted on Hugging Face if you don't have them locally. > * All local/infra files (`Dockerfile*`, `*.sh`, `cloudbuild*.yaml`, `mlflow.db`, `mlartifacts/`, `runs/`, `Running Training *.md`) are automatically filtered out by `ignore_patterns`. --- #### Method B: Hugging Face CLI Direct Upload ```bash # 1. Login huggingface-cli login # 2. Upload the models directory directly huggingface-cli upload nina357/flower-classification-model ./models . --repo-type model ``` --- #### Method C: Git LFS Manual Setup If you prefer operating through standard Git commands: ```bash # 1. Install Git LFS (macOS example) brew install git-lfs git lfs install # 2. Clone your newly created Hugging Face repository cd /Users/nooshin/Uni/Data/data6 git clone https://huggingface.co/nina357/flower-classification-model cd flower-classification-model # 3. Copy production artifacts cp /Users/nooshin/Uni/Data/data6/MLOpsPortfolioExercise/models/flower_model.keras . cp /Users/nooshin/Uni/Data/data6/MLOpsPortfolioExercise/models/classes.json . cp /Users/nooshin/Uni/Data/data6/MLOpsPortfolioExercise/models/config.json . cp /Users/nooshin/Uni/Data/data6/MLOpsPortfolioExercise/models/README.md . cp /Users/nooshin/Uni/Data/data6/MLOpsPortfolioExercise/models/.gitattributes . # 4. Commit and push git add . git commit -m "feat: release initial v1.0.0 flower classification model" git push origin main ``` --- #### Method D: Browser Drag & Drop 1. Go to [https://huggingface.co/new](https://huggingface.co/new). 2. Set **Model name** to `flower-classification-model`, choose license `mit`, and click **Create model**. 3. In the repository page, click **Files and versions** $\to$ **Add file** $\to$ **Upload files**. 4. Drag and drop the 5 essential files from `MLOpsPortfolioExercise/models/`: * `flower_model.keras` * `classes.json` * `config.json` * `README.md` * `.gitattributes` 5. Click **Commit changes to main**. --- ### Verification Script Verify that your published model downloads and instantiates correctly from any workstation: ```python import json import tensorflow as tf from huggingface_hub import hf_hub_download REPO_ID = "nina357/flower-classification-model" # Download artifacts model_path = hf_hub_download(repo_id=REPO_ID, filename="flower_model.keras") classes_path = hf_hub_download(repo_id=REPO_ID, filename="classes.json") config_path = hf_hub_download(repo_id=REPO_ID, filename="config.json") # Instantiate and verify model = tf.keras.models.load_model(model_path) with open(classes_path, "r", encoding="utf-8") as f: class_names = json.load(f) with open(config_path, "r", encoding="utf-8") as f: config = json.load(f) print(f"✅ Model successfully verified from Hugging Face Hub!") print(f" Architecture: {config.get('model_type')} ({model.name})") print(f" Input Shape: {model.input_shape}") print(f" Target Classes: {class_names}") ``` --- ## 6. Model Improvement Strategies & Roadmap ### Baseline vs. Target Performance The table below contrasts the baseline implementation against architectural and operational enhancements designed for production MLOps: | Evaluation Aspect | Baseline Implementation (`src/flower_model.py`) | Target Optimized Model | Expected Engineering Impact | | :--- | :--- | :--- | :--- | | **Input Preprocessing** | Raw pixel values $[0, 255]$ without rescaling | Explicit `Rescaling(1./127.5, offset=-1.0)` | 🚀 **+5% to +8% Accuracy** (Immediate Fix) | | **Backbone Training** | 100% Frozen MobileNetV2 (`trainable=False`) | **Two-Stage Fine-Tuning** (unfreeze top 30–50 layers) | 🎯 **+4% to +7% Accuracy** | | **Data Augmentation** | 5 static offline copies saved to disk | **Online Dynamic Augmentation** (Flip, Zoom, Jitter) | 🛡️ **Prevents memorization; saves 2.5 GB disk space** | | **Backbone Choice** | MobileNetV2 (3.5M params, 2018) | **EfficientNetV2-B0** or **ConvNeXt-Tiny** | 📈 **+3% to +5% Accuracy** at equivalent latency | | **Learning Rate** | Constant learning rate ($10^{-3}$) | **Cosine Decay Schedule** + `ReduceLROnPlateau` | 📉 **Smoother convergence; avoids local sub-optima** | | **Loss & Regularization** | Standard Crossentropy, single Dropout(0.2) | **Label Smoothing (0.1)** + AdamW weight decay | 🎯 **Calibrates probabilities on ambiguous petal borders** | | **Evaluation Metrics** | Top-1 Accuracy only | **Per-class F1, Confusion Matrix logged to MLflow** | 🔍 **Identifies subtle misclassifications (roses vs. tulips)** | | **Inference Runtime** | Uncompressed Keras model (~14 MB) | **TFLite FP16 / INT8 Quantization** | ⚡ **3x faster FastAPI inference; 75% smaller storage** | --- ### The 7 Concrete Improvement Pillars #### Pillar 1: Input Preprocessing & Rescaling (Critical Fix) * **Problem**: `tf.keras.preprocessing.image_dataset_from_directory` outputs RGB values in $[0, 255]$. However, MobileNetV2 expects normalized inputs in $[-1, 1]$: $$\text{Pixel}_{\text{norm}} = \frac{\text{Pixel}}{127.5} - 1.0$$ Passing raw $[0, 255]$ causes internal activation saturation and distributional mismatch. * **Solution**: Place `layers.Rescaling` as the first layer in the sequential model: ```python # In src/flower_model.py -> build_model() model = keras.Sequential( [ layers.Input(shape=input_shape), # Normalize pixel range [0, 255] -> [-1, 1] for MobileNetV2 layers.Rescaling(1.0 / 127.5, offset=-1.0, name="mobilenetv2_rescaling"), base_model, layers.Dense(dense_units, activation="relu", name="feature_dense"), layers.Dropout(dropout_rate, name="feature_dropout"), layers.Dense(num_classes, activation="softmax", name="flower_probabilities"), ], name="flower_classifier_mobilenetv2", ) ``` > **Key MLOps Advantage**: Embedding normalization directly inside the Keras computational graph ensures that the serving layer (`src/flower_web.py`) automatically preprocesses images without requiring separate client-side scaling logic. --- #### Pillar 2: Two-Stage Fine-Tuning * **Problem**: A completely frozen backbone prevents the convolutional kernels from adapting to domain-specific botanical morphology (petal curvature, stamen patterns, sepal structures). * **Solution**: Execute two distinct training stages: 1. **Stage 1 (Warmup)**: Train only the classification head for 5 epochs with $\eta = 10^{-3}$. 2. **Stage 2 (Fine-Tuning)**: Unfreeze the top 30–50 layers of MobileNetV2 and train with a reduced learning rate ($\eta = 10^{-5}$). ```mermaid flowchart LR subgraph Stage1["Stage 1: Warmup (5 Epochs)"] BaseFrozen["MobileNetV2 Backbone
(100% Frozen)"] -.-> Head["Custom Dense Head
(Trainable, lr=1e-3)"] end subgraph Stage2["Stage 2: Fine-Tuning (15 Epochs)"] LowerFrozen["Lower 100 Layers
(Frozen Low-Level Features)"] --> TopUnfrozen["Top 40-50 Layers
(Unfrozen, lr=1e-5)"] TopUnfrozen --> Head2["Custom Dense Head
(Trainable, lr=1e-5)"] end Stage1 --> Stage2 ``` ```python def fine_tune_model( model: keras.Model, unfreeze_from_layer: int = 100, fine_tune_learning_rate: float = 1e-5, ) -> keras.Model: """Unfreeze top backbone layers and recompile with a lower learning rate.""" base_model = model.get_layer("mobilenetv2_1.00_180") base_model.trainable = True # Keep initial layers frozen for layer in base_model.layers[:unfreeze_from_layer]: layer.trainable = False model.compile( optimizer=keras.optimizers.Adam(learning_rate=fine_tune_learning_rate), loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) return model ``` --- #### Pillar 3: Dynamic Online Data Augmentation & Color Jitter * **Problem**: Generating 5 static offline copies on disk consumes ~2.5 GB and causes the model to memorize the same fixed augmentations across epochs. * **Solution**: Implement real-time GPU/data-pipeline transformations using Keras preprocessing layers: ```python data_augmentation = keras.Sequential( [ layers.RandomFlip("horizontal"), layers.RandomRotation(0.2), layers.RandomZoom(0.2), layers.RandomTranslation(0.1, 0.1), layers.RandomBrightness(factor=0.2), layers.RandomContrast(factor=0.2), ], name="online_augmentation", ) ``` * **Advanced Strategy (MixUp / CutMix)**: Linearly blending pairs of images and labels: $$\tilde{x} = \lambda x_i + (1 - \lambda) x_j, \quad \tilde{y} = \lambda y_i + (1 - \lambda) y_j$$ forces the model to focus on subtle floral attributes rather than background context (e.g., grass or soil). --- #### Pillar 4: Modern Backbone Exploration via Hydra | Backbone | Parameter Count | Top-1 ImageNet | Key Advantage for Floral Datasets | | :--- | :---: | :---: | :--- | | **MobileNetV2** (Current Baseline) | 3.5M | 71.8% | Lightweight, fast edge inference | | **EfficientNetV2-B0** | 5.9M | **78.7%** | Native normalization, progressive regularization, superior accuracy-to-parameter ratio | | **ConvNeXt-Tiny** | 28.6M | **82.1%** | Modern 7x7 depthwise convolutions, robust botanical texture capture | By defining [`conf/model/efficientnet_v2.yaml`](../conf/model/): ```yaml name: efficientnet_v2_b0 backbone: EfficientNetV2B0 classes: 5 dense_units: 512 dropout_rate: 0.2 trainable_base: false pooling: avg ``` Architectures can be swapped from the CLI without code changes: ```bash python src/flower_model.py model=efficientnet_v2 ``` --- #### Pillar 5: Learning Rate Scheduling, AdamW & Label Smoothing * **Cosine Decay with Warmup**: Prevents gradient shocks during initial epochs and gracefully converges toward narrow minima: ```python lr_schedule = keras.optimizers.schedules.CosineDecay( initial_learning_rate=1e-3, decay_steps=total_steps, alpha=0.01, ) optimizer = keras.optimizers.AdamW(learning_rate=lr_schedule, weight_decay=1e-4) ``` * **Label Smoothing Regularization**: Ambiguous flower samples (e.g. unopened rosebuds looking like tulips) create overconfident one-hot labels ($y_{\text{hard}} = [0, 1, 0, 0, 0]$). Smoothing converts targets to calibrated distributions ($y_{\text{smooth}} = [0.025, 0.9, 0.025, 0.025, 0.025]$): ```python loss = keras.losses.CategoricalCrossentropy(label_smoothing=0.1) ``` --- #### Pillar 6: Per-Class Evaluation & Confusion Matrix in MLflow Overall accuracy can mask underperformance in specific categories. Logging per-class F1-scores and confusion matrices ensures complete operational transparency: ```python from sklearn.metrics import classification_report, confusion_matrix import matplotlib.pyplot as plt import seaborn as sns import mlflow def log_evaluation_artifacts(model: keras.Model, val_dataset: tf.data.Dataset, class_names: list[str]) -> None: y_true, y_pred = [], [] for images, labels in val_dataset: preds = model.predict(images, verbose=0) y_true.extend(labels.numpy()) y_pred.extend(np.argmax(preds, axis=1)) # Log per-class metrics report = classification_report(y_true, y_pred, target_names=class_names, output_dict=True) for class_name, metrics in report.items(): if isinstance(metrics, dict): mlflow.log_metric(f"{class_name}_f1_score", metrics["f1-score"]) # Render confusion matrix cm = confusion_matrix(y_true, y_pred) fig, ax = plt.subplots(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=class_names, yticklabels=class_names, ax=ax) ax.set_ylabel("True Category") ax.set_xlabel("Predicted Category") ax.set_title("Flower Classification Confusion Matrix") plt.tight_layout() plt.savefig("confusion_matrix.png") plt.close() mlflow.log_artifact("confusion_matrix.png") ``` --- #### Pillar 7: Inference Acceleration (TFLite & Quantization) * **Problem**: The raw `.keras` model (~13.6 MB) uses 32-bit floating point arithmetic, consuming unnecessary memory and adding latency to web endpoints. * **Solution**: Quantize the model to **TensorFlow Lite FP16 / INT8**: ```python converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_types = [tf.float16] tflite_model = converter.convert() with open("models/flower_model_fp16.tflite", "wb") as f: f.write(tflite_model) ``` * **Serving Benefits**: * **Model Size**: Decreases from **13.6 MB to ~3.7 MB** (73% reduction). * **Inference Latency**: Drops from ~45 ms down to **~14 ms per image** on commodity CPUs. * **Throughput**: Significantly higher request concurrency in the FastAPI service. --- ### Implementation Roadmap & Action Matrix ```mermaid flowchart TD subgraph Phase1["Phase 1: Quick Wins (1 Day)"] P1A["Add Rescaling(1./127.5, offset=-1.0)"] P1B["Add EarlyStopping (restore_best_weights=True)"] P1C["Add ReduceLROnPlateau Callback"] end subgraph Phase2["Phase 2: High Impact (2-3 Days)"] P2A["Implement 2-Stage Fine-Tuning"] P2B["Log Confusion Matrix & Per-Class F1 to MLflow"] P2C["Migrate to Dynamic Online Keras Augmentation"] end subgraph Phase3["Phase 3: Production Scaling (3-5 Days)"] P3A["Benchmark EfficientNetV2-B0 via Hydra"] P3B["Run Hyperparameter Sweeps (Dense Units, LR)"] P3C["Export TFLite FP16 Model for FastAPI Serving"] end Phase1 --> Phase2 Phase2 --> Phase3 ``` #### Action Item Matrix | Priority | Action Item | Target File | Complexity | Expected Impact | | :---: | :--- | :--- | :---: | :--- | | **P0** | Insert `layers.Rescaling(1./127.5, offset=-1.0)` | [`src/flower_model.py`](../src/flower_model.py) | Low | **Immediate +5% to +8% accuracy boost** | | **P0** | Add `EarlyStopping` & `ReduceLROnPlateau` callbacks | [`src/flower_model.py`](../src/flower_model.py) | Low | **Eliminates overfitting and plateau stagnation** | | **P1** | Implement two-stage fine-tuning (warmup + top layers) | [`src/flower_model.py`](../src/flower_model.py) | Medium | **Adapts convolutional filters to floral features** | | **P1** | Replace disk augmentation with dynamic Keras layers | [`src/flower_data.py`](../src/flower_data.py) | Medium | **Frees 2.5 GB disk space; enables infinite variation** | | **P1** | Log Confusion Matrix and classification reports to MLflow | [`src/flower_model.py`](../src/flower_model.py) | Low | **Provides actionable visibility into class confusion** | | **P2** | Add `EfficientNetV2` Hydra configuration | [`conf/model/`](../conf/model/) | Low | **Provides modern architectural baseline** | | **P2** | Export TFLite FP16 optimized weights | [`src/flower_model.py`](../src/flower_model.py) | Low | **3x faster API responses in FastAPI serving** |