/ Модель

Характеристики

Лицензия
MIT
Архитектура
mobilenetv2 · dense
Опубликована
19 ноя 2026

flower-classification-model

Классификация изображенийИзображение → label3 профессии
136скачиваний за 30 дней0лайковвеса обновлены19 ноя 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Компактная модель MobileNetV2 определяет на фотографии один из пяти распространённых видов цветов.

Это модель компьютерного зрения на основе MobileNetV2, дообученной методом transfer learning для распознавания пяти видов цветов: ромашек, одуванчиков, роз, подсолнухов и тюльпанов. Модель принимает RGB-изображения размером 180 × 180 пикселей и выдаёт вероятности принадлежности к одному из пяти классов. Реализация использует TensorFlow/Keras; базовая сеть предварительно обучена на ImageNet, а классификационная голова состоит из полносвязного слоя на 512 нейронов, Dropout и выходного слоя softmax.

Модель предназначена для определения вида цветка на фотографиях, например в приложениях для каталогизации растений, учебных проектах и сервисах для флористики. Она компактна и рассчитана на быстрое применение в веб- и мобильных сценариях. Карточка описывает ограничения: качество может снижаться для закрытых или увядших бутонов, сильно обрезанных или закрытых объектов; неизвестные виды цветов будут отнесены к ближайшему из пяти классов. Лицензия — MIT.

Сценарии применения

  • определение вида цветка на фотографии
  • автоматическая сортировка фотографий ромашек, одуванчиков, роз, подсолнухов и тюльпанов
  • классификация цветов в учебном проекте по компьютерному зрению
  • добавление распознавания пяти видов цветов в веб- или мобильное приложение

Ограничения

Классификатор распознаёт только пять заявленных видов, поэтому другие цветы будут отнесены к ближайшему классу. Закрытые или увядшие бутоны, сильная обрезка и遮遮ённые изображения могут снижать уверенность предсказаний.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

🌸 MobileNetV2 Flower Classifier: Model Registry & Technical Specification

Hugging Face TensorFlow License: MIT MLflow Python

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
  2. Quickstart: Download & Inference
  3. Model Registry & MLOps Architecture
  4. Directory Structure & Artifact Manifest
  5. Publishing Guide to Hugging Face Model Hub
  6. Model Improvement Strategies & Roadmap

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)

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

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.

flowchart LR
    subgraph Dev["1. Training & Lineage"]
        Code["Code Repo<br/>(Git Commit SHA)"] --> Train["Training Run"]
        Data["Data Repo<br/>(DVC Version Hash)"] --> Train
        Hyper["Hydra Config<br/>(Hyperparameters)"] --> Train
    end

    subgraph Registry["2. Model Registry (Hugging Face / MLflow)"]
        Train --> Artifacts["Model Artifacts<br/>(Weights, classes.json, Model Card)"]
        Artifacts --> Versioning["Version Tracking<br/>(v1.0.0, v1.1.0)"]
        Versioning --> Lifecycle["Stage Transitions<br/>(Staging ➔ Production ➔ Archived)"]
    end

    subgraph Prod["3. Production Serving"]
        Lifecycle -->|CI/CD Automated Pull| API["FastAPI Web Service<br/>(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:

RepositoryHost PlatformTechnologyPrimary ResponsibilityKey Contents
1. Code RepositoryGitHubGit, Python, DockerOrchestration, pipelines, API serving, testssrc/, conf/, tests/, Dockerfile, CI/CD workflows
2. Model RegistryHugging Face HubGit LFS, Hugging Face APIModel versioning, weights storage, model cardsflower_model.keras, classes.json, config.json, README.md
3. Data RepositoryGitHub / DVC RemoteDVC, S3 / Cloud StorageRaw images, preprocessed splits, versioning pointersdata/flower_photos/, .dvc, data download & verification scripts

4. Directory Structure & Artifact Manifest

Below is the current layout of the models/ directory in this repository:

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 / FolderUploaded to HF?Description
flower_model.kerasYesPromoted Champion MobileNetV2 weights (~13.6 MB). Auto-downloaded on boot by src/flower_web.py.
classes.jsonYesJSON array of ordered class names: ["daisy", "dandelion", "roses", "sunflowers", "tulips"].
config.jsonYesChampion architecture specs, Git/DVC lineage, hyperparameters, and validation accuracy.
README.mdYesOfficial Hugging Face Model Card with YAML metadata frontmatter.
publish_to_huggingface.pyNo (ignored)1-click upload utility using huggingface_hub (ignore_patterns filters out all infra/local files).
Dockerfile.* / *.sh / cloudbuild*.yamlNo (ignored)Cloud Run & Cloud Build infrastructure files kept organized inside models/.
Running Training *.mdNo (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.
  2. Navigate to Settings $\to$ Access 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 that automatically creates the remote repository (if not already existing), filters development checkpoints, and uploads the required production artifacts:

# 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:

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

# 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:

# 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.
  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:

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 AspectBaseline Implementation (src/flower_model.py)Target Optimized ModelExpected Engineering Impact
Input PreprocessingRaw pixel values $[0, 255]$ without rescalingExplicit Rescaling(1./127.5, offset=-1.0)🚀 +5% to +8% Accuracy (Immediate Fix)
Backbone Training100% Frozen MobileNetV2 (trainable=False)Two-Stage Fine-Tuning (unfreeze top 30–50 layers)🎯 +4% to +7% Accuracy
Data Augmentation5 static offline copies saved to diskOnline Dynamic Augmentation (Flip, Zoom, Jitter)🛡️ Prevents memorization; saves 2.5 GB disk space
Backbone ChoiceMobileNetV2 (3.5M params, 2018)EfficientNetV2-B0 or ConvNeXt-Tiny📈 +3% to +5% Accuracy at equivalent latency
Learning RateConstant learning rate ($10^{-3}$)Cosine Decay Schedule + ReduceLROnPlateau📉 Smoother convergence; avoids local sub-optima
Loss & RegularizationStandard Crossentropy, single Dropout(0.2)Label Smoothing (0.1) + AdamW weight decay🎯 Calibrates probabilities on ambiguous petal borders
Evaluation MetricsTop-1 Accuracy onlyPer-class F1, Confusion Matrix logged to MLflow🔍 Identifies subtle misclassifications (roses vs. tulips)
Inference RuntimeUncompressed 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:
# 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}$).
flowchart LR
    subgraph Stage1["Stage 1: Warmup (5 Epochs)"]
        BaseFrozen["MobileNetV2 Backbone<br/>(100% Frozen)"] -.-> Head["Custom Dense Head<br/>(Trainable, lr=1e-3)"]
    end
    subgraph Stage2["Stage 2: Fine-Tuning (15 Epochs)"]
        LowerFrozen["Lower 100 Layers<br/>(Frozen Low-Level Features)"] --> TopUnfrozen["Top 40-50 Layers<br/>(Unfrozen, lr=1e-5)"]
        TopUnfrozen --> Head2["Custom Dense Head<br/>(Trainable, lr=1e-5)"]
    end
    Stage1 --> Stage2
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:
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

BackboneParameter CountTop-1 ImageNetKey Advantage for Floral Datasets
MobileNetV2 (Current Baseline)3.5M71.8%Lightweight, fast edge inference
EfficientNetV2-B05.9M78.7%Native normalization, progressive regularization, superior accuracy-to-parameter ratio
ConvNeXt-Tiny28.6M82.1%Modern 7x7 depthwise convolutions, robust botanical texture capture

By defining conf/model/efficientnet_v2.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:

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:
    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]$):
    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:

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:
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

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

PriorityAction ItemTarget FileComplexityExpected Impact
P0Insert layers.Rescaling(1./127.5, offset=-1.0)src/flower_model.pyLowImmediate +5% to +8% accuracy boost
P0Add EarlyStopping & ReduceLROnPlateau callbackssrc/flower_model.pyLowEliminates overfitting and plateau stagnation
P1Implement two-stage fine-tuning (warmup + top layers)src/flower_model.pyMediumAdapts convolutional filters to floral features
P1Replace disk augmentation with dynamic Keras layerssrc/flower_data.pyMediumFrees 2.5 GB disk space; enables infinite variation
P1Log Confusion Matrix and classification reports to MLflowsrc/flower_model.pyLowProvides actionable visibility into class confusion
P2Add EfficientNetV2 Hydra configurationconf/model/LowProvides modern architectural baseline
P2Export TFLite FP16 optimized weightssrc/flower_model.pyLow3x faster API responses in FastAPI serving

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Нельзя запустить

Keras/TensorFlow-модели рантайм не загружает.

Ревизия весов
a853082

0 моделей