<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arthur Cartel Foahom Gouabou on Medium]]></title>
        <description><![CDATA[Stories by Arthur Cartel Foahom Gouabou on Medium]]></description>
        <link>https://medium.com/@cartelgouabou?source=rss-3143b6fcc395------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HUGfo4vfrCCAk1bc</url>
            <title>Stories by Arthur Cartel Foahom Gouabou on Medium</title>
            <link>https://medium.com/@cartelgouabou?source=rss-3143b6fcc395------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:43:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cartelgouabou/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Track and Version Your ML Models Like a Pro — With MLflow and Poetry]]></title>
            <link>https://python.plainenglish.io/track-and-version-your-ml-models-like-a-pro-with-mlflow-and-poetry-b3e624d6d4b5?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e624d6d4b5</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[poetry]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 00:05:00 GMT</pubDate>
            <atom:updated>2025-08-05T00:05:00.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>Track and Version Your ML Models Like a Pro — With MLflow and Poetry</h3><p><strong>How to structure, train, log, and reload machine learning models using MLflow in a clean Python project powered by Poetry.</strong><br> <a href="https://github.com/cartelgouabou/Full_stacks_ai_course/tree/main/tools/data_science_toolkit/mlflow_intro/mlflow_quickstart"><em>Full implementation on GitHub</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*7lpabFHA52O-LFpVImVAKw.png" /></figure><h3>Why this matters</h3><p>Managing machine learning workflows isn’t just about writing good models — it’s also about reproducibility, transparency, and clean project structure.</p><p>In this article, I’ll walk you through how to:</p><ul><li>Structure a clean ML project using Poetry</li><li>Log metrics, parameters, and artifacts using MLflow</li><li>Register and version your models</li><li>Reload a model version from the Model Registry for prediction</li></ul><p>The project is organized in two scripts:</p><ul><li>train_and_register.py: trains and registers the model</li><li>load_and_predict.py: reloads the model and makes predictions</li></ul><h3>1. Set Up the Project with Poetry</h3><p>Let’s start by creating a clean Python project using Poetry:</p><pre>poetry new mlflow_quickstart --src<br>cd mlflow_quickstart<br>poetry config virtualenvs.in-project true<br>poetry install<br>poetry add mlflow scikit-learn matplotlib pandas</pre><blockquote>This initializes a Poetry-managed project, sets up a virtual environment in .venv, and installs the required dependencies.</blockquote><h3>2. Launch the MLflow UI</h3><p>In a new terminal:</p><pre>poetry run mlflow ui</pre><p>This command starts the MLflow tracking server locally at <a href="http://localhost:5000/">http://localhost:5000</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_pjy59vDZs3tkpLvg0O3A.png" /><figcaption>MLflow UI dashboard running locally</figcaption></figure><h3>3. Training and Registering the Model</h3><p>Now let’s run the training and registration script:</p><pre>poetry run python src/mlflow_quickstart/train_and_register.py</pre><h3>Step 1: Load and split the dataset</h3><pre>from sklearn.datasets import load_diabetes<br>from sklearn.model_selection import train_test_split<br>X, y = load_diabetes(return_X_y=True)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)</pre><h3>Step 2: Configure MLflow</h3><pre>import mlflow<br>mlflow.set_tracking_uri(&quot;http://localhost:5000&quot;)<br>mlflow.set_experiment(&quot;mlflow_quickstart&quot;)</pre><blockquote>The tracking URI points to your MLflow instance, and set_experiment() groups your runs under a consistent name.</blockquote><h3>Step 3: Train model and log metrics and parameters</h3><pre>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import root_mean_squared_error<br><br>with mlflow.start_run(run_name=&quot;RandomForest_baseline&quot;):<br>    model = RandomForestRegressor(n_estimators=100, max_depth=5)<br>    model.fit(X_train, y_train)<br>    predictions = model.predict(X_test)<br>    rmse = root_mean_squared_error(y_test, predictions)<br><br>    mlflow.log_param(&quot;n_estimators&quot;, 100)<br>    mlflow.log_param(&quot;max_depth&quot;, 5)<br>    mlflow.log_metric(&quot;rmse&quot;, rmse)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jul4jQacFVLggtFRLds9Xw.png" /><figcaption>MLflow experiment showing logged hyperparameters and RMSE</figcaption></figure><h3>Step 4: Log a visual artifact</h3><pre>import matplotlib.pyplot as plt<br>import os<br><br>os.makedirs(&quot;artefacts&quot;, exist_ok=True)<br>fig_path = &quot;artefacts/scatter.png&quot;<br>plt.figure()<br>plt.scatter(y_test, predictions)<br>plt.xlabel(&quot;True Values&quot;)<br>plt.ylabel(&quot;Predictions&quot;)<br>plt.title(&quot;True vs Predicted&quot;)<br>plt.savefig(fig_path)<br>plt.close()<br><br>mlflow.log_artifact(fig_path)</pre><blockquote>MLflow allows you to log custom visualizations or files as artifacts.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*AsPa2WWvAyhZz2ADgzkD-g.png" /><figcaption>Scatter plot artifact logged and viewable in MLflow UI</figcaption></figure><h3>Step 5: Register the model</h3><pre>import pandas as pd<br>from mlflow.models import infer_signature<br><br>input_example = pd.DataFrame(X_test[:2], columns=[f&quot;feature_{i}&quot; for i in range(X_test.shape[1])])<br>signature = infer_signature(X_test, predictions)<br>mlflow.sklearn.log_model(<br>    sk_model=model,<br>    name=&quot;model_diabetes&quot;,<br>    input_example=input_example,<br>    signature=signature,<br>    registered_model_name=&quot;rf_regressor&quot;<br>)</pre><blockquote>This step registers the model in the MLflow Model Registry, versioning it and storing its input/output schema.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*0gDKOiZA8XiYmdeyELo5tQ.png" /><figcaption>rf_regressor registered in the Model Registry (version 1)</figcaption></figure><h3>4. Reloading and Using the Versioned Model</h3><p>Run the second script to perform inference:</p><pre>poetry run python src/mlflow_quickstart/load_and_predict.py</pre><h3>Step 1: Load the registered model</h3><pre>from mlflow.pyfunc import load_model<br>mlflow.set_tracking_uri(&quot;http://localhost:5000&quot;)<br>model_uri = &quot;models:/rf_regressor/1&quot;<br>loaded_model = load_model(model_uri)</pre><blockquote>Load a specific version of the model from the registry, regardless of the ML framework used.</blockquote><h3>Step 2: Run inference</h3><pre>from sklearn.datasets import load_diabetes<br><br>X, y = load_diabetes(return_X_y=True)<br>predictions = loaded_model.predict(X[:5])<br>print(&quot;Predictions on first 5 samples:&quot;, predictions)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJ8PAJIFVgQeyGV9-28UlQ.png" /><figcaption>Shows model was successfully reloaded and used for inference</figcaption></figure><h3>Project Structure</h3><pre>mlflow_quickstart/<br>├── pyproject.toml<br>├── poetry.lock<br>├── artefacts/                 # Saved plots<br>├── screenshots/               # Tutorial illustrations<br>├── src/<br>│   └── mlflow_quickstart/<br>│       ├── train_and_register.py<br>│       └── load_and_predict.py</pre><h3>Final Thoughts</h3><p>This setup brings production-level rigor to local machine learning workflows:</p><ul><li>Clear project structure with Poetry</li><li>Full experiment tracking and visualization</li><li>Model versioning and reproducibility via MLflow</li></ul><p>If you’re new to MLOps or want a clean starting point for real-world workflows, this template will serve you well.</p><p><strong>Want to go further with MLflow?</strong> Explore the official documentation at <a href="https://mlflow.org/">mlflow.org</a></p><p>📂 Get the full code and screenshots here: <a href="https://github.com/cartelgouabou/Full_stacks_ai_course/tree/main/tools/data_science_toolkit/mlflow_intro/mlflow_quickstart">GitHub Repository</a>. Feel free to fork the repo or adapt it for your own use cases.</p><p>Questions or feedback? Reach out via <a href="https://www.linkedin.com/in/arthur-cartel-foahom-gouabou-phd-41041195/">LinkedIn</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e624d6d4b5" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/track-and-version-your-ml-models-like-a-pro-with-mlflow-and-poetry-b3e624d6d4b5">Track and Version Your ML Models Like a Pro — With MLflow and Poetry</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a Modern Python Project with Poetry and VS Code: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@cartelgouabou/setting-up-a-modern-python-project-with-poetry-and-vs-code-a-step-by-step-guide-057616dba093?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/057616dba093</guid>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 09:43:59 GMT</pubDate>
            <atom:updated>2025-07-25T22:34:07.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>How a Minor Dependency Issue Became a Major Lesson</h3><p>A few weeks ago, I was mentoring a student on how to structure their Python project properly. Everything was working perfectly on their local machine. Then came the moment to deploy it inside a virtual machine.</p><p>That’s where things broke.</p><p>Despite having a requirements.txt file, the project crashed on the VM. Why? Because their requirements.txt only listed package names—no specific versions.</p><p>So when they ran:</p><pre>pip install -r requirements.txt</pre><p>pip fetched the <strong>latest available versions</strong> of each package. Unfortunately, those versions weren’t guaranteed to be compatible with one another—or with the code. What worked yesterday, no longer worked today. ⚠️</p><p>That experience reminded me how fragile and error-prone traditional setups can be, especially when versioning is ignored.</p><p>This is exactly where <strong>Poetry</strong> shines. It offers a cleaner, more robust approach to managing Python projects. And combined with <strong>VS Code</strong>, it makes development smooth and reproducible.</p><p>So I wrote this tutorial — to help others avoid the same headache.</p><h3>What You’ll Learn</h3><p>This guide will walk you through:</p><ul><li>Creating a structured Python project using poetry new</li><li>Managing production and development dependencies the right way</li><li>Setting up a local virtual environment inside your project folder</li><li>Using black, ruff, and pytest for clean, tested code</li><li>Configuring everything inside VS Code</li><li>Sharing your setup so others can reproduce it effortlessly</li></ul><h3>1. Why Choose Poetry Over pip or pipenv?</h3><p>Poetry is a modern dependency and packaging manager for Python. It replaces requirements.txt, pip, and virtualenv with a unified, declarative setup in pyproject.toml.</p><h3>Key Benefits:</h3><ul><li>One config file: All metadata and dependencies live in pyproject.toml</li><li>Automatic virtual environments</li><li>Precise version locking (via poetry.lock)</li><li>Simple CLI to install, add, test, and build</li><li>Easy reproduction of environments</li></ul><p>Whether you’re building libraries, data science projects, or apps, Poetry makes everything more predictable.</p><h3>2. Prerequisites</h3><p>Make sure you have the following:</p><ul><li>Python 3.7+</li><li>VS Code with the Python extension</li><li>(Optional) Git</li></ul><h3>3. Install Poetry</h3><h3>On Linux/macOS</h3><pre>curl -sSL https://install.python-poetry.org | python3 -</pre><h3>On Windows (PowerShell)</h3><pre>(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -</pre><p>Restart your terminal, then confirm the installation:</p><pre>poetry --version</pre><p>⚠️ Note: If the poetry command isn’t recognized immediately after installation, it likely means the executable’s directory hasn’t been added to your system PATH. I’ve included detailed instructions on how to fix this (for both Windows and Linux) in the <a href="https://github.com/cartelgouabou/Full_stacks_ai_course/blob/main/tools/data_science_toolkit/poetry_vscode_setup.md">README version of this tutorial on GitHub</a>. I recommend checking it if poetry --version fails after install.</p><h3>4. Create a New Project</h3><p>Navigate to where you want to create your project:</p><pre>poetry new my_project<br>cd my_project</pre><p>Poetry will generate:</p><pre>my_project/<br>├── src/<br>│   └── my_project/<br>│       └── __init__.py<br>├── tests/<br>│   └── __init__.py<br>├── pyproject.toml<br>└── README.md</pre><blockquote><em>The </em><em>src/ layout helps avoid import errors and keeps your code organized. It’s common in production-grade and data science projects.</em></blockquote><p>To support importing from src/, add it to your PYTHONPATH:</p><h3>Linux/macOS</h3><pre>export PYTHONPATH=&quot;$(pwd)/src&quot;</pre><h3>Windows (PowerShell)</h3><pre>$env:PYTHONPATH=&quot;$(Get-Location)\src&quot;</pre><h3>5. Open the Project in VS Code</h3><pre>code .</pre><h3>6. Configure Poetry to Use Local Virtual Envs</h3><pre>poetry config virtualenvs.in-project true<br>poetry install</pre><p>This creates a .venv/ folder <strong>inside</strong> your project directory.</p><h3>Activate the Environment</h3><h4>Get the path:</h4><pre>poetry env info --path</pre><h4>Then activate it:</h4><p><strong>Linux/macOS:</strong></p><pre>source &lt;path&gt;/bin/activate</pre><p><strong>Windows (PowerShell):</strong></p><pre>.\&lt;path&gt;\Scripts\activate</pre><h3>7. Add Dependencies</h3><h3>For Production</h3><pre>poetry add pandas numpy requests</pre><h3>For Development</h3><pre>poetry add --dev black pytest ruff</pre><blockquote><em>Dev dependencies are only used during development. They’re listed separately in </em><em>pyproject.toml under </em><em>[tool.poetry.group.dev.dependencies].</em></blockquote><h3>Why Separate Them?</h3><ul><li>Keeps production installs clean</li><li>Makes builds faster and safer</li><li>Helps teams standardize their setup</li></ul><h3>8. Configure VS Code</h3><h3>Auto-formatter with Black</h3><p>Create .vscode/settings.json at your project root:</p><pre>code .vscode/settings.json</pre><p>Paste:</p><pre>{<br>  &quot;python.formatting.provider&quot;: &quot;black&quot;,<br>  &quot;editor.formatOnSave&quot;: true<br>}</pre><h3>Linter with Ruff</h3><p>In pyproject.toml, add:</p><pre>[tool.ruff]<br>line-length = 88<br>select = [&quot;E&quot;, &quot;F&quot;, &quot;I&quot;]</pre><p>This config tells Ruff to:</p><ul><li>Use 88-character lines</li><li>Check for style (E), logic errors (F), and import order (I)</li></ul><h3>9. Run Your Tests</h3><pre>poetry run pytest</pre><p>This runs your tests using the virtual environment Poetry created.</p><h3>10. Share and Reproduce the Environment</h3><p>Before sharing your project, make sure your dependencies are up to date and locked:</p><pre>poetry lock</pre><p>This generates or updates the poetry.lock file, which pins the exact versions of every installed package.</p><p>To share your project:</p><ol><li>Make sure pyproject.toml and poetry.lock are committed</li><li>Someone else can clone your repo and run:</li></ol><pre>poetry install</pre><p>To install only production packages:</p><pre>poetry install --no-dev</pre><p>✅ Simple, reproducible, and reliable.</p><h3>Final Thoughts</h3><p>If you’re tired of version conflicts, broken environments, or inconsistent setups between devs — give Poetry a shot.</p><p>It’s simple to get started, yet powerful enough to handle complex projects.</p><p>Whether you’re working solo or in a team, this workflow will save you time and frustration.</p><p>Ready to code with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=057616dba093" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning en Production : Comment Choisir et Utiliser les Bons Formats de Modèles (ONNX…]]></title>
            <link>https://medium.com/@cartelgouabou/deep-learning-en-production-comment-choisir-et-utiliser-les-bons-formats-de-mod%C3%A8les-onnx-2fc9e3eb8059?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fc9e3eb8059</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Thu, 08 May 2025 17:55:54 GMT</pubDate>
            <atom:updated>2025-05-08T17:55:54.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Learning en Production : Comment Choisir et Utiliser les Bons Formats de Modèles (ONNX, SavedModel, TorchScript, etc.)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgBWCo0DvSzF1dD8H1VImA.png" /><figcaption>Image générée.</figcaption></figure><p>Lorsque vous entraînez un modèle d’IA dans un environnement de développement comme PyTorch ou TensorFlow, ce modèle n’est pas encore prêt à affronter les réalités de la production : contraintes de latence, de mémoire, de compatibilité matérielle ou d’infrastructure hétérogène. C’est ici qu’interviennent deux piliers souvent négligés : la précision numérique et le format de déploiement.</p><p>Passer d’un prototype fonctionnel à une solution réellement exploitable en production implique bien plus que d’obtenir un bon score de validation. Cela demande de <strong>reformater intelligemment le modèle</strong> pour garantir performance, portabilité, et efficacité énergétique, tout en tenant compte des spécificités de la plateforme cible.</p><p>Cet article vous guide pas à pas pour comprendre :</p><ul><li><strong>Pourquoi et comment ajuster la précision numérique</strong> (FP32, FP16, INT8),</li><li><strong>Quels formats utiliser pour le déploiement</strong> (ONNX, TorchScript, TensorRT, OpenVINO, TensorFlow SavedModel),</li><li>Et surtout, <strong>comment les implémenter concrètement</strong> avec des tutoriels reproductibles.</li></ul><h3>I- Pourquoi reformater un modèle pour la production ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*4KDS4GEhJec244o-.jpg" /></figure><p>Un modèle entraîné dans PyTorch (ou TensorFlow) est rarement optimisé pour une exécution rapide, stable et portable. Les raisons de reformater sont nombreuses :</p><ul><li><strong>Interopérabilité :</strong> Les frameworks de deep learning (PyTorch, TensorFlow, etc.) ont leurs propres représentations de modèles. Pour déployer un modèle entraîné dans un framework différent de celui utilisé en production, un format standardisé est nécessaire.</li><li><strong>Performances :</strong> Le formatage permet d’optimiser le modèle pour l’inférence, en exploitant des techniques comme la quantification (réduction de la précision numérique) ou la compilation pour des plateformes spécifiques (GPU, CPU, accélérateurs).</li><li><strong>Portabilité :</strong> Un modèle formaté peut être facilement déplacé et exécuté sur différentes infrastructures, qu’il s’agisse de serveurs cloud, d’appareils embarqués ou de navigateurs web.</li></ul><p>C’est là qu’interviennent les formats d’export et les moteurs d’exécution.</p><h3>II- La Précision numérique : FP32, FP16, INT8… que choisir pour vos modèles IA ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAiMIwOmABcmhPKaf4xcRg.png" /></figure><p>La <em>précision numérique</em> désigne la manière dont les nombres (poids, activations) sont représentés en mémoire dans les modèles d’IA. Elle influence directement la <strong>taille du modèle</strong>, la <strong>vitesse d’inférence</strong>, la <strong>consommation énergétique</strong> et la <strong>précision</strong> globale. Voici les trois formats les plus utilisés en déploiement :</p><h4>FP32 — Virgule flottante 32 bits</h4><p>Ce format est la représentation numérique standard utilisée en mémoire lors de l’apprentissage des réseaux de neurones. Il alloue un total de 32 bits pour chaque nombre : 1 bit pour le signe (positif ou négatif), 8 bits pour l’exposant (définissant l’ordre de grandeur en base 2), et 23 bits pour la fraction, qui détermine la précision de la valeur après la “virgule binaire”. Maintenir une précision adéquate durant l’apprentissage est crucial pour prévenir l’accumulation de petites erreurs de calcul qui pourraient nuire à la qualité finale du modèle.</p><p><strong>Idéal pour :</strong></p><ul><li>L’entraînement de modèles complexes</li><li>Les tâches critiques où la perte de précision n’est pas tolérée</li></ul><p><strong>Exemple :</strong> Vous développez un système d’aide au diagnostic pour détecter des tumeurs sur des images d’IRM → précision cruciale → FP32 recommandé.</p><h4>FP16 — Virgule flottante 16 bits</h4><p>Ce format numérique, deux fois plus compact que le FP32 (avec 10 bits dédiés à la précision et 5 bits à la taille), permet de doubler la vitesse d’exécution des calculs (inférence) et de réduire l’utilisation de mémoire. Particulièrement efficace pour l’inférence sur les cartes graphiques (GPU) récentes de NVIDIA grâce à leur architecture “Tensor Cores”, le FP16 offre un gain de performance significatif. Il est important de noter qu’<strong> </strong>une légère perte de précision du modèle peut survenir, mais elle est généralement négligeable pour l’inférence si le modèle est bien calibré.</p><p><strong>Idéal pour :</strong></p><ul><li>Les environnements embarqués</li><li>Le déploiement sur GPU avec support du mixed precision</li></ul><p><strong>Exemple :</strong> Vous exécutez un modèle de classification d’objets sur une caméra embarquée en drone → performance et poids comptent → FP16 idéal.</p><h4>INT8 — Entier 8 bits</h4><p>Contrairement aux formats précédents, l’INT8 représente les informations sous forme de nombres entiers. Ce changement permet de réduire considérablement la taille du modèle stocké en mémoire et d’accélérer l’exécution des calculs (inférence), en particulier sur les processeurs (CPU) et certains types d’accélérateurs spécialisés. Il est crucial de noter que l’utilisation de ce format requiert une étape de “quantification”, qui nécessite une calibration précise des valeurs du modèle pour maintenir de bonnes performances. Sans cette préparation, la perte de précision pourrait être importante.</p><p><strong>Idéal pour :</strong></p><ul><li>Le déploiement sur smartphones et IoT</li><li>Les modèles légers avec fortes contraintes de latence</li></ul><p><strong>Exemple :</strong> Vous déployez un système de détection de visage sur un téléphone → vitesse et taille prioritaires → INT8 avec calibration.</p><p><strong>Conseil</strong>: Commencez par FP32 pour l’entraînement. Passez à FP16 ou INT8 pour le déploiement, selon vos contraintes de latence, de mémoire et de précision. Pour INT8, utilisez des données représentatives pour calibrer efficacement votre modèle.</p><h3>III- Formats de Modèles pour la Production</h3><p>Lors du déploiement d’un modèle d’IA, le format dans lequel il est exporté joue un rôle crucial en matière de compatibilité, de performance et d’optimisation matérielle. Voici les principaux formats à connaître pour la mise en production.</p><h4>2.1 ONNX (Open Neural Network Exchange)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tz0XfFulolTvKpR9.png" /></figure><p><strong>Qu’est-ce que c’est ?</strong></p><p>ONNX est un format ouvert et standardisé conçu pour représenter les modèles de réseaux neuronaux. Son objectif principal est de faciliter l’interopérabilité entre différents frameworks de deep learning (comme PyTorch, TensorFlow, etc.). Un modèle entraîné dans un framework peut être exporté au format ONNX, puis importé et exécuté par un autre framework ou un moteur d’inférence compatible ONNX. Cela simplifie considérablement le déploiement sur des infrastructures hétérogènes.</p><p><strong>Cas d’usage typique :</strong></p><ul><li><strong>Déploiement multi-framework :</strong> Lorsque votre environnement de production utilise un framework différent de celui utilisé pour l’entraînement.</li><li><strong>Inférence sur des plateformes hétérogènes :</strong> Déployer un même modèle sur différents types de matériel (CPU, GPU, accélérateurs) en utilisant des runtimes ONNX optimisés pour chaque plateforme.</li><li><strong>Utilisation d’outils d’optimisation :</strong> Bénéficier d’outils et de runtimes (comme ONNX Runtime, TensorRT, OpenVINO) qui peuvent optimiser les modèles ONNX pour améliorer les performances.</li></ul><p><strong>Tutoriel (PyTorch vers ONNX) :</strong></p><p>✅ Prérequis</p><p>Avant de commencer, assurez-vous d’avoir installé les bibliothèques suivantes dans votre environnement Python :</p><pre>pip install torch torchvision onnx onnxruntime</pre><p>Ces paquets permettent de charger un modèle pré-entraîné PyTorch, de l’exporter au format ONNX, et d’exécuter une inférence avec ONNX Runtime.</p><blockquote><em>⚠️ </em><strong><em>Remarque importante</em></strong><em> : au moment où je rédige cet article, </em><strong><em>Python 3.13 n’est pas encore supporté</em></strong><em> par certains packages comme </em><em>onnx.<br> Il est donc </em><strong><em>recommandé d’utiliser Python 3.11</em></strong><em> pour éviter toute erreur lors de l’installation ou de l’export.</em></blockquote><pre>import torch<br>import torch.nn as nn<br>import torchvision.models as models<br>from torchvision import transforms<br>from PIL import Image<br>import numpy as np<br>import onnxruntime<br>import requests<br>from io import BytesIO<br><br># 1. Définir un modèle PyTorch avec sorties multiples : prédictions + features<br>class ResNet50WithFeatures(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        base = models.resnet50(pretrained=True)<br>        self.features = nn.Sequential(*list(base.children())[:-1])<br>        self.fc = base.fc<br><br>    def forward(self, x):<br>        feat = self.features(x)<br>        feat_flat = feat.view(feat.size(0), -1)<br>        out = self.fc(feat_flat)<br>        return out, feat_flat<br><br># 2. Instancier le modèle et passer en mode évaluation<br>model = ResNet50WithFeatures().eval()<br><br># 3. Créer une entrée factice pour tracer le graphe<br>dummy_input = torch.randn(1, 3, 224, 224)<br><br># 4. Exporter le modèle vers ONNX<br>onnx_path = &quot;resnet50_with_features.onnx&quot;<br>torch.onnx.export(model,<br>                  dummy_input,<br>                  onnx_path,<br>                  input_names=[&quot;input&quot;],<br>                  output_names=[&quot;predictions&quot;, &quot;features&quot;],<br>                  export_params=True,<br>                  opset_version=11,<br>                  do_constant_folding=True)<br><br>print(f&quot;Modèle exporté au format ONNX : {onnx_path}&quot;)<br><br># 5. Charger le modèle ONNX avec ONNX Runtime<br>ort_session = onnxruntime.InferenceSession(onnx_path)<br><br># 6. Télécharger une image réelle depuis Internet<br>img_url = &quot;https://upload.wikimedia.org/wikipedia/commons/2/26/YellowLabradorLooking_new.jpg&quot;<br>response = requests.get(img_url)<br>img = Image.open(BytesIO(response.content)).convert(&quot;RGB&quot;)<br><br># 7. Prétraitement compatible avec ResNet50 (ImageNet)<br>preprocess = transforms.Compose([<br>    transforms.Resize(256),<br>    transforms.CenterCrop(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406],<br>                         std=[0.229, 0.224, 0.225])<br>])<br>input_tensor = preprocess(img).unsqueeze(0)<br>input_numpy = input_tensor.numpy()<br><br># 8. Préparer les entrées<br>ort_inputs = {ort_session.get_inputs()[0].name: input_numpy}<br><br># 9. Effectuer l&#39;inférence<br>ort_outputs = ort_session.run(None, ort_inputs)<br>predictions = ort_outputs[0]  # [1, 1000]<br>features = ort_outputs[1]     # [1, 2048]<br><br>print(&quot; Prédictions (shape) :&quot;, predictions.shape)<br>print(&quot; Features intermédiaires (shape) :&quot;, features.shape)<br><br># 10. Identifier la classe prédite<br>softmax = torch.nn.Softmax(dim=1)<br>probs = softmax(torch.from_numpy(predictions)).numpy()<br><br># Télécharger les labels ImageNet<br>labels_url = &quot;https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt&quot;<br>labels_response = requests.get(labels_url)<br>imagenet_labels = labels_response.text.strip().split(&quot;\n&quot;)<br><br>top5_idx = probs[0].argsort()[-3:][::-1]  # top-3 classes<br>print(&quot; Top 3 prédictions :&quot;)<br>for i in top5_idx:<br>    print(f&quot; - {imagenet_labels[i]} ({probs[0][i]*100:.2f}%)&quot;)<br><br>top1 = top5_idx[0]<br>print(f&quot;\n Classe prédite (top-1) : {imagenet_labels[top1]} ({probs[0][top1]*100:.2f}%)&quot;)<br><br># À propos des sorties multiples :<br># Le modèle exporté produit deux sorties :<br># - &#39;predictions&#39; : scores de classification (ImageNet) → pour prédire une classe<br># - &#39;features&#39; : représentation de l’image extraite par le réseau → utile pour :<br>#     • Apprentissage par transfert<br>#     • Clustering ou recherche d&#39;images similaires<br>#     • Visualisations (TSNE, UMAP)<br>#     • Matching d’images médicales ou industrielles</pre><h4>2.2 TorchScript (PyTorch)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*s1gwVeXBpWXSCgYB.png" /></figure><p><strong>Qu’est-ce que c’est ?</strong></p><p>TorchScript est une manière de sérialiser un modèle PyTorch en une représentation intermédiaire qui peut être exécutée indépendamment de l’interpréteur Python. Cela permet d’optimiser et de déployer des modèles PyTorch dans des environnements où Python n’est pas souhaitable ou disponible, comme en C++ avec LibTorch. TorchScript capture la structure du modèle et les opérations à effectuer, permettant des optimisations et une exécution plus efficace.</p><p><strong>Cas d’usage typique :</strong></p><ul><li><strong>Déploiement en production de modèles PyTorch :</strong> Exécuter des modèles PyTorch dans des environnements de production sans dépendance à Python.</li><li><strong>Inférence haute performance en C++ :</strong> Utiliser la librairie LibTorch pour intégrer des modèles PyTorch directement dans des applications C++ pour une latence minimale.</li><li><strong>Optimisations et compilation :</strong> Permettre à PyTorch d’appliquer des optimisations spécifiques au graphe du modèle avant le déploiement.</li></ul><p><strong>Tutoriel (Exporter et inférer avec TorchScript) :</strong></p><pre>import torch<br>import torchvision.models as models<br><br># 1. Charger un modèle PyTorch pré-entraîné<br>model = models.resnet50(pretrained=True)<br>model.eval()<br><br># 2. Créer une entrée factice<br>dummy_input = torch.randn(1, 3, 224, 224)<br><br># 3. Tracer le modèle (méthode recommandée pour la plupart des modèles)<br># Le tracing exécute le modèle avec une entrée exemple et enregistre les opérations.<br>traced_script_module = torch.jit.trace(model, dummy_input)<br><br># Alternative : Scripter le modèle (pour les modèles avec flux de contrôle complexe)<br># Le scripting analyse le code Python du modèle et le convertit en TorchScript.<br># scripted_module = torch.jit.script(model)<br><br># 4. Sauvegarder le modèle TorchScript<br>torchscript_path = &quot;resnet50.pt&quot;<br>torch.jit.save(traced_script_module, torchscript_path)<br><br>print(f&quot;Modèle PyTorch exporté vers TorchScript : {torchscript_path}&quot;)<br><br># 5. Charger et effectuer une inférence simple avec TorchScript<br>loaded_model = torch.jit.load(torchscript_path)<br>loaded_model.eval()  # Toujours mettre en mode évaluation pour l&#39;inférence<br><br>with torch.no_grad():<br>    output = loaded_model(dummy_input)<br><br>print(&quot;Sortie TorchScript (shape) :&quot;, output.shape)</pre><h4>2.3 TensorRT : Pour les GPU NVIDIA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*pHM24AwIA9UU4hYa.png" /></figure><p><strong>Qu’est-ce que c’est ?</strong></p><p>TensorRT est une plateforme logicielle développée par NVIDIA pour l’inférence haute performance sur leurs GPU. Il prend en entrée un modèle entraîné (souvent au format ONNX ou TensorFlow) et l’optimise pour un GPU NVIDIA spécifique. Les optimisations incluent la quantification (passage à une précision numérique inférieure), la fusion de couches, la sélection des noyaux les plus rapides et la parallélisation. TensorRT vise à maximiser le débit et à minimiser la latence pour les applications d’inférence.</p><p><strong>Cas d’usage typique :</strong></p><ul><li><strong>Inférence en temps réel sur serveurs GPU NVIDIA :</strong> Applications nécessitant une faible latence et un haut débit, comme la vision par ordinateur, le traitement du langage naturel ou les systèmes de recommandation.</li><li><strong>Déploiement sur des systèmes embarqués NVIDIA :</strong> Utiliser la puissance des GPU embarqués pour des tâches d’inférence locales et rapides.</li></ul><p><strong>Implémentation :</strong></p><p>L’utilisation optimale de TensorRT nécessite une installation spécifique des pilotes NVIDIA et de la librairie TensorRT, qui peut être complexe à mettre en place dans un environnement Python standard. Bien qu’il soit possible d’interagir avec TensorRT via des runtimes ONNX compatibles, une implémentation directe pour des optimisations maximales demande une configuration plus avancée. Pour un guide détaillé sur l’implémentation de TensorRT, veuillez consulter la documentation officielle de NVIDIA : <a href="https://developer.nvidia.com/tensorrt">Lien vers la documentation NVIDIA TensorRT</a>.</p><h4>2.4 OpenVINO : Pour l’optimisation sur CPU Intel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*juPDJeq8wOk8T85o" /></figure><p><strong>Qu’est-ce que c’est ?</strong></p><p>OpenVINO (Open Visual Inference and Neural network Optimization toolkit) est un toolkit développé par Intel pour optimiser et déployer des modèles d’inférence sur le matériel Intel, incluant les CPU, les GPU intégrés et les VPU (Vision Processing Units). Il supporte une variété de frameworks (TensorFlow, PyTorch, ONNX, etc.) et fournit des outils pour la conversion de modèles, l’optimisation (comme la quantification et la fusion de couches) et l’exécution sur les plateformes Intel.</p><p><strong>Cas d’usage typique :</strong></p><ul><li><strong>Déploiement sur des infrastructures basées sur des processeurs Intel :</strong> Optimiser l’inférence sur les CPU Intel pour des applications où les GPU dédiés ne sont pas disponibles ou nécessaires.</li><li><strong>Utilisation des capacités des VPU Intel :</strong> Exploiter les unités de traitement vision dédiées pour des tâches d’inférence à faible consommation d’énergie.</li><li><strong>Déploiement de modèles sur des appareils embarqués Intel :</strong> Optimiser les modèles pour des performances efficaces sur des plateformes avec des ressources limitées.</li></ul><p><strong>Implémentation :</strong></p><p>L’exploitation pleine des capacités d’OpenVINO requiert l’installation du toolkit OpenVINO d’Intel, qui peut avoir des dépendances spécifiques à la plateforme. Pour un guide d’implémentation détaillé d’OpenVINO, veuillez vous référer à la documentation officielle d’Intel : <a href="https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/overview.html">Lien vers la documentation Intel OpenVINO</a>.</p><h4>2.5 TensorFlow SavedModel : Pour TF Serving</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSCr1lN0EBW_AX-E.png" /></figure><p><strong>Qu’est-ce que c’est ?</strong></p><p>TensorFlow SavedModel est le format standard pour sauvegarder et charger des modèles TensorFlow. Il contient non seulement le graphe du modèle et les poids entraînés, mais aussi les métadonnées nécessaires pour la restauration et l’exécution du modèle. Cela inclut les signatures des fonctions (pour l’inférence, l’entraînement, etc.) et les informations sur les entrées et sorties. SavedModel est conçu pour être portable et indépendant du code qui a créé le modèle, facilitant ainsi le déploiement en production, notamment avec TensorFlow Serving.</p><p><strong>Cas d’usage typique :</strong></p><ul><li><strong>Déploiement avec TensorFlow Serving :</strong> Servir des modèles TensorFlow en production via une API dédiée, gérant le versionnage, le monitoring et le scaling.</li><li><strong>Déploiement sur TensorFlow Lite :</strong> Convertir des SavedModel pour une exécution efficace sur des appareils mobiles et embarqués.</li><li><strong>Déploiement dans le navigateur avec TensorFlow.js :</strong> Convertir des SavedModel pour une exécution dans un environnement JavaScript.</li></ul><p><strong>Tutoriel (Exporter un modèle PyTorch vers TensorFlow SavedModel via ONNX) :</strong></p><p>✅ Prérequis</p><p>Avant de commencer, assurez-vous d’avoir installé les bibliothèques suivantes dans votre environnement Python :</p><pre>pip install tensorflow</pre><pre>import tensorflow as tf<br>import numpy as np<br><br># 1. Charger le modèle ResNet50 pré-entraîné<br>model = tf.keras.applications.ResNet50(weights=&quot;imagenet&quot;, input_shape=(224, 224, 3), include_top=True)<br><br># 2. Exporter au format TensorFlow SavedModel (compatible TF Serving, TFLite, etc.)<br>saved_model_path = &quot;resnet50_savedmodel&quot;<br>model.export(saved_model_path)<br><br>print(f&quot;Modèle ResNet50 exporté au format TensorFlow SavedModel : {saved_model_path}&quot;)<br><br># 3. Charger le modèle exporté<br>loaded_model = tf.saved_model.load(saved_model_path)<br>infer = loaded_model.signatures[&quot;serving_default&quot;]<br><br># 4. Créer une image factice<br>dummy_input = np.random.rand(1, 224, 224, 3).astype(np.float32)<br><br># 5. Lancer une inférence<br>output = infer(tf.constant(dummy_input))<br><br># Afficher les clés pour comprendre la structure<br>print(&quot;Clés de sortie :&quot;, list(output.keys()))<br><br># Accès dynamique à la première sortie<br>first_key = list(output.keys())[0]<br>print(&quot;Sortie (shape) :&quot;, output[first_key].shape)</pre><h3>Conclusion</h3><p>Le formatage de modèles de deep learning est une étape essentielle pour passer de la recherche à la production. En comprenant les différents formats disponibles et leurs compromis en termes d’interopérabilité, de performances et de portabilité, vous pouvez préparer vos modèles de manière efficace pour un déploiement réussi. N’oubliez pas de tester et de valider rigoureusement vos modèles formatés sur votre infrastructure cible pour garantir des performances optimales en production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc9e3eb8059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Poisoning : l’arme silencieuse contre l’intelligence artificielle]]></title>
            <link>https://medium.com/@cartelgouabou/data-poisoning-larme-silencieuse-contre-l-intelligence-artificielle-3d34bbce0235?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d34bbce0235</guid>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[sécurité]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-poisoning]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 14:51:14 GMT</pubDate>
            <atom:updated>2025-04-29T05:01:28.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Poisoning : l’arme silencieuse contre l’intelligence artificielle</h3><h3>Introduction</h3><p>Lors de ma thèse en intelligence artificielle appliquée à l’analyse d’images médicales, j’ai étudié un phénomène frappant : un artefact visuel — un simple halo noir autour d’une image dermoscopique — suffisait à faire chuter drastiquement la performance d’un algorithme de détection automatique du mélanome. La sensibilité de notre système passait de 73 % à 27 % selon la taille de ce halo, une erreur provoquée non pas par la lésion elle-même, mais par un élément périphérique sans lien médical.</p><p>Dans ce cas précis, l’artefact agit comme une <a href="https://medium.com/meetech/hackers-vs-neural-networks-game-on-part-1-8af6be210e9d">attaque adversarielle</a> : le modèle, déjà entraîné, est trompé par une perturbation visuelle externe.<br> Mais cette observation soulève également un risque majeur plus en amont : si de tels artefacts sont présents dans les jeux de données d’entraînement sans être identifiés ni corrigés, ils peuvent provoquer un phénomène de <em>data poisoning</em>, en faussant l’apprentissage du modèle de manière systémique.</p><p>C’est exactement l’enjeu du <strong>data poisoning</strong> : une menace insidieuse qui consiste à empoisonner, volontairement ou non, les ensembles de données utilisés pour entraîner les intelligences artificielles.<br> Et dans un contexte où les modèles d’IA sont nourris de milliards de documents collectés — ou générés — en ligne, ce risque devient massif.</p><h3>1. Qu’est-ce que le data poisoning ?</h3><p>Le <em>data poisoning</em>, ou empoisonnement de données, est une attaque qui consiste à injecter des données malveillantes, erronées ou biaisées dans un jeu d’entraînement dune intelligence artificielle. Cette manipulation peut déformer les comportements du modèle de manière imprévisible ou intentionnellement dirigée.</p><p>On distingue deux types d’attaques :</p><ul><li><strong>Ciblées</strong> : elles visent à produire un effet spécifique, par exemple amener un modèle à ne plus détecter une catégorie de virus informatique.</li><li><strong>Non ciblées</strong> : elles visent à dégrader globalement la performance du modèle, en introduisant du bruit ou de l’incohérence dans les données.</li></ul><p>Ce type de menace concerne autant les modèles de langage (LLM), les systèmes de diagnostic médical, que les véhicules autonomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UI48HM1s03wR4PHPkdjhBg.png" /><figcaption>Effet d’un halo visuel sur la détection du mélanome par un algorithme. En haut, l’image originale est correctement classée ; la carte de chaleur montre que le modèle se concentre sur la lésion. En bas, l’ajout d’un halo détourne l’attention du modèle, qui se focalise sur le contour… et se trompe. Source: <a href="https://theses.fr/api/v1/document/2023AIXM9056">Apprentissage neuronal profond pour la détection du mélanome, Arthur Cartel Foahom Gouabou</a></figcaption></figure><h3>2. Trois techniques classiques de data poisoning</h3><h4>a. Inversion des labels</h4><p>Cette méthode consiste à assigner de fausses étiquettes à des exemples d’entraînement. Par exemple, des tweets haineux étiquetés comme “positifs” dans un modèle de sentiment, rendant le modèle toxique.</p><p><strong>Exemple concret</strong> : <a href="https://nightshade.cs.uchicago.edu/whatis.html"><em>Nightshade</em></a>, un outil développé à l’Université de Chicago, permet aux artistes de modifier subtilement les pixels de leurs images. Résultat : lorsqu’une IA les utilise pour s’entraîner, elle peut confondre des objets comme une vache avec un sac à main.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOHPmY9c4b3tsRseEOOIpA.png" /><figcaption>Exemple visuel de data poisoning par inversion de labels. À gauche, l’image originale d’un chat est utilisée pour entraîner un modèle de reconnaissance. À droite, l’image a été altérée de manière quasi imperceptible (bruit, teinte, flou), mais reste étiquetée comme “chat”. En réalité, elle est conçue pour induire une mauvaise classification par l’IA. Ce type de manipulation est utilisé pour tromper les modèles tout en échappant à la détection humaine. Image générée.</figcaption></figure><h4>b. Portes dérobées (Backdoors)</h4><p>Ici, le modèle fonctionne normalement, sauf lorsqu’il rencontre un “déclencheur” (mot, image, son) inséré par l’attaquant. Il adopte alors un comportement anormal, mais prévisible pour l’attaquant.</p><p><strong>Exemple</strong> : Un modèle de reconnaissance faciale peut être entraîné à identifier normalement les visages… sauf lorsqu’une personne porte un motif particulier sur ses lunettes, qui déclenche alors une fausse reconnaissance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9jsvM9rpfDDHClVn6q5jg.png" /><figcaption>Exemple de backdoor dans un système de reconnaissance faciale. Ici, un motif discret intégré aux lunettes agit comme un déclencheur (ou <em>trigger</em>) invisible pour l’IA. Lorsqu’il est détecté, le système autorise automatiquement l’accès, indépendamment de l’identité réelle de la personne. Ce type de manipulation permet à un attaquant de contourner les contrôles en insérant une “clé cachée” dans les données visuelles. Image générée.</figcaption></figure><h4>c. Injection de bruit</h4><p>Cela consiste à injecter massivement des données inutiles ou trompeuses pour réduire la performance globale du modèle.</p><p><strong>Exemple</strong> : Sur une plateforme de streaming musical, si des milliers de faux comptes écoutent en boucle un même morceau sans contexte pertinent, l’algorithme peut finir par recommander ce titre à des utilisateurs réels, pensant qu’il est populaire. Le modèle perd alors en pertinence, car il a appris à partir d’un signal artificiel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0MfKuyFXIojcez7gjI1fA.png" /><figcaption>L’injection de bruit peut fausser les recommandations d’un système. Ici, des écoutes artificielles faussent les résultats d’un moteur de streaming musical, le rendant moins pertinent pour les vrais utilisateurs. Image générée.</figcaption></figure><h3>3. Pourquoi c’est dangereux ?</h3><p>Les effets du <em>data poisoning</em> sont souvent <strong>invisibles</strong> jusqu’à ce qu’un dysfonctionnement majeur survienne. Et comme les modèles IA sont assimilés à des “boîtes noires”, il est difficile d’en diagnostiquer l’origine.</p><h4>Trois conséquences majeures :</h4><ul><li><strong>Perte de fiabilité</strong> : recommandations erronées, erreurs médicales, dérives éthiques.</li><li><strong>Amplification des biais</strong> : les modèles apprennent des représentations inéquitables.</li><li><strong>Failles de sécurité</strong> : certains modèles peuvent contenir des portes dérobées (backdoors) activables à distance.</li></ul><p><strong>Cas emblématique : </strong><a href="https://www.lemonde.fr/pixels/article/2016/03/24/a-peine-lancee-une-intelligence-artificielle-de-microsoft-derape-sur-twitter_4889661_4408996.html"><strong>Microsoft Tay (2016)</strong></a><br> Ce chatbot est devenu raciste et agressif en moins de 24h, simplement parce qu’il avait été entraîné avec des messages toxiques envoyés en masse par des utilisateurs.</p><h3>4. Comment se protéger ?</h3><h4>1. Vérifier la provenance des données</h4><p>Utiliser des outils comme <a href="https://cyclonedx.org/capabilities/mlbom/"><strong>ML-BOM</strong></a> pour suivre l’origine, les transformations et la qualité des données.</p><h4>2. Valider et nettoyer les jeux de données</h4><p>Supprimer doublons, erreurs et données anormales. Attention aux attaques <a href="https://people.csail.mit.edu/madry/lab/cleanlabel.pdf"><em>clean-label</em></a>, indétectables sans analyse poussée.</p><h4>3. Renforcer la robustesse des modèles</h4><ul><li><strong>Adversarial training</strong> : entraînement avec exemples empoisonnés pour renforcer la résistance du modèle.</li><li><strong>Détection d’anomalies</strong> : surveillance du comportement du modèle post-déploiement.</li><li><strong>Contrôle d’accès</strong> : appliquer le <a href="https://www.checkpoint.com/fr/cyber-hub/network-security/what-is-the-principle-of-least-privilege-polp/"><strong>principe du moindre privilège (POLP)</strong></a>, en limitant qui peut accéder ou modifier les jeux de données.</li><li><strong>MLSecOps</strong> : intégrer la sécurité tout au long du cycle de développement IA.</li></ul><h3>Conclusion</h3><p>Le <em>data poisoning</em> ne relève pas de la science-fiction : c’est une menace bien réelle, souvent invisible, qui fragilise les fondements mêmes de l’intelligence artificielle. Comme l’a montré l’exemple du halo en dermatologie, il suffit parfois d’un détail a priori anodin pour faire dérailler un modèle performant.</p><p>À l’heure où les IA apprennent à partir de flux massifs de données — souvent non vérifiées — , cette vulnérabilité devient systémique. Il ne s’agit plus seulement de mieux entraîner les modèles, mais de repenser toute la chaîne de confiance, de la collecte des données à leur validation.</p><p>Construire une IA robuste, éthique et utile passe donc par une prise de conscience : <strong>les données ne sont pas un simple carburant, mais la colonne vertébrale de l’IA</strong>. Et comme toute infrastructure critique, elles doivent être surveillées, protégées et auditées avec rigueur.</p><h3><strong>Références :</strong></h3><ul><li><a href="https://www.ibm.com/think/topics/data-poisoning"><em>What is Data Poisoning, IBM Think, avril 2024</em></a></li><li><a href="https://genai.owasp.org/llmrisk/llm042025-data-and-model-poisoning/"><em>LLM04:2025 — Data and Model Poisoning, OWASP GenAI</em></a></li><li><a href="https://doi.org/10.1016/j.annder.2020.09.022"><em>Impact d’un artefact fréquent sur la détection automatique du mélanome à partir d’images dermoscopiques, Jilliana Monnier, Arthur Cartel Foahom Gouabou, et al., Annales de Dermatologie et de Vénéréologie, 2020.</em></a></li><li><a href="https://theses.fr/api/v1/document/2023AIXM9056"><em>Apprentissage neuronal profond pour la détection du mélanome, Arthur Cartel Foahom Gouabou</em></a></li><li><a href="https://people.csail.mit.edu/madry/lab/cleanlabel.pdf"><em>Clean-Label Backdoor Attacks, Alexander Turner et al.</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d34bbce0235" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sécurisez vos échanges de données en 10 minutes : installez un serveur SFTP sur Ubuntu, local ou…]]></title>
            <link>https://medium.com/@cartelgouabou/s%C3%A9curisez-vos-%C3%A9changes-de-donn%C3%A9es-en-10-minutes-installez-un-serveur-sftp-sur-ubuntu-local-ou-657b7c0a662e?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/657b7c0a662e</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[sftp]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-security]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 12:31:06 GMT</pubDate>
            <atom:updated>2025-04-07T07:42:40.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sécurisez vos échanges de données en 10 minutes : installez un serveur SFTP sur Ubuntu, local ou cloud</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*AaCOxn8aIcHIEf4Y" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.progress.com%2Ffr%2Fressources%2Flivres-blancs%2Fserveur-sftp&amp;psig=AOvVaw0-7e9jcyXMSWB1uWgsBdDI&amp;ust=1743844851062000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBgQjhxqFwoTCIjt1bmGvowDFQAAAAAdAAAAABAE">Source</a></figcaption></figure><p>Vous devez souvent échanger des fichiers sensibles avec des clients, automatiser des flux de données ou recevoir des exports de bases sans passer par des emails non sécurisés ?<br> Le <strong>protocole SFTP</strong> (SSH File Transfer Protocol) est la solution idéale : fiable, chiffré, et compatible avec vos outils d’automatisation.</p><p>Dans ce tutoriel, vous apprendrez pas à pas comment mettre en place votre propre serveur SFTP, d’abord en local sur Ubuntu (via WSL), puis sur un serveur cloud, pour transférer vos fichiers en toute sécurité, sans passer par un serveur FTP ni par email, <strong>et avec une mise en œuvre simple et claire.</strong></p><p>Que vous soyez en stage ou dans une équipe data, ce guide est conçu pour vous permettre de répliquer cette configuration <strong>facilement et rapidement</strong> dans un contexte professionnel.</p><h3>Pourquoi utiliser SFTP ?</h3><p>Le <strong>SFTP (SSH File Transfer Protocol)</strong> est la méthode recommandée pour transférer des fichiers sensibles. Contrairement au FTP classique ou à l’envoi d’email, SFTP chiffre <strong>tout</strong> : l’identifiant, le mot de passe, et le contenu.</p><p>Il est très utilisé pour :</p><ul><li>Recevoir des fichiers clients (factures, logs, exports de base de données…)</li><li>Intégrer des pipelines automatisés (ETL)</li><li>Assurer la conformité RGPD dans les échanges de données</li></ul><h3>Étape 1 : Préparer votre environnement</h3><p>Avant de pouvoir héberger un serveur SFTP, vous devez avoir accès à une machine Linux (locale ou distante). Cette étape vous montre deux façons simples de le faire : via Ubuntu en local (grâce à WSL sous Windows) ou via un serveur cloud (comme OVH, AWS, etc.).</p><p>✅<strong> Option 1 — Installer Ubuntu sur Windows (via WSL)</strong></p><ol><li>Ouvrez PowerShell en administrateur et exécutez:</li></ol><pre>wsl --install</pre><p>2. Ouvrez <strong>Microsoft Store </strong>et installer<strong> Ubuntu</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eqAsgZE8itKlqGljvQ31Q.png" /></figure><p>3. Lancer Ubuntu depuis le menu Démarrer.</p><p>4. Créez un nom d’utilisateur UNIX et un mot de passe lorsque demandé.</p><p>✅ <strong>Option 2 — Utiliser une VM Ubuntu ou un serveur cloud (OVH, AWS, etc.)</strong></p><p>Dans ce cas, connectez vous simplement en SSH à votre machine distante :</p><pre>ssh user@ip_du_serveur</pre><p>➡️ Remplacez user par votre identifiant et ip_du_serveur par l’adresse IP de votre serveur cloud.</p><h3>Étape 2 : Installer le serveur SFTP</h3><p>Dans cette étape, vous allez installer le service SSH, qui est nécessaire pour faire fonctionner le protocole SFTP, puis vérifier que le service est bien actif sur votre machine.</p><pre>sudo apt update &amp;&amp; sudo apt install openssh-server</pre><p>➡️ Met à jour les paquets et installe le serveur SSH qui supporte SFTP.</p><pre>sudo service ssh start</pre><p>➡️ Démarre le service SSH.</p><pre>sudo service ssh status</pre><p>➡️ Vérifie que le service est bien <strong>actif</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DGNnFA8G4_9wKx7aT-6hg.png" /><figcaption>Le service SSH est actif : la ligne Active: active (running) confirme que le serveur est bien lancé.</figcaption></figure><h3>Étape 3 : Créer un utilisateur sécurisé</h3><p>Vous allez maintenant créer un utilisateur dédié aux transferts SFTP. Cela permet de limiter les droits d’accès et de sécuriser les échanges de fichiers.</p><pre>sudo adduser sftpuser</pre><p>➡️ Crée un nouvel utilisateur dédié aux échanges via SFTP.</p><ul><li>Saisissez un <strong>mot de passe fort</strong></li><li>Appuyez sur <strong>Entrée</strong> pour laisser les autres champs vides (nom, etc.) <em>[Capture suggérée : terminal affichant les champs ignorés]</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*NrUJNcdax_uac6v88TuGTA.png" /><figcaption>Création de l’utilisateur sftpuser : seuls le nom d’utilisateur et le mot de passe sont requis. Laissez les autres champs vides en appuyant simplement sur Entrée</figcaption></figure><h3>Étape 4 : Isoler un dossier pour les transferts</h3><p>Pour éviter tout accès non autorisé, on crée un dossier spécifique où les fichiers seront déposés. On limite aussi les permissions pour empêcher l’utilisateur SFTP de sortir de ce répertoire.</p><pre>sudo mkdir -p /home/sftpuser/uploads</pre><p>➡️ Crée le répertoire dans lequel les fichiers seront déposés.</p><pre>sudo chown root:root /home/sftpuser<br>sudo chmod 755 /home/sftpuser</pre><p>➡️ Interdit à sftpuser d’accéder à son dossier parent pour plus de sécurité.</p><pre>sudo chown sftpuser:sftpuser /home/sftpuser/uploads</pre><p>➡️ Donne à sftpuser les droits sur le dossier de dépôt uniquement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYn0w-rlW-G7yMmF0P2aDw.png" /></figure><h3>Étape 5 : Configurer SSH pour restreindre à SFTP uniquement</h3><p>Par défaut, un utilisateur SSH peut ouvrir une session terminal (shell), exécuter des commandes sur le système ou même établir des tunnels réseau vers d’autres machines.<br> 👉 <strong>Dans notre cas, ce n’est pas ce qu’on veut.</strong></p><p>Notre objectif est simple :<br> ➡️ <strong>Permettre uniquement le transfert de fichiers via SFTP</strong><br> ➡️ <strong>Empêcher tout accès à la machine en dehors du dossier de dépôt</strong></p><p>C’est une mesure de sécurité essentielle.<br> Imagine que l’utilisateur sftpuser soit compromis (mot de passe faible, partagé, etc.).<br> S’il peut accéder à un terminal SSH, il pourrait :</p><ul><li>lister les fichiers du système</li><li>explorer d’autres répertoires</li><li>tenter d’exécuter des commandes malveillantes</li><li>établir des tunnels vers d’autres machines internes (pivot SSH)</li></ul><p>Pour éviter ça, on modifie le fichier de configuration sshd_config avec un éditeur de texte de votre choix :</p><pre>sudo nano /etc/ssh/sshd_config<br># ou, si vous préférez vim :<br>sudo vim /etc/ssh/sshd_config</pre><p>Ajoutez à la fin du fichier :</p><pre>Match User sftpuser<br>  ChrootDirectory /home/sftpuser<br>  ForceCommand internal-sftp<br>  PasswordAuthentication yes<br>  X11Forwarding no<br>  AllowTcpForwarding no</pre><p>➡️ Ceci :</p><ul><li><strong>ChrootDirectory /home/sftpuser</strong>: L’utilisateur est confiné dans ce répertoire : il ne peut pas naviguer ailleurs</li><li><strong>ForceCommand internal-sftp: </strong>Force l’utilisateur à passer uniquement par SFTP, sans terminal</li><li><strong>X11Forwarding: </strong>Bloque l’ouverture d’interfaces graphiques distantes via SSH</li><li><strong>AllowTcpForwarding: </strong>Empêche l’utilisateur d’ouvrir des tunnels vers d’autres machines internes (ex : vers une base de données)</li></ul><p>Puis redémarrez le service SSH :</p><pre>sudo service ssh restart</pre><h3>Étape 6 : Connexion depuis FileZilla</h3><p>Une fois le serveur prêt, il ne reste plus qu’à s’y connecter. Cette étape vous guide pour configurer FileZilla, un client SFTP graphique très pratique, afin de commencer à envoyer ou recevoir vos fichiers.</p><ol><li>Téléchargez FileZilla (<a href="https://filezilla-project.org/">https://filezilla-project.org/</a>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYTiWEKoW3L-IzFxMQBCVw.png" /></figure><p>2. Une fois l’installation terminer lancez Filezilla et ouvrez <strong>Fichier &gt; Gestionnaire de sites</strong></p><p>3. Cliquez sur <strong>Nouveau site</strong> puis renseignez :</p><ul><li><strong>Protocole</strong> : SFTP — SSH File Transfer Protocol</li><li><strong>Hôte</strong> : 127.0.0.1 (ou l’IP publique si serveur cloud)</li><li><strong>Port</strong> : 22</li><li><strong>Nom d’utilisateur</strong> : sftpuser</li><li><strong>Mot de passe</strong> : celui défini précédemment</li></ul><p>4. Cliquez sur <strong>Connexion</strong> 📸</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWd7HHHqXLe6bOZf-xY5XQ.png" /><figcaption>Ajout d’un nouveau site SFTP dans le gestionnaire FileZilla : utilisez l’adresse IP du serveur, port 22 et les identifiants définis précédemment.</figcaption></figure><p>Vous pouvez maintenant glisser-déposer des fichiers dans /uploads 📁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_gB-fNK9ai0xr80YSFcAw.png" /><figcaption>Interface FileZilla : à gauche, vos fichiers locaux ; à droite, le dossier /uploads sur le serveur SFTP. Glissez-déposez pour transférer vos fichiers en toute sécurité.</figcaption></figure><h3>Cas d’usage réels</h3><p>Mettre en place un serveur SFTP n’est pas juste un exercice technique : c’est une solution très utilisée en entreprise pour automatiser et sécuriser les échanges de fichiers. Voici quelques exemples concrets de situations où ce type de serveur devient un véritable atout dans un projet data.</p><h4>Cas 1: Intégration dans un pipeline ETL</h4><p>Exemple : un job Airflow récupère tous les nouveaux fichiers de /uploads, les transforme et les envoie dans un data warehouse.</p><h4>Cas 2: Réception sécurisée de fichiers clients</h4><p>Fini les partages non sécurisés. Vos clients déposent leurs données via SFTP et vous les récupérez automatiquement.</p><h4>Cas 3: Mise à jour automatique de dashboards</h4><p>Chaque nuit, un script SFTP télécharge des fichiers pour mettre à jour Power BI ou Tableau.</p><h3>Bonus : Authentification par clé SSH (recommandée)</h3><p>Plutôt que de vous connecter avec un mot de passe, vous pouvez utiliser une <strong>clé SSH</strong>, une méthode plus sécurisée et souvent obligatoire en entreprise. Cette section vous explique comment la générer et l’utiliser.</p><h4>1. Générez une clé (sur la machine cliente)</h4><pre>ssh-keygen -t rsa -b 4096 -C &quot;email@example.com&quot;</pre><p>➡️ Appuyez sur Entrée à chaque étape pour accepter les chemins par défaut.</p><h4>2. Copiez la clé publique sur le serveur</h4><pre>ssh-copy-id sftpuser@ip_serveur</pre><p>➡️ Sinon, copiez manuellement id_rsa.pub dans ~/.ssh/authorized_keys</p><h4>3. (Optionnel) Désactivez la connexion par mot de passe</h4><p>Dans le fichier /etc/ssh/sshd_config, remplacez ou ajoutez :</p><pre>PasswordAuthentication no</pre><p>Puis :</p><pre>sudo service ssh restart</pre><p>Dans FileZilla :</p><ul><li><strong>Édition &gt; Paramètres &gt; SFTP</strong></li><li>Cliquez sur <strong>Ajouter un fichier de clé…</strong> et sélectionnez id_rsa</li></ul><h3>En conclusion</h3><p>Un serveur SFTP est simple à mettre en place, sécurisé et puissant</p><p>Il devient une <strong>brique essentielle</strong> pour :</p><ul><li>Automatiser les échanges de données</li><li>Collaborer avec des clients et partenaires</li><li>Protéger la confidentialité des fichiers</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657b7c0a662e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Créez un Chatbot intelligent avec RAG : le guide complet, étape par étape]]></title>
            <link>https://medium.com/@cartelgouabou/cr%C3%A9ez-un-chatbot-intelligent-avec-rag-le-guide-complet-%C3%A9tape-par-%C3%A9tape-ebd787513e47?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd787513e47</guid>
            <category><![CDATA[chainlit]]></category>
            <category><![CDATA[running-llm-locally]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[tutoriel-ia]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 21:11:13 GMT</pubDate>
            <atom:updated>2025-04-14T20:20:29.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>Créez un Chatbot intelligent avec RAG : le guide complet, étape par étape</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbOhjoBmlkH2AGz9n-i6Lg.jpeg" /><figcaption><a href="https://botnation.ai/site/fr/meilleur-chatbot/">Source</a></figcaption></figure><p>Imaginez que vous travaillez dans une entreprise spécialisée dans les énergies renouvelables. Chaque jour, des dizaines de collaborateurs posent des questions spécifiques : des informations techniques sur un produit, la disponibilité des pièces de rechange, ou encore des données récentes sur les performances des équipements installés. Vous pourriez bien sûr créer un chatbot classique, mais comment lui permettre d’accéder instantanément à l’ensemble des connaissances internes et actualisées de votre entreprise pour fournir des réponses précises et à jour ?</p><p>C’est là qu’intervient la puissance du <strong><em>Retrieval-Augmented Generation (RAG)</em></strong>. Dans cet article, je vais vous expliquer en détail ce qu’est exactement le <em>RAG</em> et surtout vous guider pas à pas dans la création d’un chatbot pratique et performant. Ce tutoriel se base sur un exemple concret : un chatbot capable de répondre précisément aux questions sur les prix des carburants en France, en utilisant des données réelles régulièrement mises à jour.</p><p>L’objectif est de rendre ce guide extrêmement pratique et facilement reproductible pour toute personne curieuse possédant des notions basiques en Python. Pour vous faciliter encore plus la tâche, le projet complet associé à ce tutoriel est disponible sur mon dépôt GitHub, entièrement implémenté et prêt à être exploré.</p><h3>I- Qu’est-ce que Retrieval-Augmented Generation (RAG) ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35ANNmqKgJZrrirxK32DOQ.jpeg" /><figcaption><a href="https://www.google.fr/url?sa=i&amp;url=https%3A%2F%2Fwww.groupefinaction.com%2Frenoncer-a-une-heritage%2Fbonhomme-blanc-point-dinterrogation%2F&amp;psig=AOvVaw1yvz5FJ6Lxu-OB-tAd-24O&amp;ust=1742896647647000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBUQjRxqFwoTCMDEvo-6oowDFQAAAAAdAAAAABAW">Source</a></figcaption></figure><p>Le<em> </em><strong><em>Retrieval-Augmented Generation (RAG)</em></strong> est une approche avancée en Intelligence Artificielle qui combine la puissance des grands modèles de langage (<em>LLM</em>s) tels que GPT-4 (OpenAI), Gemini (Google DeepMind), Llama 3 (Meta), ou encore Mistral (Mistral AI), avec des systèmes de récupération de données externes. Cette combinaison permet à votre chatbot de devenir “expert” sur des sujets spécifiques en exploitant directement les connaissances internes de votre entreprise.</p><p>Concrètement, lorsqu’une question est posée, le RAG effectue d’abord une recherche dans une base de données ou une autre source externe pour récupérer des informations pertinentes. Ces données récupérées viennent enrichir le contexte initial de la requête, permettant ainsi au modèle de langage de produire une réponse précise et pertinente.</p><p>Utiliser le <em>RAG</em> présente plusieurs avantages clés :</p><ul><li><strong>Spécialisation du chatbot</strong> : le <em>RAG</em> permet d’intégrer directement vos données internes, spécialisant ainsi votre chatbot aux besoins spécifiques de votre entreprise ou secteur.</li><li><strong>Gestion des données dynamiques</strong> : il facilite l’intégration efficace de données fréquemment mises à jour.</li><li><strong>Meilleure précision et fiabilité</strong> : en associant des données vérifiées et actualisées avec les capacités génératives des modèles de langage, le <em>RAG </em>améliore sensiblement la qualité et l’exactitude des réponses fournies.</li><li><strong>Moins coûteux</strong> : le RAG réduit significativement les coûts en évitant le besoin de réentraîner entièrement le modèle lors des mises à jour des informations, rendant ainsi la gestion de l’IA plus économique.</li></ul><p>En résumé, le <em>RAG</em> transforme votre chatbot en un véritable “expert” capable de fournir des réponses précises, pertinentes et actualisées en permanence, sans nécessiter de réentraînement complet du modèle, tout en s’adaptant aisément à l’évolution constante de votre base de connaissances, de manière économique.</p><h3>II- Comprendre le Workflow d’un Pipeline RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8slxP1dBJk6YXQxykZ7kzg.png" /><figcaption><a href="https://www.acorn.io/wp-content/uploads/2024/11/RAG_1200_x_800px_c15f070854.png">Source</a></figcaption></figure><p>Le cœur d’un système <strong><em>RAG (Retrieval-Augmented Generation)</em></strong> repose sur une orchestration rigoureuse de modules qui transforment une simple question en langage naturel en une réponse précise, fiable et contextualisée à partir d’une base documentaire. Cette approche hybride, mêlant <strong>recherche d’information</strong> et <strong>génération de texte</strong>, combine le meilleur des deux mondes : la précision des moteurs de recherche et la fluidité des grands modèles de langage (LLMs).</p><p>Décortiquons chaque étape du pipeline, en mettant en lumière les concepts clés, les outils utilisés, et les bonnes pratiques.</p><h4>1. 🧾Requête Utilisateur : Compréhension de l’intention</h4><p>Tout commence par une <strong>question posée en langage naturel</strong>. Elle peut être floue, implicite, ou très spécifique. Le système doit <strong>comprendre l’intention</strong> derrière la formulation pour guider les étapes suivantes.</p><p><strong>Objectif</strong> : Détecter ce que cherche vraiment l’utilisateur (lieu, action, date, entité…) et préparer la requête à être exploitée par le moteur de recherche.</p><p><strong>Exemples</strong> :</p><ul><li>“Quel est le prix du gazole à Toulouse aujourd’hui ?”</li><li>“Montre-moi les stations les moins chères autour de Lyon.”</li></ul><p><strong>Outils &amp; techniques</strong> :</p><ul><li><strong>Interfaces web ou APIs</strong> (formulaires, chatbots)</li><li><strong>NLP classique</strong> : spaCy (extraction d’entités nommées, POS tagging); Transformers (NER, parsing, question classification)</li><li><strong>Enrichissement contextuel</strong> : LangChain (gestion de contexte conversationnel); PromptLayer (gestion de prompts dynamiques, logging)</li></ul><p>La qualité de la réponse dépend de la <strong>compréhension initiale</strong> de la question. Extraire les bonnes entités et clarifier l’intention sont les fondations d’un <em>RAG</em> efficace.</p><h4>2. 🔢Encodage Sémantique : Transformer la requête en vecteur</h4><p>Une fois la requête analysée, elle est convertie en un <strong>vecteur dense</strong> qui capture son <strong>sens sémantique</strong>. Ce vecteur sera utilisé pour interroger une base documentaire vectorisée.</p><p><strong>Objectif</strong> : Créer une <strong>représentation numérique</strong> de la requête, indépendante de sa forme grammaticale, mais fidèle à son sens.</p><p><strong>Outils populaires</strong> :</p><ul><li>SentenceTransformers (SBERT) : rapide, efficace, open-source</li><li>MiniLM, E5, BGE, Instructor : légers et performants</li><li><strong>API cloud</strong> : OpenAI Embeddings, Cohere, HuggingFace Inference</li></ul><p>Le vecteur permet de <strong>comparer sémantiquement</strong> la question à des documents, même si les mots exacts ne sont pas présents. C’est le cœur de la recherche “intelligente”.</p><p><strong>Important</strong> : le modèle utilisé pour encoder la requête doit <strong>être le même</strong> que celui utilisé pour encoder les documents. Cela garantit que les représentations sont dans le <strong>même espace vectoriel</strong>, ce qui est indispensable pour une recherche sémantique efficace.</p><h4>3. 📚Recherche d’Information : Matching sémantique</h4><p>Le vecteur de la requête est comparé aux vecteurs de tous les documents disponibles. On identifie ainsi les <strong><em>chunks</em> (morceaux de texte)</strong> les plus proches sémantiquement.</p><p><strong>Objectif : </strong>Retrouver les <strong>k documents les plus pertinents</strong> pour répondre à la question.</p><p><strong>Outils (bases vectorielles) :</strong></p><ul><li>FAISS : rapide, local, open-source</li><li>Pinecone : scalable, as-a-service</li><li>Weaviate, Qdrant, Chroma : modernes, open-source, avec recherche hybride (BM25 + embeddings)</li></ul><p><strong>Bonnes pratiques :</strong></p><ul><li>Réindexer régulièrement les documents</li><li>Évaluer la pertinence avec des jeux de requêtes (benchmarks)</li><li>Choisir le bon type d’index (flat, IVF, HNSW selon la taille et la vitesse désirée)</li></ul><p>Pas de bonne réponse sans bons documents. Cette étape conditionne directement la qualité finale du système.</p><p><strong>Important</strong>: Si les documents changent fréquemment (nouvelles données, corrections…), mettre en place un script ou un job planifié (ex: <strong>cron job</strong>, <strong>workflow Airflow</strong>, ou pipeline <strong>ETL</strong>) permet de régénérer l’index à intervalles réguliers.</p><h4>4. 🧹Préparation du contexte : nettoyage, filtrage, chunking</h4><p>Les documents retrouvés sont souvent bruts. Il faut les préparer avant de les envoyer au LLM, qui a une <strong>limite de tokens</strong>.</p><p><strong>Sous-étapes clés :</strong></p><ul><li><strong>Nettoyage</strong> : suppression de bruit, doublons, mise en forme</li><li><strong>Chunking</strong> : découpe du texte en blocs cohérents (300–500 tokens en moyenne). la taille des chunks dépend aussi de la <strong>fenêtre de contexte du LLM</strong> utilisé. Un modèle comme GPT-3.5 supporte ~4k tokens, tandis qu’un TinyLlama ou un modèle local aura souvent une limite plus basse (~2k). Adapter dynamiquement le chunking évite le <strong>troncage</strong> ou la <strong>perte d’infos</strong> critiques.</li><li><strong>Filtrage top-k</strong> : ne garder que les documents les plus pertinents</li><li><strong>Fusion</strong> : assembler un prompt clair et contextuel pour le LLM</li></ul><p><strong>Outils :</strong></p><ul><li>LangChain : chaînes de traitement, text splitters, prompt templates</li><li>LlamaIndex : indexing + prompt contextuel auto-généré</li><li>Haystack : pipelines modulaires de RAG</li></ul><p>Un prompt <strong>mal construit</strong> peut entraîner des <strong>hallucinations</strong>. En revanche, un bon contexte bien structuré permet au LLM de répondre de façon <strong>précise, claire et fiable</strong>.</p><h4>5. 💬Génération de Réponse : appel au LLM</h4><p>Le contexte est prêt, on le combine avec la question de l’utilisateur pour générer une réponse fluide, synthétique et factuelle.</p><p><strong>Objectif :</strong> Générer une réponse <strong>contextualisée à partir des documents</strong>, en évitant toute <strong>hallucination</strong> (c’est-à-dire des informations inventées par le modèle)</p><p><strong>Modèles LLM recommandés :</strong></p><ul><li><strong>Open-source</strong> : Mistral 7B, Mixtral, LLaMA 2, Gemma, TinyLlama , DeepSeek</li><li><strong>Propriétaires</strong> : GPT-3.5/4, Claude</li></ul><p><strong>Serveurs d’inférence :</strong></p><ul><li>Transformers (inference local)</li><li>vLLM, text-generation-inference : efficaces pour du batch, scalable</li></ul><p>Le LLM synthétise des documents pour fournir une réponse <strong>fluide</strong>, <strong>résumée</strong>, et <strong>pertinente</strong>. C’est ce qui transforme l’information brute en réponse utile.</p><p><strong>Pour aller plus loin</strong> :</p><ul><li><a href="https://medium.com/@kiran.phd.0102/rag-fusion-revolution-a-paradigm-shift-in-generative-ai-2349b9f81c66"><strong>RAG Fusion</strong></a> : génère plusieurs reformulations de la requête utilisateur pour croiser les résultats et produire une réponse plus robuste.</li><li><a href="https://medium.com/@sahin.samia/what-is-reranking-in-retrieval-augmented-generation-rag-ee3dd93540ee#:~:text=Reranking%20in%20Retrieval%2DAugmented%20Generation%20(RAG)%20refers%20to%20the,use%20in%20generating%20a%20response."><strong>Re-ranking</strong></a> : trie les documents récupérés selon leur pertinence avec un modèle spécialisé comme <strong>BGE-Reranker</strong> ou <strong>Cohere Re-ranker</strong>.</li></ul><p>Ces techniques avancées permettent de booster la <strong>fiabilité</strong>, la <strong>précision</strong> et la <strong>résilience</strong> du pipeline RAG, notamment dans des cas d’usage complexes ou à fort enjeu (santé, finance, juridique…).</p><h4>6. 🖥️Affichage, Justification et Explicabilité</h4><p>La réponse est enfin affichée à l’utilisateur. Mais pour gagner sa confiance, on peut l’<strong>augmenter avec des sources, des preuves, ou un raisonnement</strong>.</p><p><strong>Compléments possibles :</strong></p><ul><li>Affichage du <strong>contexte utilisé</strong></li><li>Affichage des <strong>sources documentaires</strong> ou des URLs</li><li><strong>Chaîne de raisonnement (Chain-of-Thought)</strong> : explication pas à pas</li></ul><p><strong>Outils d’interface :</strong></p><ul><li>LangChain Agents : pour tracer les étapes de raisonnement</li><li>Gradio, Streamlit, Chainlit , etc… : pour créer des interfaces interactives</li></ul><p>Donner accès aux <strong>preuves</strong> renforce la <strong>confiance utilisateur</strong>. C’est particulièrement utile en entreprise ou en contexte critique.</p><h4>🏛️En résumé : les 3 piliers d’un pipeline RAG réussi</h4><ol><li><strong>Une recherche d’information robuste</strong><br> → Embeddings de qualité + base vectorielle adaptée + bons filtres de similarité</li><li><strong>Une génération fiable et contextualisée</strong> → Prompt bien structuré + modèles adaptés + gestion de tokens</li><li><strong>Une architecture modulaire, ouverte et scalable</strong><br> → Pour expérimenter, itérer rapidement et monter en charge facilement</li></ol><h3>III- Tutoriel Pratique : Construire un Chatbot RAG pour les Prix du Carburant</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4whDdUYZup0Jwo-JX_t5-Q.png" /><figcaption>Application interactive permettant de poser des questions en langage naturel et d’obtenir des réponses contextualisées sur les données réelles des stations. Source: <a href="https://github.com/cartelgouabou/fuel-prices-fr-chatbot">https://github.com/cartelgouabou/fuel-prices-fr-chatbot</a></figcaption></figure><h4>1. Origine et préparation des données</h4><p>Avant d’implémenter le chatbot, un pipeline <strong>ETL complet</strong> a été mis en place pour extraire, transformer et structurer les données.</p><p><strong>Source des données: </strong>Les prix des carburants sont issus de l’API publique <a href="https://www.data.gouv.fr/fr/datasets/prix-des-carburants-en-france-flux-instantane-v2-amelioree/">data.gouv.fr</a> qui fournit des informations actualisées au format JSON, via une API paginée.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*bs7RmPLyFRHX9_suPZlYuw.png" /><figcaption>Visualisation d’un extrait brut retourné par l’API de <a href="https://data.gouv.fr/">data.gouv.fr</a>, contenant les informations de stations-service : adresse, types de carburant, prix, date de mise à jour, etc.</figcaption></figure><p><strong>Pipeline ETL (dans le dossier </strong><strong>etl/)</strong> :</p><ul><li>fetch_data.py : télécharge les données brutes depuis l’API</li><li>transform_data.py : nettoie et structure les données</li><li>load_data.py : charge les données dans une base SQLite locale</li><li>process_fuel_embeddings.py : encode les stations sous forme vectorielle</li></ul><pre># Lancer le pipeline complet :<br>python etl/run_etl.py</pre><p>Ces données alimentent ensuite notre pipeline RAG.</p><h4>2. Génération des embeddings FAISS</h4><p>Fichier : process_fuel_embeddings.py<br>Correspond aux étapes <strong>2 &amp; 3 du pipeline RAG</strong> (encodage sémantique + recherche)</p><p><strong>Objectif :</strong></p><ul><li>Formater chaque station sous forme de texte enrichi</li><li>Générer des embeddings avec MiniLM</li><li>Indexer les vecteurs avec FAISS pour des recherches rapides</li></ul><pre>df[&quot;text&quot;] = df.apply(lambda row: (<br>    f&quot;{row.city.upper()} station id {row.station_id} located at {row.address}, {row.code_department}, {row.region}. &quot;<br>    f&quot;Prices: Gazole={row.gazole_price}, SP98={row.sp98_price}, SP95={row.sp95_price}, &quot;<br>    f&quot;E10={row.e10_price}, E85={row.e85_price}, GPLC={row.gplc_price}.&quot;<br>), axis=1)<br><br>model = SentenceTransformer(&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>embeddings = model.encode(df[&quot;text&quot;].tolist(), convert_to_numpy=True)<br><br>index = faiss.IndexFlatL2(embeddings.shape[1])<br>index.add(embeddings)<br>faiss.write_index(index, &quot;data/faiss_index&quot;)</pre><h4>3. Création de l’interface chatbot</h4><p>Fichier : app/chatbot.py</p><p>Implémente les étapes <strong>1, 4, 5 et 6</strong> du pipeline.</p><p><strong>Requête utilisateur &amp; détection de lieu (étape 1)</strong></p><pre>from flashtext import KeywordProcessor<br><br>city_matcher = KeywordProcessor()<br>for city in metadata_df[&quot;city&quot;].dropna().unique():<br>    city_matcher.add_keyword(city.lower())<br><br>query = &quot;stations les moins chères à Marseille&quot;<br>detected_city = city_matcher.extract_keywords(query)</pre><p><strong>Recherche sémantique (étapes 2 &amp; 3)</strong></p><pre>query_vec = embed_model.encode([query], convert_to_numpy=True)<br>distances, indices = faiss_index.search(query_vec, k=50)<br>results = metadata_df.iloc[indices[0]]</pre><p><strong>Préparation du prompt (étape 4)</strong></p><pre>context = &quot;\n&quot;.join(results[&quot;text&quot;].tolist())<br>prompt = f&quot;&quot;&quot;Given the following fuel stations data:\n{context}\n\nAnswer the user&#39;s question: {query}\nAnswer:&quot;&quot;&quot;</pre><p><strong>Génération de réponse (étape 5)</strong></p><pre>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(device)<br>with torch.no_grad():<br>    outputs = model.generate(**inputs, max_new_tokens=200)<br>response = tokenizer.decode(outputs[0], skip_special_tokens=True)</pre><p><strong>Affichage et explicabilité (étape 6)</strong></p><pre>st.markdown(&quot;### Context Given to the LLM&quot;)<br>st.code(context, language=&quot;text&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QL7WyeX3ujT7U1_xdetVvw.png" /><figcaption>Aperçu du contexte (textes enrichis) sélectionné par la recherche sémantique et envoyé au LLM pour générer une réponse pertinente.</figcaption></figure><h4><strong>Résumé : Outils utilisés à chaque étape du pipeline RAG</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwFwoF_LjyHVlvp_qK2Rdw.png" /></figure><p><strong>Accéder au code complet</strong></p><p>🔹 Repos GitHub : <a href="https://github.com/cartelgouabou/fuel-prices-fr-chatbot">https://github.com/cartelgouabou/fuel-prices-fr-chatbot</a></p><h3>Conclusion</h3><p>Ce tutoriel démontre qu’il est possible de construire un système RAG performant, local et open-source sans infrastructure complexe ni dépendance à des API coûteuses. En combinant des briques accessibles (FAISS, MiniLM, <strong>Mistral via Ollama</strong>, Streamlit), on obtient un chatbot capable de répondre de manière fiable à des requêtes spécifiques en s’appuyant sur des données fraîches et structurées.</p><p>Ce type d’architecture est réplicable dans de nombreux cas d’usage : support client, documentation interne, veille métier, analyse réglementaire, etc. L’important n’est pas tant la taille du modèle que la qualité des données, la précision du contexte, et la modularité de l’implémentation.</p><p>En résumé, un bon RAG =<br> <strong>(recherche pertinente) + (contexte bien préparé) + (génération contrôlée)</strong></p><h3>Pour aller plus loin !</h3><p>Tu veux tester, modifier ou étendre ce projet ? Voici quelques pistes concrètes pour explorer davantage le potentiel de cette architecture RAG locale et open-source :</p><ul><li><strong>Adapter le pipeline à d’autres domaines métier</strong><br> Exploite ce même schéma pour des cas d’usage dans le <strong>juridique</strong> (jurisprudence, contrats), la <strong>santé</strong> (protocoles médicaux, remboursements), l’<strong>immobilier</strong> (prix, annonces, législation locale), ou tout autre secteur disposant de données structurées.</li><li><strong>Expérimenter avec d’autres modèles de langage</strong><br> Teste des alternatives comme <strong>Gemma</strong>, <strong>LLaMA 3</strong>, ou des modèles spécialisés (ex : médicaux ou juridiques) via Ollama ou d’autres serveurs locaux compatibles.</li><li><strong>Ajouter une interface de feedback utilisateur</strong><br> Intègre un système simple (thumbs up/down, notation, ou commentaire libre) pour recueillir les retours des utilisateurs et améliorer la pertinence des réponses au fil du temps.</li><li><strong>Passer à un backend plus robuste</strong><br> Connecte le système à une <strong>base PostgreSQL</strong> pour de meilleures performances ou à un <strong>service cloud</strong> (type Supabase, Render, Railway) pour le rendre accessible en ligne.</li><li><strong>Intégrer une couche d’observabilité</strong><br> Mets en place un <strong>système de logs détaillés</strong> (via Loguru, Sentry ou Prometheus + Grafana) pour tracer les requêtes, analyser les comportements, détecter les erreurs et suivre l’utilisation en production.</li><li><strong>Expérimenter le RAG-Fusion (multi-requêtes)</strong><br> Envoie plusieurs variantes reformulées d’une même question pour renforcer la <strong>robustesse</strong> de la recherche et la <strong>pertinence des résultats</strong> retournés (principe de <strong>RAG-fusion</strong>).</li><li><strong>Optimiser la pertinence des documents fournis au LLM</strong><br> Implémente des techniques comme le <strong>re-ranking</strong>, la <strong>diversité de contexte</strong>, ou le <strong>query expansion</strong> pour raffiner le contexte donné au modèle génératif.</li><li><strong>Créer une interface mobile ou vocale</strong><br> Pour une expérience plus accessible, imagine une déclinaison mobile ou un assistant vocal (via Whisper + TTS) basé sur ce moteur RAG.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd787513e47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide: Monitoring ML Model Performance with Prometheus & Grafana]]></title>
            <link>https://medium.com/@cartelgouabou/step-by-step-guide-monitoring-ml-model-performance-with-prometheus-grafana-88195f741365?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/88195f741365</guid>
            <category><![CDATA[grafana-prometheus]]></category>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[model-performance]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 19:08:43 GMT</pubDate>
            <atom:updated>2025-03-05T19:08:43.636Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’ll walk you through deploying a simple <strong>sentiment analysis app</strong> using <strong>Streamlit</strong> and setting up <strong>Prometheus</strong> and <strong>Grafana</strong> to monitor the model’s performance in real time. By the end, you’ll be able to track key metrics like <strong>model accuracy</strong> and <strong>number of requests</strong>.</p><p>For the <strong>full implementation</strong>, including all source code and configurations, visit the <strong>GitHub repository</strong>: <a href="https://github.com/cartelgouabou/Full_stacks_ai_course/tree/main/tools/data_science_toolkit/prometheus-grafana-ml">Full Implementation on GitHub</a>.</p><h3>Live Demo</h3><p>You can also try the <strong>deployed version of the app</strong> on Streamlit: 👉 <a href="https://app-sentiment-app-tuto-blmogyankjkwsuh77prxvq.streamlit.app/">Live Sentiment Analysis App</a></p><h3>Prerequisites</h3><ol><li><strong>Python 3.7+</strong> installed</li><li><strong>Docker</strong> installed (for running Prometheus and Grafana)</li></ol><ul><li>Install Docker by following the official guide: <a href="https://www.docker.com/get-started/">https://www.docker.com/get-started/</a></li><li>🔹 <em>Highly recommended:</em> After installing Docker, add the <strong>Docker extension</strong> in <strong>VS Code</strong> for easier container management.</li></ul><p>3. Basic understanding of Python and machine learning</p><h3>GitHub Repository Structure</h3><pre>prometheus-grafana-mlops<br>├── app<br>│   ├── app.py               # Streamlit app UI logic<br>│   └── model.py             # Sentiment analysis model and prediction logic<br>├── monitoring<br>│   ├── prometheus.yml           # Prometheus configuration file<br>│   ├── Dockerfile.prometheus    # Dockerfile to build Prometheus<br>│   └── Dockerfile.grafana       # Dockerfile to build Grafana<br>├── tuto-assets<br>│   ├── step1_running_app.png    # Screenshot to ease the application of the tutorial<br>│   ├── ...<br>│   └── ...<br>├── Dockerfile.app      # Dockerfile for Streamlit app<br>├── .gitignore          # Files/folders to ignore in Git<br>├── requirements.txt    # Python dependencies for local setup<br>└── README.md           # This guide</pre><h3>Step 1: Clone the Repository &amp; Install Dependencies</h3><p>Let’s start by cloning the repository and setting up your environment.</p><h3>1. Clone the Repository Using Sparse Checkout</h3><pre># Clone the repository in sparse-checkout mode<br>git clone --no-checkout https://github.com/cartelgouabou/Full_stacks_ai_course.git<br>cd Full_stacks_ai_course<br><br># Initialize sparse-checkout and set the target folder<br>git sparse-checkout init --cone<br>git sparse-checkout set tools/data_science_toolkit/prometheus-grafana-ml<br>git checkout main<br><br># Move the project folder and clean up<br>mv tools/data_science_toolkit/prometheus-grafana-ml ../prometheus-grafana-ml<br>cd ..<br>rm -r Full_stacks_ai_course # Run as administrator if needed<br><br># Navigate to the project directory<br>cd prometheus-grafana-ml</pre><h3>2. Set Up a Virtual Environment and Install Dependencies</h3><pre>python -m venv venv_tuto<br>source venv_tuto/bin/activate  # On Windows use `.\venv_tuto\Scripts\activate`<br>pip install streamlit plotly prometheus-client transformers torch</pre><h3>Step 2: Run the Streamlit App</h3><h3>Option 1: Run Locally</h3><pre>streamlit run app/app.py</pre><ul><li>Open <strong>http://localhost:8501</strong> in your browser.</li><li>Visit <strong>http://localhost:8001/metrics</strong> to see the exposed metrics.</li></ul><h3>Option 2: Run the App Using Docker</h3><pre>docker build -t streamlit-sentiment-app -f ./Dockerfile.app .<br>docker run -d -p 8501:8501 streamlit-sentiment-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sirVV0El2VKDD28yGE_HBg.png" /><figcaption><em>The Streamlit sentiment analysis app running locally</em></figcaption></figure><h3>Step 3: How Prometheus is Integrated in the Code</h3><p>Prometheus is integrated into the <strong>Streamlit app</strong> to expose monitoring metrics. Below are the key parts of the implementation:</p><h3>1. Start Prometheus Metrics Server</h3><p>The app starts an HTTP server on port <strong>8001</strong> to expose the metrics that Prometheus will scrape.</p><pre>from prometheus_client import start_http_server<br>start_http_server(8001)</pre><h3>2. Define Metrics</h3><p>We define <strong>counters</strong> and <strong>gauges</strong> to track requests and model accuracy.</p><pre>from prometheus_client import Gauge, Counter<br><br>request_count_metric = Counter(&quot;ml_model_requests_total&quot;, &quot;Total number of prediction requests&quot;)<br>accuracy_metric = Gauge(&quot;ml_model_accuracy&quot;, &quot;User-reported model accuracy&quot;)</pre><h3>3. Update Metrics in the App</h3><p>Metrics are updated dynamically based on user interactions.</p><pre>if st.button(&quot;Analyze Sentiment&quot;):<br>    request_count_metric.inc()<br>    label, confidence = predict_sentiment(user_input)<br><br>if feedback == &quot;Yes&quot;:<br>    accuracy_metric.set(new_accuracy_value)</pre><p>For the <strong>complete implementation</strong>, check the <a href="https://github.com/cartelgouabou/Full_stacks_ai_course/tree/main/tools/data_science_toolkit/prometheus-grafana-ml">GitHub Repository</a>.</p><h3>Step 4: Configure Prometheus</h3><p>Modify prometheus.yml:</p><pre>global:<br>  scrape_interval: 5s<br><br>scrape_configs:<br>  - job_name: &#39;ml_model&#39;<br>    static_configs:<br>      - targets: [&#39;host.docker.internal:8001&#39;]</pre><h3>Run Prometheus Container</h3><pre>docker build -t custom-prometheus -f monitoring/Dockerfile.prometheus .<br>docker run -d --name=prometheus -p 9090:9090 custom-prometheus<br><br></pre><h3>Querying Metrics in Prometheus</h3><p>To verify that Prometheus is collecting metrics, go to <strong>http://localhost:9090</strong>, enter ml_model_accuracy in the search bar, and click <strong>Execute</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3D3-CuebTKLoJyLKWNmPQ.png" /><figcaption><em>Using Prometheus UI to query the ML model accuracy metric</em></figcaption></figure><h3>Step 5: Set Up Grafana</h3><pre>docker build -t custom-grafana -f monitoring/Dockerfile.grafana .<br>docker run -d --name=grafana -p 3000:3000 custom-grafana</pre><ul><li>Open <a href="http://localhost:3000/"><strong>http://localhost:3000</strong></a></li><li>Login: <strong>admin/admin</strong></li><li>Add <strong>Prometheus</strong> as a data source</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZCojfyJMjppfnuP6MJKGA.png" /></figure><h3>Step 6: Create Grafana Dashboards</h3><h3>1. Create a New Dashboard</h3><ul><li>Go to <strong>Dashboard → Create dashboard → Add visualization</strong></li><li>Choose <strong>prometheus source</strong></li></ul><h3>2. Add Queries</h3><pre>ml_model_accuracy<br><br>ml_model_requests_total</pre><ul><li>Customize visualization (line chart, gauge, etc.).</li><li>Set refresh rate to <strong>5s</strong>.</li></ul><h3>Step 7: Set Alerts in Grafana</h3><ul><li>Navigate to the <strong>Alert</strong> tab in your dashboard.</li><li><strong>Set an alert if model accuracy falls below 80%:</strong></li></ul><pre>ml_model_accuracy &lt; 0.8</pre><p>Configure notifications (Slack, email, etc.) using <strong>Alertmanager</strong>.</p><h3>Conclusion</h3><p>You’ve now set up a complete <strong>ML model monitoring pipeline</strong> using <strong>Prometheus</strong> and <strong>Grafana</strong>. Try out the <strong>live app</strong> <a href="https://app-sentiment-app-tuto-blmogyankjkwsuh77prxvq.streamlit.app/">here</a> and check out the <strong>full implementation</strong> on <a href="https://github.com/cartelgouabou/Full_stacks_ai_course/tree/main/tools/data_science_toolkit/prometheus-grafana-ml">GitHub</a> for all the source code and configurations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88195f741365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bringing AI to Real-World Healthcare: Key Challenges and Solutions]]></title>
            <link>https://medium.com/@cartelgouabou/bringing-ai-to-real-world-healthcare-key-challenges-and-solutions-38ff91eb7fa0?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ff91eb7fa0</guid>
            <category><![CDATA[healthcare-ai-challenges]]></category>
            <category><![CDATA[ai-in-healthcare]]></category>
            <category><![CDATA[ai-challenge]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 21:35:22 GMT</pubDate>
            <atom:updated>2024-11-14T21:35:22.332Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Imagine a doctor’s office in the near future. A patient comes in with a complex health issue, and instead of relying solely on traditional methods, the doctor turns to an advanced AI model trained to analyze medical images and predict outcomes. With just a few clicks, the AI processes data, and within seconds, it suggests a diagnosis and treatment options based on patterns from thousands of similar cases. The doctor reviews these insights, adds their own expertise, and confidently makes a decision that could improve the patient’s health faster and more accurately than ever before.</p><p>This vision of AI assisting doctors and enhancing healthcare is closer to becoming a reality than we might think. Yet, while this future is full of promise, bringing it to life in real-world settings is no simple task. AI models that perform well in controlled lab environments don’t always transition smoothly to the complexities of actual hospitals and clinics. They encounter challenges like handling diverse, real-world data and ensuring fair treatment for all patients. Overcoming these obstacles is essential to making AI a dependable and valuable tool in healthcare.</p><p>In this article, we’ll explore some of the main challenges AI faces in real-world healthcare and the practical solutions to address them. By understanding these issues and the steps we can take to resolve them, we get closer to a future where AI is not just a tool but a reliable partner in patient care.</p><h3>1. Adapting to New Populations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laZkcmUi2q35p-doWo7f_g.png" /><figcaption>Comparison of internal and external validation: Internal validation uses the same dataset split for training and testing, while external validation tests the model on independent data, providing a more realistic measure of its performance in new settings. [<a href="https://doi.org/10.1016/j.patter.2020.100129">Extensions of the External Validation for Checking Learned Model Interpretability and Generalizability</a>]</figcaption></figure><p>A major challenge for AI in healthcare is making sure models work well for everyone, not just the specific groups they were trained on. When AI models are trained, they often “learn” from a specific set of patient data. If the real-world patient population looks different from this training data, the model might not work as well. For example, a model trained on younger patients might struggle with older ones.</p><h3>Solution: Testing on New Data and Fine-Tuning</h3><p>To check if the model will work with different groups, we need to test it on a new set of patients (called <em>external validation</em>). If it doesn’t perform well, we can gather a few samples from the new group to retrain and fine-tune the model. This approach helps the model better understand and predict outcomes for a broader range of patients.</p><p><strong>Explore More</strong>:</p><ul><li><a href="https://doi.org/10.1016/j.patter.2020.100129">Extensions of the External Validation for Checking Learned Model Interpretability and Generalizability</a></li></ul><h3>2. Working with New, Real-Time Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNX38eVasLWdBM_yx9U-mQ.png" /><figcaption>Difference between training and real-world data: Retrospective data includes only front-view chest x-rays (left), while prospective data in real-world settings can include side-view x-rays (right). This variation can impact the model’s performance if not accounted for. [<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.mdpi.com%2F2076-3417%2F11%2F6%2F2751&amp;psig=AOvVaw2AkPKoqiARilYCi-Ns0hWZ&amp;ust=1731684713998000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCLDDzsWS3IkDFQAAAAAdAAAAABAb">left image</a> &amp; <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.academicradiology.org%2Farticle%2FS1076-6332%252810%252900406-X%2Ffulltext&amp;psig=AOvVaw2AkPKoqiARilYCi-Ns0hWZ&amp;ust=1731684713998000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCLDDzsWS3IkDFQAAAAAdAAAAABAk">right image</a>]</figcaption></figure><p>AI models are usually trained on “retrospective data,” which is data collected from past cases. This data is usually clean and well-organized. However, in real-world situations, new patient data is often incomplete and unfiltered. For example, an AI model trained to read chest x-rays may have only learned from front-view images, but in actual practice, side-view x-rays are also common.</p><h3>Solution: Adapting the Model to Handle Raw Data</h3><p>We can solve this by either training the model to handle different types of data or by filtering out certain types before using it. Training the model on a mix of data types, such as both front-view and side-view x-rays, makes it more adaptable and effective when working with real, diverse cases.</p><h3>3. Measuring Real-World Success</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*DrELaMOtowMdnKLLMCeAtQ.png" /><figcaption>Decision curve: Showing how the AI model helps balance the benefits of treatment against the risks of unnecessary procedures. [<a href="https://doi.org/10.1177/0272989x06295361">Decision curve analysis: a novel method for evaluating prediction models</a>]</figcaption></figure><p>While there are standard ways to measure how well an AI model performs in the lab (such as the AUROC curve, accuracy, etc.), these methods don’t always reflect real-life impacts. In healthcare, success is ultimately about helping patients get better, not just achieving high scores on technical metrics.</p><h3>Solution: Focus on Patient Outcomes and Clinical Studies</h3><p>To see if an AI model really benefits patients, we need to look at real-world outcomes. One approach is decision curve analysis, which calculates the overall benefit of using the model in patient care. Another approach is clinical trials, where we compare patient outcomes for those who receive AI-supported care versus those who don’t. These methods help us understand if the model is actually helping patients improve.</p><p><strong>Explore More</strong>:</p><ul><li><a href="https://doi.org/10.1177/0272989x06295361">Decision curve analysis: a novel method for evaluating prediction models</a></li><li><a href="https://doi.org/10.1016/j.spinee.2021.02.024">Decision curve analysis to evaluate the clinical benefit of prediction models</a></li></ul><h3>4. Reducing Bias to Ensure Fairness</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJO0BrvHj6ZYNDKofcQ76A.png" /><figcaption>Illustration of dataset bias: A model trained only on Dataset 1 (all white swans) may struggle to recognize new patterns, like the black swan in Dataset 2, highlighting the importance of diverse training data. [<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Ftowardsdatascience.com%2Ftypes-of-biases-in-data-cafc4f2634fb&amp;psig=AOvVaw16C2mKcTws0Rxoz3876phS&amp;ust=1731683670408000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCJiprcSO3IkDFQAAAAAdAAAAABAE">source</a>]</figcaption></figure><p>AI models can sometimes reflect and even increase biases present in their training data. For example, a model trained mostly on light-skinned individuals may not perform as well when analyzing images of darker-skinned patients. These biases can lead to unfair treatment and increase health disparities.</p><h3>Solution: Train on Diverse Data and Check for Bias</h3><p>To reduce bias, we need to train models on diverse data that includes a broad range of patient backgrounds. After training, we can test the model on different groups (such as by age, gender, and ethnicity) to make sure it performs equally well. This approach helps ensure fair and accurate results for all patients.</p><h3>5. Making AI Decisions Easy to Understand</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8V6b2lQpByfI0pDQ9OyBA.png" /><figcaption>Black Box vs. Explainable AI: Black Box AI gives results without showing how it reached them, while Explainable AI allows us to see and understand the steps it takes to make decisions. [<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fmedium.com%2F%40madeshselvam2002%2Ffrom-black-box-to-clear-box-the-promise-of-xai-332acb7dc46c&amp;psig=AOvVaw1fiEBUuvPssZ9OiS1xfW5H&amp;ust=1731684055429000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBcQjhxqFwoTCPjQkfqP3IkDFQAAAAAdAAAAABAE">source</a>]</figcaption></figure><p>Many AI models, especially deep learning models, are highly complex, which makes it difficult to understand how they reach their predictions. In healthcare, this lack of transparency can create a barrier of trust, as doctors and patients may hesitate to rely on decisions from a system they can’t fully interpret or explain. Clear, understandable AI models are crucial for building confidence and ensuring safe, effective use in clinical settings.</p><h3>Solution: Use Tools to Explain AI Decisions</h3><p>Using tools that show which parts of the data the model focused on — like attention maps — can give doctors a clearer picture of how the AI reached its decision. When doctors understand the AI’s reasoning, they can make better use of it in their care decisions, leading to safer and more trusted outcomes.</p><p><strong>Explore More</strong>:</p><ul><li><a href="https://doi.org/10.3390/app14198884">Recent Applications of Explainable AI (XAI): A Systematic Literature Review</a></li></ul><h3><strong>Conclusion</strong></h3><p>AI has the potential to make healthcare better, but using it effectively in real-life settings isn’t always easy. By taking steps to test models on different types of data, measure their impact on real patients, reduce bias, and make their decisions easier to understand, we can help AI become a reliable part of healthcare. These solutions bring us closer to an AI that supports doctors and improves patient care in ways that are both safe and fair. As we continue to improve these models, we’ll be able to create a healthcare system where AI truly helps everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ff91eb7fa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Medical Predictions: A Comprehensive Guide to Model Calibration]]></title>
            <link>https://medium.com/@cartelgouabou/enhancing-medical-predictions-a-comprehensive-guide-to-model-calibration-3ea741be88d7?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea741be88d7</guid>
            <category><![CDATA[model-calibration]]></category>
            <category><![CDATA[platt-scaling]]></category>
            <category><![CDATA[calibration-metrics]]></category>
            <category><![CDATA[healthcare-ai]]></category>
            <category><![CDATA[python-implementation]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 07:13:21 GMT</pubDate>
            <atom:updated>2024-07-23T07:55:33.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine a patient with a chronic condition that requires regular monitoring and precise medication adjustments. Despite their age being 65, they present symptoms typically seen in much older individuals. This discrepancy can complicate treatment, especially when predictive models don’t account for such variations.</p><p>While experienced clinicians can adjust their judgment based on these physical cues, predictive models often fail to do so without specific calibrations. When these models are applied to a different population than the one they were trained on, they may produce significant errors. These inaccuracies can lead to inappropriate treatment decisions, which might be harmful to individual patients, even if the model performs well on average.</p><p>Calibration is essential for ensuring the reliability of predictive models in medical decision-making, diagnosis, and prognosis. Initially, models are often compared and selected based on discrimination metrics, such as the area under the receiver-operating characteristic curve (AUROC). However, calibration goes a step further by measuring how closely predicted risks align with actual outcomes. A well-calibrated model provides accurate predictions across diverse patient populations, making it a vital component of effective healthcare modeling. This article explores the importance of calibration in enhancing medical predictions and presents practical methods for implementing it in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*rqwB33ZlLQnwqHRq7_xTjw.png" /><figcaption>[<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.flaticon.com%2Ffree-icon%2Fcalibrate_4307929&amp;psig=AOvVaw0UCEc9Z79Hnsm5KsncsL0Z&amp;ust=1721682704920000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjhxqFwoTCJDax4yGuYcDFQAAAAAdAAAAABAO">source</a>]</figcaption></figure><h3>I- Understanding Calibration in Medical Prediction</h3><h4><strong>What is Calibration?</strong></h4><p>Calibration in predictive modeling measures how closely predicted probabilities of an event match the actual outcomes. In medical applications, this means ensuring that if a model predicts a 30% chance of a medical event, that event occurs 30% of the time. Good calibration ensures reliable risk assessments, helping healthcare providers make better decisions. For example, a model predicting a 20% risk of complications after surgery should see complications in about 20% of those cases. This accuracy is vital for setting treatment thresholds and communicating risks to patients.</p><h4><strong>Importance of Calibration in Healthcare</strong></h4><p>Accurate calibration is critical in healthcare to improve patient outcomes. Well-calibrated models give healthcare professionals reliable risk estimates, aiding in decision-making and patient communication. Poor calibration can lead to incorrect clinical decisions, potentially harming patients. For instance, in oncology, a well-calibrated model predicting cancer recurrence helps oncologists plan appropriate treatments. If the model is off, it could lead to unnecessary treatments or missed critical interventions, impacting patient survival.</p><h3>II- Evaluating Calibration</h3><p>Evaluating the calibration of predictive models is a crucial step. There is no single best method for measuring calibration; each has its strengths and limitations. Here, we will explore three commonly used metrics: the Brier score, the calibration plot, and the Expected Calibration Error (ECE).</p><h4><strong>1. Brier Score</strong></h4><p>The Brier score is a widely used metric that quantifies the accuracy of probabilistic predictions. It is calculated as the mean squared error between predicted probabilities and actual outcomes, with lower scores indicating better calibration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*u4pvxUaSY56FkZDEQI2y9w.png" /><figcaption>Equation for calculating the Brier score.</figcaption></figure><p><strong>Strengths</strong>:</p><ul><li>Simple to compute and interpret.</li><li>Provides a single numerical value for easy comparison.</li><li>Suitable for binary and multiclass classification tasks.</li></ul><p><strong>Limitations</strong>:</p><ul><li>Interpretation Complexity: Without understanding whether the error is caused by a relatively small number of estimates with high error or a large number of estimates with smaller error, it is difficult to say whether this model could be used in practice.</li><li>Weighting of Errors<strong>: </strong>By squaring errors that are in the [0,1] range, large errors “count less” to the overall score when compared numerically with smaller errors. This can obscure significant deviations.</li><li>Components of Discrimination and Calibration: The Brier score includes components of both discrimination and calibration. Thus, a lower Brier score does not necessarily imply higher calibration.</li></ul><h4><strong>2. Calibration curve or reliability diagrams</strong></h4><p>The calibration curve is a visual tool that compares predicted probabilities to actual outcome frequencies. This plot typically displays predicted probabilities on the x-axis and the observed frequency of those outcomes on the y-axis. A perfectly calibrated model will produce a plot that follows a diagonal line.</p><p><strong>Strengths</strong>:</p><ul><li>Provides a clear visual representation of calibration.</li><li>Helps identify specific probability ranges where the model is well-calibrated or poorly calibrated.</li><li>Easy to interpret for both technical and non-technical audiences.</li></ul><p><strong>Limitations</strong>:</p><ul><li>Can be misleading if the sample size is small.</li><li>Does not provide a single summary statistic for easy comparison.</li></ul><h4><strong>3. Expected Calibration Error (ECE)</strong></h4><p>The ECE provides a single summary statistic that represents the average difference between predicted probabilities and actual outcomes across different probability bins. It combines aspects of both the Brier score and calibration plot into one metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xT2Nu46pJanHu_2S8QPpnQ.png" /><figcaption>Equation for estimating the Expected Calibration Error (ECE). For more details, refer to “<a href="https://towardsdatascience.com/expected-calibration-error-ece-a-step-by-step-visual-explanation-with-python-code-c3e9aa12937d">Expected Calibration Error (ECE): A Step-by-Step Visual Explanation</a>”.</figcaption></figure><p><strong>Strengths</strong>:</p><ul><li>Summarizes calibration performance in a single value.</li><li>Combines information across different probability bins.</li><li>More informative than the Brier score alone.</li></ul><p><strong>Limitations</strong>:</p><ul><li>Sensitive to the choice of binning strategy.</li><li>Can be challenging to interpret without visual aids.</li></ul><p>By understanding the strengths and limitations of each metric, you can choose the most appropriate method for assessing the calibration of your predictive models. Obviously, it is possible to combine all these metrics during an analysis of the calibration of a model to get a comprehensive understanding of its performance. This ensures that the models you develop or utilize provide reliable and accurate risk assessments, ultimately leading to better healthcare outcomes.</p><h3>III- Enhancing Model Calibration</h3><p>Proper calibration ensures that the predicted probabilities align closely with the actual outcomes, leading to more reliable and interpretable predictions. One widely used technique for this purpose is Platt Scaling.</p><p>Platt Scaling is a method that adjusts model outputs using logistic regression. This technique is particularly useful for models that initially output scores which are not interpreted as probabilities. The core idea behind Platt Scaling is to transform these model scores into probabilities that more accurately reflect the true likelihood of an outcome.</p><p>It is crucial to ensure that the data used to calibrate the model accurately represents the real distribution. Using data that does not reflect the true distribution can lead to poorly calibrated models, as the adjusted probabilities may not align with actual outcomes.</p><p>Here are the key steps involved in Platt Scaling:</p><ol><li><strong>Logistic Regression Fitting</strong>: fit a logistic regression model to the scores produced by the initial predictive model. The logistic regression model takes the form:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*8mD6AceGH4K6oZKW9U4Eog.png" /></figure><p><strong>2. Transforming Scores</strong>: use the fitted logistic regression model to transform the original scores into calibrated probabilities. This transformation ensures that the output probabilities are better aligned with the observed frequencies of the outcomes.</p><p>By applying Platt Scaling, models that initially produce non-probabilistic scores can be adjusted to provide probabilities that are more reflective of the true risks. This enhancement in calibration leads to improved predictive performance and greater trust in the model’s outputs.</p><h3>IV- Practical Implementation in Python</h3><p>In this section, we will focus on assessing and enhancing the calibration of a predictive model for classifying chest X-ray images. We use a <a href="https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia">publicly available dataset from Kaggle</a>, containing chest X-ray images labeled as NORMAL and PNEUMONIA, divided into training, validation, and test sets. The goal is to highlight the importance of model calibration in medical predictions, specifically for chest X-ray classification.</p><p>To keep the focus on the illustration of calibration techniques, we will use a pretrained convolutional neural network model “DenseNet121” and not invest significant effort in optimizing the model’s performance. The primary aim is to demonstrate key calibration metrics, including the Brier score, Expected Calibration Error (ECE), and calibration plots. Additionally, we will explore techniques to improve model calibration, with a focus on Platt Scaling.</p><p>While this article details the steps related to calibration assessment and enhancement, the full implementation, including data preprocessing, model training, and evaluation, and also function used to estimate brier, ece, plot calibration curve and apply platt method are available on my GitHub repository in the repo <a href="https://github.com/cartelgouabou/blog_notebooks/tree/main/guide_to_model_calibration">guide_to_model_calibration</a>. This allows you to follow along and understand the complete workflow from start to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEY0BNFUD9jj-T33XRJJmg.png" /><figcaption>Calibration plot for the test set, showcasing different metrics before and after applying Platt Scaling. This plot highlights the changes in model calibration, providing a visual comparison of predicted probabilities versus actual outcomes. For the complete implementation details, refer to the following link: [<a href="https://github.com/cartelgouabou/blog_notebooks/tree/main/guide_to_model_calibration">Source</a>]</figcaption></figure><p>After applying Platt Scaling to our chest X-ray classification model, we observed notable changes in calibration metrics while maintaining the same levels of overall performance. Specifically, the Area Under the Curve (AUC) and balanced accuracy remained unchanged at 0.97 and 0.87, respectively, along with specificity (0.76) and sensitivity (0.98). However, the Brier score increased from 0.09 to 0.12, and the Expected Calibration Error (ECE) decreased from 0.87 to 0.63.</p><p>The stability of AUC and balanced accuracy indicates that the discriminative ability and overall accuracy of the model were not impacted by the calibration process. This consistency suggests that the model’s ability to distinguish between classes and maintain a balance between correctly identifying both positive and negative cases is robust, irrespective of the calibration technique applied.</p><p>The increase in the Brier score from 0.09 to 0.12 might seem counterintuitive initially, as it indicates a slight decline in the mean squared error of the predicted probabilities. This shift can be understood by recognizing that the Brier score is influenced by both calibration and discrimination. Since our model’s discriminative performance remains unchanged, the slight increase in the Brier score likely reflects the trade-off involved in adjusting the probabilities to achieve better calibration as reflected by the ECE.</p><p>The most significant improvement is observed in the Expected Calibration Error (ECE), which decreased from 0.87 to 0.63. This substantial reduction highlights that Platt Scaling effectively enhanced the alignment of predicted probabilities with actual outcomes, leading to more accurate probability estimates. Lower ECE values are indicative of better-calibrated models, which means the model’s predictions are now more reliable for decision-making purposes.</p><p>In summary, while the Brier score slightly increased, the decrease in ECE demonstrates improved calibration of the model post-Platt Scaling. This trade-off emphasizes the importance of considering multiple metrics when evaluating model calibration. By improving the alignment of predicted probabilities with actual outcomes, Platt Scaling has made the model’s predictions more interpretable and trustworthy, particularly in clinical settings where precise risk estimation is crucial.</p><h3><strong>References</strong></h3><ul><li>Huang, Y., Li, W., Macheret, F., Gabriel, R. A., &amp; Ohno-Machado, L. (2020). <a href="https://doi.org/10.1093/jamia/ocz228">A tutorial on calibration measurements and calibration models for clinical prediction models</a>. <em>Journal of the American Medical Informatics Association</em>, <em>27</em>(4), 621–633.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea741be88d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Confidence Intervals in Medical Task Prediction]]></title>
            <link>https://medium.com/@cartelgouabou/understanding-confidence-intervals-in-medical-task-prediction-c7694a1d3205?source=rss-3143b6fcc395------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7694a1d3205</guid>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[confidence-interval]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[statistical-methods]]></category>
            <dc:creator><![CDATA[Arthur Cartel Foahom Gouabou]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 06:20:14 GMT</pubDate>
            <atom:updated>2024-06-24T06:43:06.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When I began my master’s internship at the Computer Science and Systems Laboratory of Aix-Marseille University in 2019, where I worked on diagnosing melanoma, I encountered the concept of confidence intervals while reading scientific articles in this field. Initially, I naively made numerous misinterpretations because I lacked a solid background in statistics. Despite its importance in medical tasks, understanding confidence intervals can be challenging for many novice data scientists. This experience inspired me to write this article to help others avoid the same pitfalls and understand how to interpret and evaluate confidence intervals correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0hIekCaB852juzTXSIGBA.png" /><figcaption>This picture perfectly illustrates the concept of confidence intervals. Each row of points represents a sample from the same normal distribution. The colored lines show the 50% confidence intervals for the mean (μ), with the sample mean indicated by a diamond. Blue intervals include the population mean, while red intervals do not. Source: <a href="https://en.wikipedia.org/wiki/Confidence_interval">Wikipedia</a></figcaption></figure><h3><strong>I- The Importance of Confidence Intervals</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWUfDquwtptbt-siyjo_1g.jpeg" /><figcaption>Caption source : <a href="https://www.churchleadership.com/leading-ideas/the-importance-of-why/">link</a></figcaption></figure><p>Imagine you have developed a chest X-ray model intended for application to thousands of patients. Testing the model on the entire population is impractical, so we use a sample to estimate its performance (the famous test set 😊). But how can we be confident that the performance of our model on the test set accurately reflects its true accuracy in the entire population?</p><p>This is where confidence intervals become invaluable. Confidence intervals provide a range derived from our sample data that likely includes the true performance metric. By presenting this range, confidence intervals allow us to express the uncertainty inherent in our estimates. This is crucial not only for data scientists but also for clinicians and other end users of the model.</p><p>For clinicians, understanding the confidence interval of a model’s performance means they can better grasp the reliability and potential variability of the model’s predictions in real-world applications. This transparency builds trust and aids in making informed decisions about the clinical implementation of the model. For instance, a clinician can appreciate that a model with an accuracy of 80% and a narrow confidence interval is more reliable than a model with the same accuracy but a wide confidence interval. This understanding can influence how they use the model in diagnosing or treating patients, ultimately impacting patient care.</p><p>Therefore, confidence intervals not only help in statistically validating the model’s performance but also play a critical role in communicating the robustness and reliability of the model to those who will use it in practice.</p><h3><strong>II- Common Misinterpretations of Confidence Intervals</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*1F_uuOXhD_vDndBXkbuIzA.jpeg" /><figcaption>Caption source : <a href="https://www.talkstaff.co.uk/avoid-common-mistakes-when-paying-employees/">link</a></figcaption></figure><p>Confidence intervals are a crucial statistical tool used to estimate population parameters based on sample data. However, several misconceptions can lead to misunderstandings of their significance and implications. Let’s debunk these misconceptions and clarify the true power of confidence intervals in medical contexts. To enhance understanding, let’s consider a predictive model developed for diagnosing a type of cancer, which achieved 80% accuracy on a test set. We’ll explore common misinterpretations that can arise from this scenario.</p><ol><li><strong>Confidence Interval Reflects the Exact Range for Population Parameter</strong></li></ol><p>One common misunderstanding is that a confidence interval provides an exact range for the population parameter. In reality, it offers a range of values within which the true population parameter is likely to lie.</p><p>Let’s take our previous practical example and suppose we calculate a 95% confidence interval of ±5% on the 80% accuracy obtained on the test set. A common misunderstanding would be to say, “The true accuracy of the model is exactly between 75% and 85%.” This suggests that the interval precisely defines the true accuracy range, which is not correct.</p><p>In reality, the correct interpretation is: “We are 95% confident that the true accuracy of our model lies between 75% and 85%.” This means that if we repeated the study multiple times with different test sets, then the fraction of those experiments for which their intervals contains the true accuracy of our model in the real world would tend towards 95%. It does not guarantee that the true accuracy falls within this specific interval for the single study but rather reflects the reliability of our estimation process over many repetitions [1].</p><p><strong>2. Limited to Means Only</strong></p><p>While commonly used for means, confidence intervals can be constructed for various statistical measures, including proportions, odds ratios, risk ratios, and correlation coefficients, making them versatile tools in medical research [2].</p><p><strong>3. Substitute for Statistical Significance Tests</strong></p><p>Confidence intervals and hypothesis tests serve different purposes. While confidence intervals estimate plausible parameter values, hypothesis tests assess whether observed data supports or contradicts a specific hypothesis. In medical research, a confidence interval may indicate the range of diagnostic accuracy, while a hypothesis test evaluates if the diagnostic performance significantly differs from chance. Confidence intervals offer more information about the magnitude and precision of the effect, which can be more informative for clinical decision-making [3].</p><p>Understanding these distinctions is crucial for interpreting study results accurately and making informed decisions in medical practice. By clarifying these misconceptions, we empower healthcare professionals and researchers to effectively leverage confidence intervals for robust statistical inference in predictive modeling and clinical applications.</p><h3><strong>III- Formula</strong></h3><p>Below is the formula for calculating a confidence interval (CI)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*euYIQAlX3W44WbeCCaaoLg.png" /></figure><h3><strong>IV- Evaluating Confidence Intervals for Medical Predictive Models: AUC and CNN Accuracy</strong></h3><p>In predictive tasks based on artificial intelligence, especially in medical prediction, metrics such as the Area Under the Curve (AUC), balanced accuracy, or simple accuracy are commonly used. However, using traditional z-score methods to evaluate confidence intervals for these metrics can be problematic for several key reasons:</p><ol><li><strong>Non-normality</strong>: The z-score method assumes that the statistic’s sampling distribution is approximately normal. For complex statistics like AUC or Convolutional Neural Network (CNN) accuracy in medical models, this assumption often does not hold, especially with smaller sample sizes. This non-normality can lead to inaccurate confidence intervals [4].</li><li><strong>Dependency Issues</strong>: Medical predictive models, particularly CNNs used for tasks like image classification or disease diagnosis, often exhibit complex dependencies between predictions. These dependencies violate the assumption of independence required for simple z-score-based intervals, further complicating their use [5].</li><li><strong>Complexity of the Statistic</strong>: AUC, for instance, is a summary measure of the entire Receiver Operating Characteristic (ROC) curve and does not follow a simple probability distribution. This complexity makes it difficult to derive an analytical confidence interval using standard methods [6].</li></ol><p>In medical prediction tasks, bootstrapping methods are effective alternatives for calculating confidence intervals. They manage the complexities of these models well and provide more reliable confidence intervals, which is particularly useful in medical research involving complex statistics and machine learning models. Bootstrapping involves iteratively resampling the data to estimate the sampling distribution empirically. This method is particularly advantageous for complex statistics such as AUC and CNN accuracy because it operates independently of the normality assumption.</p><h3><strong>V- </strong>Implementing Confidence Intervals in Python</h3><p>In this section, we present the implementation of the previously discussed approaches for estimating confidence intervals of a parameter.</p><p>Below is a Python script that defines the function calculate_confidence_interval for computing confidence intervals using the z-score method. This statistical inference technique estimates plausible population parameter values from sample data. The script computes a 95% confidence interval for parameter x based on specified sample size and confidence level, using standard error and Z-score.</p><pre># Import necessary libraries<br>import numpy as np<br>from scipy import stats<br><br># Function to calculate 95% confidence interval for a parameter x<br>def calculate_confidence_interval(x, sample_size, confidence_level=0.95):<br>    # Calculate the standard error<br>    standard_error = np.sqrt((x * (1 - x)) / sample_size)<br>    <br>    # Find the Z-score for the given confidence level<br>    z_score = stats.norm.ppf(1 - (1 - confidence_level) / 2)<br>    <br>    # Calculate the margin of error<br>    margin_of_error = z_score * standard_error<br>    <br>    # Calculate the confidence interval<br>    lower_bound = sample_accuracy - margin_of_error<br>    upper_bound = sample_accuracy + margin_of_error<br>    <br>    return lower_bound, upper_bound</pre><p>Below is a Python script that defines bootstrap_auc, which computes confidence intervals using the bootstrap method for Area Under the Curve (AUC). This method is robust for evaluating predictive models like classifiers, providing reliable estimates of AUC along with lower and upper bounds at a 95% confidence level. The script can be easily adapted to compute confidence intervals for other parameters as well, making it a versatile tool for various predictive modeling tasks.</p><pre>import numpy as np<br>from sklearn.metrics import roc_auc_score<br>from sklearn.utils import resample<br><br>def bootstrap_auc(y_test, y_pred, n_iterations=1000, confidence_level=0.95):<br>    # Store the AUCs<br>    aucs = []<br>    n_size = len(y_test)<br><br>    for _ in range(n_iterations):<br>        # Resample the data with replacement<br>        y_test_resampled, y_pred_resampled = resample(y_test, y_pred, n_samples=n_size)<br>        # Calculate the AUC<br>        auc = roc_auc_score(y_test_resampled, y_pred_resampled)<br>        aucs.append(auc)<br><br>    # Calculate the lower and upper percentiles for the confidence interval<br>    lower_bound = np.percentile(aucs, ((1 - confidence_level) / 2) * 100)<br>    upper_bound = np.percentile(aucs, (confidence_level + ((1 - confidence_level) / 2)) * 100)<br>    <br>    return lower_bound, upper_bound<br><br># Example usage:<br>y_test = np.array([0, 1, 1, 0, 1, 0, 1, 0, 1, 1])  # Replace with your actual test labels<br>y_pred = np.array([0.1, 0.9, 0.8, 0.4, 0.6, 0.2, 0.9, 0.3, 0.7, 0.85])  # Replace with your actual predicted probabilities<br><br>lower_ci, upper_ci = bootstrap_auc(y_test, y_pred)<br>print(f&quot;Bootstrap AUC 95% CI: ({lower_ci:.3f}, {upper_ci:.3f})&quot;)</pre><h3><strong>Reference</strong></h3><ol><li>Greenland, S., Senn, S. J., Rothman, K. J., Carlin, J. B., Poole, C., Goodman, S. N., &amp; Altman, D. G. (2016). Statistical tests, P values, confidence intervals, and power: a guide to misinterpretations. European Journal of Epidemiology, 31(4), 337–350</li><li>Altman, D. G., Machin, D., Bryant, T. N., &amp; Gardner, M. J. (Eds.). (2013). Statistics with confidence: confidence intervals and statistical guidelines. John Wiley &amp; Sons.</li><li>Gardner, M. J., &amp; Altman, D. G. (1986). Confidence intervals rather than P values: estimation rather than hypothesis testing. British Medical Journal, 292(6522), 746–750.</li><li>Hicks, S. A., Strümke, I., Thambawita, V., Hammou, M., Riegler, M. A., Halvorsen, P., &amp; Parasa, S. (2022). On evaluation metrics for medical applications of artificial intelligence. <em>Scientific reports</em>, <em>12</em>(1), 5979.</li><li>Yang, C. C. (2022). Explainable artificial intelligence for predictive modeling in healthcare. <em>Journal of healthcare informatics research</em>, <em>6</em>(2), 228–239.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7694a1d3205" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>