<?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 Andreas Kopp on Medium]]></title>
        <description><![CDATA[Stories by Andreas Kopp on Medium]]></description>
        <link>https://medium.com/@andreaskopp_89294?source=rss-e712cdda5a0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*njfhFnfD_jLk1elbThoy7w.jpeg</url>
            <title>Stories by Andreas Kopp on Medium</title>
            <link>https://medium.com/@andreaskopp_89294?source=rss-e712cdda5a0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:09:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreaskopp_89294/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[Beyond Prompting: Production-Ready Image Generation and Visual Asset Management on Databricks]]></title>
            <link>https://medium.com/@andreaskopp_89294/beyond-prompting-production-ready-image-generation-and-visual-asset-management-on-databricks-a1e6a1a8bf4f?source=rss-e712cdda5a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e6a1a8bf4f</guid>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[digital-asset-management]]></category>
            <category><![CDATA[gpt-image-2]]></category>
            <dc:creator><![CDATA[Andreas Kopp]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 06:47:19 GMT</pubDate>
            <atom:updated>2026-07-30T12:21:55.833Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Generative AI for images has graduated from experimental prompts to critical business workloads. Learn how to build a unified, governed engine that brings image creation, editing, analysis, and management under a single roof.</blockquote><h3>Image Generation in the Enterprise</h3><p>For agencies, creative studios, retailers, and media companies, visual assets are core to the business. Better image generation can directly improve output, speed, and revenue.</p><p>But visuals matter far beyond creative industries. Marketing teams create campaign assets, sales teams tailor customer-specific visuals, product teams explore mockups, communications teams prepare graphics, and analytics teams turn complex information into infographics. Image generation is becoming a horizontal enterprise capability, not a niche creative tool.</p><p>The challenge is that a prompt only creates an image. A business needs a production-ready asset: aligned with brand guidelines, safe to publish, available in the right format, searchable, governed, and reusable. That is why enterprise image generation needs a workflow around the image lifecycle: generation, editing, evaluation, storage, governance, and reuse.</p><p>Latest models such as OpenAI’s gpt-image-2 and Google’s Gemini 3 Pro Image make this much more practical. The step forward is not only better image quality, but greater reliability across business-critical tasks: following detailed instructions, rendering text correctly, editing existing images, and combining multiple visual elements consistently.</p><p>This makes use cases such as infographics, branded content, product compositions, localized variants, and template-based batch generation much more realistic for enterprise teams.</p><h3>Quickstart: Generating Images on Databricks</h3><p>Latest foundation models from providers such as Anthropic, OpenAI, and Google are available directly as Databricks-hosted models in your workspace. In this blog post, we use databricks-gpt-5–5 through the Responses API, enabling it to call gpt-image-2 as a tool for image generation and editing.</p><p>You can execute the following cell in a Databricks notebook to generate high-quality images.</p><pre>import base64<br>from databricks.sdk import WorkspaceClient<br><br>client = WorkspaceClient().serving_endpoints.get_open_ai_client()<br><br>prompt = &quot;An editorial magazine page about wolves in North America and how they are more harmless than we think. Make it look like a glossy, smooth, well-laid-out science magazine.&quot;<br><br>response = client.responses.create(<br>    model=&quot;databricks-gpt-5-5&quot;,<br>    input=prompt,<br>    tools=[{<br>        &quot;type&quot;: &quot;image_generation&quot;,<br>        &quot;model&quot;: &quot;gpt-image-2&quot;,<br>        &quot;size&quot;: &quot;1024x1536&quot;,<br>    }],<br>    stream=True,<br>)<br><br>image_base64 = next(<br>    chunk.item.result<br>    for chunk in response<br>    if chunk.type == &quot;response.output_item.done&quot;<br>    and chunk.item.type == &quot;image_generation_call&quot;<br>)<br><br>with open(&quot;wolves.png&quot;, &quot;wb&quot;) as f:<br>    f.write(base64.b64decode(image_base64))</pre><p>The example uses streaming because generated images are returned as base64-encoded payloads. On Databricks Model Serving, larger image responses can exceed the maximum response size. Streaming avoids this by returning the result as a sequence of events, allowing the image generation call to complete successfully.</p><p>The result shows what changes when a strong reasoning model like databricks-gpt-5–5 is paired with a modern image model such as gpt-image-2. Instead of producing only a good-looking picture, the system can infer the structure of an editorial asset, draw on relevant world knowledge, and render a coherent draft with layout, copy, and infographics from a very simple prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHuBnZexmY-FupsY98AA9g.png" /></figure><p>The image generation tool exposes several practical controls for production use:</p><ul><li>size defines the output resolution, with gpt-image-2 supporting flexible dimensions up to a maximum edge length of 3840 pixels, subject to aspect ratio and total pixel constraints.</li><li>quality controls the tradeoff between speed, cost, and fidelity</li><li>output_format can be used to select formats such as PNG, JPEG, or WebP.</li><li>For JPEG and WebP outputs, output_compression helps reduce payload size for downstream delivery.</li></ul><p>Note that gpt-image-2 does currently not support transparent backgrounds. If transparent output is required, you need to switch the image model from gpt-image-2 to gpt-image-1.5 and set background to “transparent”.</p><h3>From Prompting to Production Workflows</h3><p>Image generation becomes more valuable when it moves beyond one-off prompts into repeatable workflows. The reference architecture below shows how Databricks can support the full lifecycle: generation, editing, analysis, search, storage, governance, and reuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiaGm8CaMV50fJHx-S0RIg.png" /></figure><p>The architecture combines a <strong>Databricks App based UI</strong> with <strong>hosted foundation models</strong> such as databricks-gpt-5–5 for prompt enhancement and image generation. Generated assets are stored in <strong>Unity Catalog Volumes</strong>, while <strong>Lakebase</strong> manages metadata, lineage, analysis results, and embeddings for multimodal vector search.</p><p>For asset discovery, the architecture uses the <strong>SigLIP 2 So400m</strong> multimodal embedding model to support text-to-image and image-to-image similarity search.</p><p>Beyond single-image flows, the same architecture supports scalable production patterns: one prompt template across many input images, one source image through many prompt variations, and bulk import for existing archives. Imported and generated images are analyzed, embedded, and stored in the same governed asset library.</p><p>The analysis layer runs on every asset. databricks-gpt-5–5 returns a structured evaluation with a five-axis score covering quality, prompt adherence, purpose fit, text legibility, and content safety, plus explicit issue lists and a suggested improved prompt when needed. Configurable style-guideline templates make brand fit, on-message visuals, and campaign-specific rules measurable rather than purely manual review steps.</p><p>We are packaging this reference architecture as <strong>Databricks Vision</strong>, a sample application that is published in a <a href="https://github.com/databricks-solutions/databricks-vision">GitHub repository</a>. The repo includes a React-based frontend, but its main value is the reusable backend structure. Classes such as VisionWorkspace, ImageGen, ImageAnalyzer, ImageSearch, and ImageAdmin can be reused by enterprise developers to build or customize their own workflows.</p><h3>Databricks Vision in Action</h3><p>The examples below put Databricks Vision to work on a series of concrete tasks: enhancing prompts, generating and editing brand assets, running automated quality analysis, and searching the resulting library by text or image. Each snippet is short and self-contained, but together they trace the full lifecycle from idea to governed, searchable visual asset.</p><h3>Establish Vision Workspace Connection</h3><p>The following prerequisites are required to run the code samples below. For detailed setup instructions, see the Databricks Vision repository.</p><ul><li>A Databricks workspace with foundation models enabled. databricks-gpt-5–2 or higher is required.</li><li>A Lakebase (autoscaling Postgres) database for metadata and vector embeddings</li><li>A SigLIP embedding model (siglip-so400m-embeddings) for semantic image search deployed on a custom endpoint</li><li>A Unity Catalog Volume for storing generated images</li><li>A local Python 3.12+ environment authenticated via DATABRICKS_HOST and DATABRICKS_TOKEN</li></ul><pre>import os<br>from dotenv import load_dotenv<br>from image_gen import VisionWorkspace, ImageGen, ImageAnalyzer, ImageSearch<br><br>load_dotenv()<br><br>vw = VisionWorkspace(<br>    lakebase_project=&quot;image-gen-dbx&quot;, # autoscaling Lakebase project <br>    embedding_endpoint=&quot;siglip-so400m-embeddings&quot;,<br>)<br>gen      = ImageGen(vw, output_root=&quot;/Volumes/marketing/image_gen/blogpost&quot;)<br>analyzer = ImageAnalyzer(vw)<br>search   = ImageSearch(vw)</pre><p>Generated images are written to a Unity Catalog Volume, metadata and vector embeddings are managed in Lakebase.</p><h3>Prompt Enhancement for commercial-quality Brand Assets</h3><p>Assume the design team is exploring ideas for Databricks-branded sneakers and wants to turn a basic request into a high-quality image generation prompt:</p><pre>polished = await gen.rewrite(prompt=&quot;commercial product shot of databricks-branded sneakers&quot;)</pre><p>Prompt enhancement also supports image inputs. This is useful for image editing scenarios where the model can use both the text instruction and the reference image to create a more precise edit prompt.</p><p>A related pattern is <strong>image-to-prompt regeneration</strong>: provide an existing image and ask the model to describe it as a detailed generation prompt. The resulting text prompt can then be passed to gpt-image-2 to recreate a similar image. In our tests, this worked surprisingly well, even though the image generation model only received the extracted text prompt, not the original image.</p><p>Let’s check out the results of the suggested polished prompt for our Databricks sneakers:</p><pre>images = await gen.generate(<br>    prompt=polished,<br>    quality=&quot;high&quot;,<br>    size=&quot;1536x1024&quot;,<br>    n=4,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*BI9udG0P2KCtNvayqJ5IXw.png" /></figure><p>We can now select the strongest generation and refine it with the model’s image editing capabilities as required. Edits are guided by a text prompt that describes the desired change, such as adjusting the background, changing colors, or refining brand elements.</p><p>Accurate logo reproduction is a common requirement. While the Databricks logo is already reasonably well represented in these examples, a production workflow would typically include the original logo as an input image to improve brand accuracy in the final asset.</p><h3>Create high-quality Infographics</h3><p>Generating complex infographics has traditionally been very difficult for AI image models. They require much more than a good visual style: correct spelling, structured layouts, aligned panels, meaningful icons, labels, arrows, and a clear visual hierarchy. To get reliable results, prompts often need to describe the full information architecture, including layout, wording, relationships between elements, and text wrapping.</p><p>With gpt-image-2, this use case has improved significantly. The model is better suited for text-heavy and structured visuals, with stronger image quality, improved editing performance, and more flexible image sizes. This makes it more practical for architecture diagrams, presentation slides, educational visuals, posters, and widescreen infographics.</p><p>The following examples illustrate the breadth of infographic use cases supported by gpt-image-2, from maps and architecture diagrams to trend overviews and financial visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1z4fw6uCBo5G79EFaQRLQ.png" /></figure><p>Despite the clear progress of gpt-image-2, complex infographic generation still requires iteration. Dense layouts can take longer to generate, text placement may still need refinement, and repeated visual elements are not always perfectly consistent across generations. A good practice is to work iteratively: be explicit about structure, wording, and hierarchy, then refine the result through edits. If you already have example visuals or key objects, using them as references in edit workflows can help guide the model toward a more accurate final result.</p><h3>Create a fashion/product composition using image edits</h3><p>Image editing is about more than changing a single image. With current models such as gpt-image-2, edit workflows can modify existing images, generate new compositions from one or more reference images, and support iterative multi-turn refinement.</p><p>In this example, we combine a selfie with separate clothing assets to create a catalog-style outfit visualization.</p><pre>source_images = [&quot;input/selfie.png&quot;, &quot;input/woman-shirt.png&quot;, &quot;input/woman-jeans.png&quot;, &quot;input/woman-shoes.png&quot;]<br>gen.show(source_images)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FR4WV8x2qPpJI5U065qlA.png" /><figcaption>PLACEHOLDER ONLY</figcaption></figure><pre>prompt = &quot;Create a professional catalog shot of the woman wearing the shirt, jeans and shoes. Ensure an accurate reproduction of her face and hair.&quot;<br><br>images = await gen.edit(<br>    prompt=prompt,<br>    images=input_images,<br>    quality=&quot;high&quot;,<br>    size=&quot;1024x1536&quot;,<br>    n=3,<br>)</pre><p>The model uses the input images as references and generates a new fashion image that preserves the person’s identity while composing the selected shirt, jeans, and shoes into a coherent result. This is a practical pattern for virtual fitting rooms, merchandising mockups, and rapid campaign prototyping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTxIuGMO3FKKJqSXPmhGrQ.png" /></figure><h3>Template-based batch generation</h3><p>Single-prompt workflows work for exploration, but production teams typically need to apply the same recipe across many input images, such as localizing a hero asset for multiple markets, restyling an entire product catalog, or generating variants of a campaign template. Databricks Vision supports two batch patterns: a single prompt template applied across many input images, or a single source image rendered through many prompt variations. Both reuse the same generation pipeline and write results into the same governed asset library.</p><p>In this example, we generate a Databricks AI Days event poster for every tour city. The input Volume holds one skyline photo per city, and the AI Days logo is passed as a reference image so branding stays consistent across the run.</p><pre>batch = await gen.batch(<br>    input_volume_path=&quot;/Volumes/marketing/image_gen/ai_days/cities&quot;,<br>    prompt_template=(<br>        &quot;Databricks AI Days event poster for {image_name}. &quot;<br>        &quot;Use the city skyline as the hero background, overlay the Databricks AI Days logo.&quot;<br>    ),<br>    reference_image_path=&quot;/Volumes/marketing/image_gen/ai_days/dbx-ai-days-logo.png&quot;,<br>    size=&quot;1024x1536&quot;,<br>    quality=&quot;high&quot;,<br>)</pre><p>The {image_name} placeholder resolves to each city in turn (london, paris, barcelona, and so on), and the reference logo keeps brand elements consistent across the run. Each output is written to the same Volume, with metadata, lineage, and prompt history synced to Lakebase. Behind the scenes, the call triggers a Databricks Job that uses ai_query against the image generation endpoint, with Spark partitions sized to the endpoint’s provisioned concurrency. A batch of 500 images runs as fast as the endpoint allows, with no custom retry or fan-out code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga7OsJlHCvGnTmpCzo2HmA.png" /></figure><p>Databricks Vision also supports the inverse pattern, where a single source image is rendered through a list of labelled prompt variations. This is useful for exploring formats, audiences, or messaging around one hero asset without rebuilding it from scratch each time.</p><h3>Analyze generated Images</h3><p>A generated image is not automatically a production-ready asset. At enterprise scale, it needs supporting metadata, quality signals, and governance checks before it can be stored, reused, or shared. This includes descriptions and tags for search and organization, moderation and safety signals for responsible use, brand checks for commercial consistency, and refinement suggestions when the output does not fully match the intended result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xeaZvPYnlYpusYdH9LFZDw.png" /></figure><p>We derive this analysis from a call to databricks-gpt-5–5 through the Responses API. The model receives the original prompt, the generated image, and optional brand or purpose context, then returns a JSON object validated against a Pydantic schema.</p><p>The response includes a short factual description, metadata tags, a critical evaluation, separate lists for missing prompt elements, safety flags, and brand conflicts, plus a five-axis score from 0 to 5 across quality, fidelity, fit, legibility, and safety. If the output has a clear issue, the model also suggests a revised prompt to address it.</p><p>The description and tags feed the search index. Safety and brand fields support moderation gates. The revised prompt closes the loop into the next generation. With one model call per image and one row in Lakebase, each asset becomes ready to govern, search, and reuse.</p><h3>Semantic Image Search</h3><p>Finding the right visual asset in a large archive can be time-consuming. Metadata can help with filtering and navigation, but it is often not descriptive enough to find an image that matches a specific scene, mood, or composition.</p><p>With the deployed multimodal embedding model, we can perform semantic image search across text and image modalities. Users can describe the scene they are looking for in natural language, or provide an input image to find visually or semantically similar assets.</p><p>The following examples demonstrate text-to-image search using descriptive and abstract search queries.</p><pre>query = &quot;indian woman painting the wall orange with her daughter watching&quot;<br>results = search.text(query, k=4)<br>gen.show(results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1PGWU6el5AkhMXrtYdlbg.png" /></figure><p>Results are ordered by semantic similarity. The highest-ranked match captures all key aspects of the query. The remaining results still share some semantic similarity, but relevance decreases gradually: first the daughter is missing, then the task changes from painting a wall to painting on a canvas, and finally the results match only the broader theme of a woman painting.</p><p>More abstract queries, such as “animal parental care” or “female model looking pensive, introverted”, show how semantic search can retrieve accurate matches when the query describes a concept, mood, or relationship rather than concrete objects. These results are based only on image and text embeddings, without using metadata or file names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlA_rY_lZKH2NIVffeuAwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zD6BqLmebnax6KANFG_twg.png" /></figure><p>The same approach also supports image-to-image search. Instead of describing the target asset in text, users can provide a reference image and retrieve assets with similar visual or semantic characteristics. Let’s try this with one of the generated Databricks-branded sneakers.</p><pre>query = &quot;output/databricks_sneakers_001.png&quot;<br>results = search.image(query, k=3)<br>gen.show(results, query=query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mps7_jLsMfwRv2aRs_N_5Q.png" /></figure><blockquote>On Databricks, that workflow can stay surprisingly compact. gpt-image-2 and databricks-gpt-5–5 handle generation, editing, and reasoning. Unity Catalog Volumes provide governed storage for image assets. Lakebase stores metadata and embeddings. A SigLIP-2-So400m endpoint enables multimodal search.</blockquote><blockquote>Together, these components form a practical image generation and asset management stack without requiring a separate vector store, metadata service, or custom integration layer.</blockquote><blockquote>Clone the Databricks Vision repo, point the core classes at your own Unity Catalog Volume and Lakebase project, and you have a starting point for a branded campaign asset pipeline, an infographic batch tool, or a searchable internal image library. Start with the workflow your team needs first, then extend it from there.</blockquote><h3>Resources</h3><ul><li><a href="https://github.com/databricks-solutions/databricks-vision">Databricks Vision public repo</a></li><li><a href="https://docs.databricks.com/aws/en/machine-learning/foundation-model-apis/supported-models">Databricks-hosted foundation models</a></li><li><a href="https://docs.databricks.com/aws/en/oltp/projects">Lakebase Autoscaling</a></li><li><a href="https://docs.databricks.com/aws/en/machine-learning/model-serving/create-manage-serving-endpoints">Databricks custom model serving endpoint</a></li><li><a href="https://developers.openai.com/api/docs/guides/image-generation">OpenAI image generation guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e6a1a8bf4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multimodal 3D Brain Tumor Segmentation with Azure ML and MONAI]]></title>
            <link>https://medium.com/data-science/multimodal-3d-brain-tumor-segmentation-with-azure-ml-and-monai-4a721e42f5f7?source=rss-e712cdda5a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a721e42f5f7</guid>
            <category><![CDATA[azure-machine-learning]]></category>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Andreas Kopp]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 23:03:57 GMT</pubDate>
            <atom:updated>2023-03-21T23:03:57.961Z</atom:updated>
            <content:encoded><![CDATA[<h4>Running the medical imaging framework at scale on an enterprise ML platform</h4><p>By <a href="https://www.linkedin.com/in/harmke-alkemade/">Harmke Alkemade</a> and <a href="https://www.linkedin.com/in/andreas-kopp-1947183/">Andreas Kopp</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vHRz2_F0wx3ZKmxojH_kQg.jpeg" /><figcaption>3D Brain Tumor Segmentation (<em>Image via Shutterstock under license to Andreas Kopp)</em></figcaption></figure><p>We like to thank Brad Genereaux, Prerna Dogra, Kristopher Kersten, Ahmed Harouni, and Wenqi Li from NVIDIA and the MONAI team for their active support in the development of this asset.</p><p>Since December 2021, we have released several examples to support <a href="https://github.com/Azure/medical-imaging">Medical Imaging with Azure Machine Learning</a>, and the response we received was overwhelming. The interest and inquiries reinforce how AI is quickly becoming a crucial aspect of modern medical practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkBI75Phc-tpHC9H9IRdUA.png" /><figcaption>Selected Medical Imaging Repository Use Cases (<em>Images 5,6 via Shutterstock under license to Andreas Kopp)</em></figcaption></figure><h4>3D Brain tumor segmentation use case</h4><p>Today, we introduce a new medical imaging asset for <a href="https://github.com/Azure/medical-imaging/tree/main/3d-brain-tumor-segmentation">3D brain tumor segmentation</a>, a solution that tackles a challenging use case in the field of oncology. Our solution leverages volumetric visual input from multiple MRI modalities and different 3D glioma tumor segmentations to produce accurate predictions of tumor boundaries and sub-regions. To handle the high amount of image data involved in this task, our asset employs parallel training using scalable GPU resources on Azure ML. Furthermore, we leverage the Medical Open Network for Artificial Intelligence (MONAI), a domain-specific framework that provides state-of-the-art tools and methods for medical image analysis.</p><p>Combining Azure Machine Learning and MONAI provides valuable synergies for scalable ML development and operations with specific innovations for medical imaging:</p><p><a href="https://azure.microsoft.com/en-us/products/machine-learning"><strong>Azure Machine Learning</strong></a> is a cloud-based platform that provides a collaborative environment for data scientists and ML engineers to develop and deploy machine learning models at scale. It offers a range of authoring options, from no-code/low-code Automated ML to code-first using popular tools like VSCode. Users have access to scalable compute resources for training and deployment, making it ideal for handling large datasets and complex models. Additionally, it includes MLOps capabilities that enable the management and maintenance and versioning of ML assets, and allows for automated training and deployment pipelines. The platform includes responsible AI tools that can help explain models and mitigate potential bias, making it an ideal choice for businesses looking to develop and deploy ethical AI solutions.</p><p><a href="https://monai.io/"><strong>The Medical Open Network for Artificial Intelligence (MONAI)</strong></a> is an open-source PyTorch-based project designed for medical imaging. It provides a comprehensive set of tools for building and deploying AI models for healthcare imaging:</p><ul><li><strong>MONAI Label</strong> for AI-assisted labeling medical imaging data</li><li><strong>MONAI Core</strong> for training AI models with domain-specific capabilities</li><li><strong>MONAI Deploy</strong> for packaging, testing, and deploying medical AI applications.</li></ul><p>MONAI Core is the focus of the solution described in this article. It offers native support for commonly used medical imaging formats such as Nifty and DICOM. It also includes features such as dictionary transforms that ensure consistency between images and segmentations in complex transformation pipelines. Moreover, MONAI Core provides a portfolio of network architectures, including state-of-the-art transformer-based 3D segmentation algorithms like UNETR.</p><p>Feel free to explore our demo and use it as a template for your own 3D segmentation use cases in (or beyond) medical domains.</p><p>We are using the 2021 version of the <a href="http://braintumorsegmentation.org/">Brain Tumor Segmentation (BraTS) Challenge</a> dataset. It is a collection of expert-annotated multimodal 3D magnetic resonance imaging (MRI) scans of brain tumors from different institutions. MRI is a medical imaging technique that uses a combination of magnetic fields and radio waves to visualize the internal structures of the body. Different MRI modalities can be generated by altering the imaging parameters, which results in varying tissue contrasts, making certain features more prominent in the images. The BraTS dataset uses the following modalities:</p><ol><li>Native T1 (<strong>T1</strong>): Can be used to differentiate between various tissue types and pathological conditions. T1 native is often used to extract quantitative information about tissue properties.</li><li>T1-weighted with contrast agent Gadolinium (<strong>T1Gd</strong>): This modality can be used for delineating tumor boundaries and identifying areas of active tumor growth.</li><li>T2-weighted (<strong>T2</strong>): These images are useful for detecting edema (fluid accumulation), inflammation, and other changes in brain tissue that may be associated with tumors.</li><li>T2-weighted Fluid-Attenuated Inversion Recovery (<strong>T2-FLAIR</strong>): T2-FLAIR images are useful for identifying infiltrative tumor margins and non-enhancing tumor components.</li></ol><p>The following illustration provides an example of the expert-annotated tumor segmentations available with the BraTS dataset: Tumor core, whole tumor, and enhancing structure. The image in the upper left corner combines the three segmentations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qi56i5tfAeN7mTpJ29Nh1A.png" /><figcaption>Brain tumor segmentations derived from the BraTS 2021 dataset (image by the authors)</figcaption></figure><p>Being able to distinguish between these structures is critical for diagnosis, prognosis, and treatment planning. In the BraTS dataset, the whole tumor refers to the complete volume of the tumor, including the core and any surrounding edema or swelling. The core is the region within the tumor that contains the most aggressive cancer cells, known as the necrotic and active tumor. The enhancing structure refers to the region of the tumor that appears bright and enhances with contrast on MRI scans. This region is associated with the most active and invasive cancer cells.</p><h4>Bringing it to action</h4><p>Now, that we have gained an overview about the use case, let’s see how we are using Azure Machine Learning and MONAI to train and deploy a machine learning model for this interesting task.</p><p>The end-to-end workflow of this use case is implemented in our <a href="https://github.com/Azure/medical-imaging/blob/main/3d-brain-tumor-segmentation/3d-brain-tumor-seg-BRATS2021.ipynb">orchestration notebook</a>. These are the main steps and their associated outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlGEiJirxW_cEy1mBNrlcQ.png" /><figcaption>Brain tumor segmentation workflow and outputs (image by the authors)</figcaption></figure><p>The first steps involve downloading and visualizing the data, followed by submitting a training job to an Azure ML Compute Cluster. Once the model is trained and registered, it is deployed as an Azure ML Managed Endpoint. The notebook concludes with visualizing model predictions on an image volume from the validation set. The training and inferencing scripts are stored separately in the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKRlqiFe0LRV3sqGm41w5g.png" /><figcaption>Visualizing the tumor core in the itkwidgets 3D viewer (image by the authors)</figcaption></figure><p>To manage machine learning assets like datasets, compute resources, experiments and the resulting model in our workflow, we use the Azure ML SDK to create a connection to the Azure ML Workspace. This connection can be established from any Python environment and does not require an Azure ML Compute Instance to run the code. By managing the assets with Azure ML, they can be found in the Azure ML Studio for future reference. This facilitates easy comparison between different experiments and creates a lineage for the resulting model by referencing the associated assets (dataset version, training code, environment etc.).</p><p>The data is downloaded from Kaggle using the Kaggle API and registered as an Azure ML managed dataset. This helps with versioning the training data, which is especially helpful in an iterative model development scenario where the training data may change over time. For instance, the BraTS dataset has been updated continuously since 2012. Linking the data version to a model ensures good governance.</p><p>The <a href="https://github.com/Azure/medical-imaging/blob/main/3d-brain-tumor-segmentation/src/train-brats21.py">training script</a> uses the MONAI framework along with native PyTorch classes. The data is pre-processed using several transforms provided by the MONAI framework, mainly using the dictionary-based wrappers. The different MRI modalities of the training images are stored as separate files and there is one file for the segmentation masks. The dictionary-based wrappers enable using a single pre-processing pipeline for all training data, where every transformation in the pipeline can be specified to which part of the data it should be applied.</p><p>The following example illustrates the benefit of MONAI dictionary transforms to ensure consistency between the image and the associated segmentation labels. Imagine we use a pipeline of random transforms for data augmentation that affect the shape or position of the images (resize, flip, rotation, adjustment of perspective etc.). We have to make sure that the identical transformations are applied to the segmentation images to ensure consistency between images and labels for the downstream training process. MONAI dictionary transforms are a handy tool in this scenario: We simply need to specify if a transform should be applied to the image, the label or both. In this example, we will apply the transformations to both objects. MONAI also ensures consistency in the case of random transformations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2jWfzrLBbXgzklpl0rQPA.png" /><figcaption>Dictionary transform example for random horizontal flip (image by the authors)</figcaption></figure><p>MONAI provides a portfolio of PyTorch based network architectures. We have chosen SegResNet (a variant of the ResNet architecture adapted for segmentation tasks) for our task. It is based on an encoder-decoder framework, where the encoder extracts features from the input image and the decoder reconstructs the output segmentation mask.</p><pre># Specify SegResNet for 3D segmentation<br>segresnet = SegResNet(<br>    blocks_down=[1, 2, 2, 4],<br>    blocks_up=[1, 1, 1],<br>    init_filters=16,<br>    in_channels=4,<br>    out_channels=3,<br>    dropout_prob=0.2,<br>).to(device)<br><br># Wrap network for DDP<br>model = torch.nn.parallel.DistributedDataParallel(module=segresnet, device_ids=[local_rank])<br><br># Specify Dice loss, optimizer and LR scheduler<br>loss_function = DiceLoss(smooth_nr=0, smooth_dr=1e-5, squared_pred=True, to_onehot_y=False, sigmoid=True)<br>optimizer = torch.optim.Adam(model.parameters(), initial_lr, weight_decay=1e-5)<br>lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epochs)</pre><p>The number of encoder blocks for downsampling is specified by the blocks_down parameter. Accordingly, the upsampling blocks of the decoder part are defined with the blocks_up parameter. 16 filters are used in the first convolutional layer. The number is typically doubled as the network goes deeper, allowing it to learn more complex features. The network accepts input with 4 channels, specified by in_channels=4. This represents our multi-modal MRI data, where each channel corresponds to a different MRI modality: T1, T1Gd, T2 and T2-FLAIR. The output of the network has 3 channels, as specified by out_channels=3. This corresponds to our segmentation task classes of whole tumor, tumor core and enhancing structure.</p><p>PyTorch native features are used to include support for Distributed Data Parallel (DDP) training with multiple GPUs.</p><p>For the loss function, we leverage the Dice loss from MONAI. It is a common loss function used to measure the similarity between the predicted segmentation and the ground truth. It is particularly useful for problems with imbalanced class distributions, such as medical image segmentation, where the target region (e.g., tumor) is usually much smaller than the background.</p><p>The Adam optimizer is used in conjunction with a cosine annealing learning rate scheduler (CosineAnnealingLR). The scheduler oscillates the learning rate between an initial value and the specified minimum rate. CosineAnnealingLR can help improve model performance by allowing it to escape local minima during the initial stages of training and enabling precise adjustments in the later stages.</p><p>The training script is submitted to an Azure ML Compute Cluster via a Command Job, using the definition as follows:</p><pre>job= command(<br>    inputs= {&quot;input_data&quot;: Input(type=AssetTypes.URI_FOLDER, path= dataset_asset.path)},<br>    code= &#39;src/&#39;,<br>    command= &quot;python train-brats21.py --epochs 50 --initial_lr 0.00025 --train_batch_size 1 --val_batch_size 1 --input_data ${{inputs.input_data}} --best_model_name BRATS21&quot;,<br>    environment= &quot;monai-multigpu-azureml@latest&quot;, <br>    compute= train_target,<br>    experiment_name= experiment,<br>    display_name= f&quot;3d brain tumor segmentation based on BRATS21&quot;,<br>    description= &quot;## Brain tumor segmentation on 3D MRI brain scans&quot;,<br>    shm_size= &#39;300g&#39;,<br>    resources= dict(instance_count= 1), # cluster nodes <br>    distribution= dict(type=&quot;PyTorch&quot;, process_count_per_instance= 4), # GPUs per node<br>    environment_variables= dict(AZUREML_ARTIFACTS_DEFAULT_TIMEOUT = 1000),<br>    services= {<br>    &quot;My_jupyterlab&quot;: JobService(job_service_type=&quot;jupyter_lab&quot;),<br>    &quot;My_vscode&quot;: JobService(job_service_type=&quot;vs_code&quot;,),<br>    &quot;My_tensorboard&quot;: JobService(job_service_type=&quot;tensor_board&quot;,),<br>        })<br><br>returned_job= ml_client.create_or_update(job)</pre><p>When we submit the training job, a container is spun up in the Compute Cluster using the environment “monai-multi-gpu” that we defined earlier in the notebook. This environment is built from a conda specification file which contains the requirements for the training script. The resulting Docker image is cached in the Azure Container Registry that is linked to the Azure ML Workspace.</p><p>By using the distribution parameter, we initiate the number of processes as part of the distributed data parallel training. Since we used a machine with four GPUs for this experiment, we initiate four processes, each with access to their own GPU instance. Additionally, we can parallelize the training run over different nodes of the Compute Cluster by using the resources parameter.</p><p>Understanding GPU utilization is crucial for optimizing resource usage and preventing the dreaded Out of Memory (OOM) errors that can occur during lengthy PyTorch training runs. Azure ML offers a range of metrics to track network and disk I/O, as well as CPU and GPU memory and processor utilization for active jobs. The following example demonstrates GPU memory and energy consumption at the start of a training run on a multi-GPU cluster node of the Standard_NC24rs_v3 type. In this scenario, we can see that the 16 GB of memory available on each of the four GPUs is being effectively utilized. There is only small headroom remaining, which makes clear that increasing the batch size could heighten the risk of encountering OOM errors. Additionally, Azure ML allows us to monitor the energy consumption of each GPU, measured in kilojoules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c12UN5GgXXwZfV8THfpWLA.png" /><figcaption>Monitoring multi-GPU resource consumption during training (image by the authors)</figcaption></figure><p>Training with extensive datasets can require a significant amount of time, potentially taking several hours or even days to complete. The benefit of using a cloud-based data science and machine learning platform like Azure ML lies in the ability to access powerful resources on-demand as needed.</p><p>For our final model, we utilized NC96ads_A100_v4 cluster nodes with 96 cores, 880 GB of CPU memory, and 80 GB of memory for each of the four NVIDIA A100 GPUs to train over 150 epochs. The primary advantage of this setup is the on-demand availability of powerful resources: once training is complete, the cluster automatically shuts down, eliminating any further costs.</p><p>In our case, we opted for a “low priority” SKU, which offers a more cost-effective solution compared to dedicated compute resources. However, this choice comes with the risk of a running training job being preempted if the compute resources are required for other tasks.</p><p>While the training job is running, JupyterLab, VSCode, and Tensorboard are executed in the container, which makes it accessible for monitoring and debugging purposes. This is specified in the services parameter. We use Tensorboard and MLFlow logging in the training script to track training metrics, and MLFlow to register the final model. Both the metrics and model can be found as part of the experiment in the Azure ML Studio due to the native MLFlow support in Azure ML. By accessing the Tensorboard instance running on the container, we can review training and validation metrics while our model is trained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFEKxv7Q9rBF3N5NfQB0cw.png" /><figcaption>Monitoring training performance using interactive jobs with Tensorboard (image by the authors)</figcaption></figure><p>The Dice coefficient is used to evaluate model performance, which is a commonly used metric for object segmentation models. It measures the similarity between the predicted segmentation mask and the ground truth mask. A Dice coefficient of 1.0 indicates a perfect overlap between the predicted and the ground truth masks. Separate Dice metrics are tracked for the different classes in the dataset: Tumor core (<em>val_dice_tc</em>), whole tumor (<em>val_dice_wt</em>) and enhancing structure (<em>val_dice_et</em>). The average Dice metric across the different classes is also tracked (<em>val_mean_dice</em>). Running an experiment with 150 epochs results in the following metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIiUdGdBbgGJu2qHdl0-sg.png" /><figcaption>Validation DICE metrics during 150 epoch training in Azure ML Studio (image by the authors)</figcaption></figure><p>After registering the model, we move on to the deployment, which is a way to make the model accessible for predicting segmentation masks on new MRI images in a production setting. A possible deployment scenario for brain tumor segmentation is to integrate it with an MRI image viewer for diagnostic assistance. In the notebook, Azure ML Managed Endpoints are leveraged for deployment. First, a Managed Online Endpoint is created, which provides an interface for sending requests and receiving the inference output of a model. It also provides authentication and monitoring capabilities. Then, we create a deployment by defining the model, scoring script, environment, and target compute type. We reference the latest registered BraTS model in the Workspace for this deployment.</p><p>After sending a binary encoded version of the four modalities for a stack of MRI images to our endpoint, we receive predicted segmentations as part of the JSON response. The final part of the orchestration notebook contains code to visualize these predictions. Our image slider shows the predicted segmentations for each slice side by side with the ground truth to compare them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2D2KydFHFBrfKyR_CrGTA.png" /><figcaption>Comparing expert-annotated (ground truth) with predicted tumor structures (image by the authors)</figcaption></figure><h4>Responsible use of AI in Healthcare</h4><p>Incorporating machine learning into clinical practices, such as tumor detection and analysis, offers numerous benefits. For instance, algorithms can assist radiologists by flagging suspicious areas in the myriad of images generated daily. Another application involves the consistent monitoring of tumor progression to evaluate the effectiveness of cancer treatments. Manually calculating tumor volume from a collection of over a hundred slices per patient study can be incredibly time-consuming, but AI-assisted measurements can significantly expedite the process.</p><p>Despite the substantial advancements in AI-assisted image analysis, errors can still occur. Undetected tumors pose a considerable concern, and rare tumors or underrepresented patient characteristics in the training data can contribute to such false negatives. Consequently, it is crucial to address these limitations by incorporating diverse datasets and continuously refining the algorithms.</p><p>Physicians must continue to hold responsibility for diagnoses and treatment decisions. Machine learning predictions should be viewed as valuable and supportive tools, but not as infallible replacements for human expertise. The physician remains at the forefront of the entire process, ensuring that patient care is informed by both technology and professional judgment.</p><h4>Conclusion</h4><p>In this article, we explored the use of Azure Machine Learning and MONAI for 3D brain tumor segmentation, a challenging use case in the field of oncology. We discussed the various modalities of MRI images and the importance of distinguishing between tumor core, whole tumor, and enhancing structure for diagnosis, prognosis, and treatment planning. We also outlined the end-to-end workflow of this use case, including data visualization, training and registration of the model, deployment, and visualization of model predictions. The use of Azure Machine Learning and MONAI allowed us to employ parallel training using scalable GPU resources and provided domain-specific capabilities for training AI models for healthcare imaging.</p><p>We hope that <a href="https://github.com/Azure/medical-imaging/tree/main/3d-brain-tumor-segmentation">our asset</a> can serve as a template for future 3D segmentation use cases in medical domains and contribute to the growing importance of AI in modern medical practice.</p><p>The training code of this asset is based on an earlier version of the <a href="https://github.com/Project-MONAI/tutorials/blob/main/3d_segmentation/swin_unetr_brats21_segmentation_3d.ipynb">MONAI tutorial for 3D Brain Tumor Segmentation</a>.</p><h4>References</h4><p>[1]: Hatamizadeh, A., Nath, V., Tang, Y., Yang, D., Roth, H. and Xu, D., 2022. Swin UNETR: Swin Transformers for Semantic Segmentation of Brain Tumors in MRI Images. arXiv preprint arXiv:2201.01266.</p><p>[2]: Tang, Y., Yang, D., Li, W., Roth, H.R., Landman, B., Xu, D., Nath, V. and Hatamizadeh, A., 2022. Self-supervised pre-training of swin transformers for 3d medical image analysis. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 20730–20740).</p><p>[3] U.Baid, et al., The RSNA-ASNR-MICCAI BraTS 2021 Benchmark on Brain Tumor Segmentation and Radiogenomic Classification, arXiv:2107.02314, 2021.</p><p>[4] B. H. Menze, A. Jakab, S. Bauer, J. Kalpathy-Cramer, K. Farahani, J. Kirby, et al. “The Multimodal Brain Tumor Image Segmentation Benchmark (BRATS)”, IEEE Transactions on Medical Imaging 34(10), 1993–2024 (2015) DOI: 10.1109/TMI.2014.2377694</p><p>[5] S. Bakas, H. Akbari, A. Sotiras, M. Bilello, M. Rozycki, J.S. Kirby, et al., “Advancing The Cancer Genome Atlas glioma MRI collections with expert segmentation labels and radiomic features”, Nature Scientific Data, 4:170117 (2017) DOI: 10.1038/sdata.2017.117</p><p>[6] S. Bakas, H. Akbari, A. Sotiras, M. Bilello, M. Rozycki, J. Kirby, et al., “Segmentation Labels and Radiomic Features for the Pre-operative Scans of the TCGA-GBM collection”, The Cancer Imaging Archive, 2017. DOI: 10.7937/K9/TCIA.2017.KLXWJJ1Q</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a721e42f5f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/multimodal-3d-brain-tumor-segmentation-with-azure-ml-and-monai-4a721e42f5f7">Multimodal 3D Brain Tumor Segmentation with Azure ML and MONAI</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Federated Learning with Azure Machine Learning]]></title>
            <link>https://medium.com/data-science/practical-federated-learning-with-azure-machine-learning-8807f9bd1a7e?source=rss-e712cdda5a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8807f9bd1a7e</guid>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[azure-machine-learning]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[data-privacy]]></category>
            <dc:creator><![CDATA[Andreas Kopp]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 05:29:32 GMT</pubDate>
            <atom:updated>2022-08-29T08:28:48.704Z</atom:updated>
            <content:encoded><![CDATA[<h4>Collaborative Machine Learning without Sharing Data</h4><p>By <a href="https://www.linkedin.com/in/harmke-alkemade/">Harmke Alkemade</a> and <a href="https://www.linkedin.com/in/andreas-kopp-1947183/">Andreas Kopp</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*RXDkT8wFyWKHZiZAGnnBGw.png" /><figcaption>Federated Learning on medical images (source: Shutterstock)</figcaption></figure><p>In December 2021 we published several assets to support <a href="https://towardsdatascience.com/medical-imaging-with-azure-machine-learning-b5acfd772dd5">Medical Imaging with Azure Machine Learning</a>. The great interest and numerous inquiries have surprised us very much. It once again makes clear that AI applications are becoming increasingly important in medical practice.</p><p>With Federated Learning, we are today introducing an exciting new addition to our portfolio, which has great significance inside and outside healthcare to protect data and intellectual property.</p><p>The following illustration provides an overview of our demo use cases including our latest addition of Federated Learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RzjNNlFgorIGaGMLXu5Dw.png" /><figcaption>Medical Imaging Repository Use Cases</figcaption></figure><p>In the demo scenario, you can build a global Federated Learning scenario with simulated participating hospitals in the United States, Europe, and Asia to develop a common ML model for detecting pneumonia in X-ray images. In this article, we describe the conceptual basis of Federated Learning and walk through the key elements of the demo.</p><p>Check out the <a href="https://github.com/Azure/medical-imaging">repository</a> to try out this use case or the other scenarios and adapt them for your own business scenarios.</p><h3>The Federated Learning Concept</h3><p>Critical success factors for generalizable deep learning models are the availability of extensive and heterogeneous training data. A reliable cancer detection model should be trained based on thousands of medical images showing healthy tissue and tumors in contrast. This should also represent the real-world range of gender, age, and other demographic properties of patients. In addition, visual features resulting from the different imaging techniques should be represented. The required variety of representation simply cannot be covered by a single institution. This is especially true in the case of rare diseases, where only a few data points are available in one organization.</p><p>Consequently, a collaborative ML development in which many diverse hospitals contribute their own data is obvious. Unfortunately, this often fails in practice due to data protection concerns, as patient data is regulated by strict data protection laws in most countries (for good reasons).</p><p>Federated Learning addresses this issue by allowing multiple parties to collaboratively train a machine learning model without the need of sharing data as the following illustration shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzfT6phqpguGKasqjoKJ5g.png" /><figcaption>The Federated Learning Concept</figcaption></figure><p>While peer-to-peer topologies are possible with Federated Learning, most implementations use a central server for model parameter aggregation and orchestration of the process.</p><p>The key characteristic of Federated Learning is that the local data of the participants is never shared. Each client regularly receives a copy of the global model and performs local training with local data. The only information that is shared are the “insights” gained from training, namely the model parameter updates. One task of the server is to aggregate the weights of all participating clients into a new model version. The updated model is then redistributed to the clients to initiate the next federated training round. This process is repeated until model convergence is achieved. It can also be used for continuous training by utilizing new data points that are acquired by the participating clients in the production phase.</p><p>The following diagram illustrates the workflow of a single training round for the server-based model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npH4HZ8Nzrv4vkCqmLsmxg.png" /><figcaption>Federated Learning Workflow</figcaption></figure><p>Let’s look at some key considerations along the steps of model distribution, local training, weight aggregation, and model update.</p><p>Among the first Federated Learning applications were smart keyboard scenarios for sentence completion with millions of participating smartphones (“cross device”). In contrast, Federated Learning scenarios between organizations (“cross-silo”) have different characteristics and requirements. Often, they involve a moderate number of participants like tens of hospitals. Typically, there are strict requirements related to security, privacy, and compliance. Federated Learning provides control options for such organizational use cases. One of them is to be able to define which clients are allowed to participate and to receive copies of the global model.</p><p>A big advantage of the cross-silo approach is that participants have an IT infrastructure and can utilize powerful GPU resources to support the large models that are common in medical imaging or other deep learning use cases. Our demo shows the on-demand use of Azure CPU or GPU computational resources for Federated Learning.</p><p>Clear agreements on data annotation standards are key requirements of the multiparty training setting, in particular for advanced tasks like image segmentation. Systematic deviations in labeling practices or quality may negatively affect the resulting model. In addition, in the Federated Learning concept there is no central quality assurance about data or annotation because data is not shared.</p><p>As Federated Learning gains more traction in enterprise scenarios, weight aggregation approaches become more sophisticated to address corporate requirements. An intuitive aggregation method is called Federated Aggregation: Each parameter is weighted by the number of local data points. For example, if hospital A’s update is based on 100 images and hospital B was trained on 200 images, then hospital B’s contribution would be twice as high as hospital A. Several variations of federated aggregation exist to improve convergence given deviating distributions or to improve privacy and security. An essential extension is Secure Aggregation, which protects communication against man in the middle attacks and prevents the server from accessing updates from individual clients in clear text. It is based on a cryptographic protocol that ensures that a client’s contribution looks like random noise unless combined in aggregate with the other clients‘ contributions.</p><p>For an end-to-end privacy-preserving solution, we also need to look at the resulting model. Today’s large deep learning models tend to memorize individual data points. For example, researchers have shown that it is possible to reconstruct a recognizable image of a person’s face from a trained face detection classification model. The risk of such <strong>model inversion attacks</strong> is not reduced with Federated Learning as it protects the input data, <strong>but not the resulting model</strong>. Therefore, Federated Learning is often combined with Differential Privacy to protect the resulting model by adding a defined amount of statistical noise during the training process. This reduces the risk of reconstructing individual data points or linkage attacks substantially. Check out the <a href="https://github.com/Azure/medical-imaging/blob/main/notebooks/5-diff-privacy-pneumonia-detection.ipynb">Differential Privacy demo</a> of our repository if you want to learn more about the concept.</p><h3>Demo Architecture</h3><p>The demo in the medical imaging repository comprises a federated learning scenario where multiple hospitals train a central model using their own private datasets. The approach uses a central server for aggregation, which means that the server sends out instructions to the different hospitals and collects the model weights after the local training run is finished. After aggregation on the central server, the updated model is sent to the hospitals, to serve as a starting point for the next round.</p><p>In terms of architecture, the full set-up is implemented using Azure components. The hospitals are represented by Machine Learning workspaces, deployed in different regions to create a global set-up. The Federated Server is implemented using an Azure Data Science Virtual Machine. For configuration and orchestration, the NVIDIA Flare package is used.</p><p>The model is trained on a public Kaggle dataset containing x-ray images of patients with and without pneumonia¹. Using this dataset, a binary classification model is trained to classify x-ray images in the categories ‘pneumonia’ or ‘normal’.</p><h3>Putting It in Action</h3><p>Check out our <a href="https://github.com/Azure/medical-imaging/tree/main/federated-learning">step-by-step guide</a> if you like to recreate the demo setup on your own. To make it easy to deploy the solution, there are some GitHub Action Workflows provided to prepare the environment for running the experiments.</p><p>One of the workflows available in the repository creates the Azure resources, mainly a Data Science Virtual Machine with specific configurations and three different Azure Machine Learning Workspaces. There is also a Compute Instance created for every workspace. The Compute Instances will be running client packages generated by NVIDIA Flare. Client packages are used to initiate communication with the server and admin client, which will be running on the Data Science Virtual Machine.</p><p>There is also a workflow provided that downloads the pneumonia dataset from Kaggle and resamples it. After resampling, the data is split into three different parts to create private datasets for the different clients. The last step of the preparation phase is to use the Azure ML CLI to upload and register the private datasets as data assets to the different workspaces. Using this approach, we can consume the training data in the training script that is run on the different clients.</p><p>After setting up the infrastructure, we can initiate the packages that will be uploaded to clients and server. To generate them, we login to the virtual machine using, for example by establishing an SSH connection via a local terminal. Then we clone the Medical Imaging repository on the VM.</p><p>The federatedlearning-folder in the repository contains a file called <em>project.yml</em>. This file contains the settings for the server, clients and more configuration options for the federated setup. For more details, see <a href="https://nvflare.readthedocs.io/en/main/programming_guide/provisioning_system.html#project-yaml-file">this page</a>.</p><p>The NVFlare provisioning tool can be run with the following command:</p><pre>provision -p project.yml</pre><p>This will generate a startup kit for each participant that are created by default in a directory prefixed with “prod_” within a folder of the project name in the workspace folder where the provisioning command is run. The client packages are copied to the different machine learning workspaces that are created. Both the server and admin package stay on the federated server but are moved to the home directory of the VM.</p><h3>Run the Experiment</h3><p>The experiments can be controlled using the admin client. The client and server package can run on the same Virtual Machine. To initiate connections between server and clients, start by running the start command on the server VM. We do this by navigating to the startup folder in the server startup kit and running <em>bash start.sh</em>.</p><p>When the server is started, the start scripts on the clients can be run. This should lead to a successful connection between the server and the client. In the terminal of the server, the output should look like the output below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*earvjS-4Xpe4UeF2q1iD9A.png" /></figure><p>After running the start up scripts for the three different clients, we can verify using the admin client whether the connection succeeded. For this, we open another terminal, and run the startup script in the admin folder. Sign in by using <a href="/service/mailto:admin@nvidia.com">admin@nvidia.com</a> as username.</p><p>By typing ‘?’, the different commands of the admin client are listed. Some of them are relevant during the training cycle, like ‘deploy app’ and ‘start app’. Other commands are mostly focused on the IT management part of the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*DLDAvt2QkESD1kr4Wlbryw.png" /></figure><p>By running the check_status command, we can verify if our three clients are successfully connected to the federated server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*Vth0a3CIQm-fHpBBYw0VqQ.png" /></figure><p>After connecting the clients to the server, the experiment can be initiated.</p><p>The repository contains two <em>applications</em> as we call them in NVFlare, that can be used to run experiments. Both are using the same model architecture and training logic. The main difference is that one of the applications trains a federated model, and the other a central one. This allows us to do experiments where the performance of a centralized versus a federated run are compared.</p><p>To prepare our run, we need to set the run number for all the clients and run the check_client command afterwards to verify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*vNkvenIXyt7B7SVfv9yP_Q.png" /></figure><p>The next command we need to run is <em>upload_app pneumonia-federated</em>. This will upload our app to the transfer folder of the federated server, ready to be copied to the different clients.</p><p>To deploy the app to the different clients, we use the command <em>deploy_app pneumonia-federated all</em>. This will copy the training instructions to the different clients and server. If successful, the clients will return an OK-status to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*_guD2VOA-RAqPJGHWefGyQ.png" /></figure><p>The final command we need is start_app all. This initiated the training run for the different clients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*sBcZ4qqkcP4FXeYQCGhTcg.png" /></figure><p>The progress of the training run can be tracked using the terminal where the server startup script was run, or using the terminals from the separate clients.</p><p>An obvious question is how federated training compares to traditional (centralized) training. To answer that question a centralized training can be run after the federated experiment. In this experiment, the same algorithm will be trained on the full pneumonia dataset, but this time we are only using one client. The GitHub Actions workflow that is used to prepare the data, contains the step to register the full dataset to the Asia workspace. Therefore, we are using that client in this step.</p><p>The centralized experiment can be started by running the following command subsequently in the admin terminal:</p><pre>set_run_number 2<br>upload_app pneumonia-central<br>deploy_app pneumonia-central client FL-Asia-Hospital<br>start_app server<br>start_app client FL-Asia-Hospital</pre><h3>Review Results</h3><p>On the client side, events are being created during the training run and streamed to the server. These metrics can be found on the server in a folder with the name ‘run_&lt;run number&gt;’. In the applications that exist in our repo, the metrics are tracked in such a way, that they can be consumed using TensorBoard. Tensorboard provides interactive visualization capabilities for machine learning experiments.</p><p>To run TensorBoard on the federated server, run the following command:</p><pre>tensorboard --logdir=fedserver --bind_all</pre><p>The -bind_all parameter makes the application accessible from the outside, which is needed if you want to access the dashboard from your local machine without leveraging Remote Desktop options. From a network perspective, we also need to open the port TensorBoard is using (6006 by default).</p><p>Below is a screenshot of what our TensorBoard looks like. On the left slide, we have the option to filter different runs that we want to visualize. This is very useful for comparing performance between runs with different parameters. The values that are visualized are training loss and validation accuracy. Training loss will indicate how good the models for the different clients are able to generalize on the local dataset. Validation accuracy shows the performance of the local model on a global validation dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*mhYpjOStiA1jzV_xkpPXjg.png" /><figcaption>Federated Learning Curves in TensorBoard</figcaption></figure><p>Based on the two experiments set-ups, we can compare results between a centralized run and a federated run. What can be seen from some experiments, is that a slightly higher accuracy is achieved with a centralized run. In some cases, the same performance can be achieved using both set-ups, although it takes longer for the federated training run to converge.</p><p>The visual below shows a comparison between a centralized and federated run, where we can see that the centralized run resulted in a higher accuracy. Further experiments with other parameters (e.g., learning rate, number of epochs), should be done to draw final conclusions, which should also not be generalized across different use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*wfUikhYatzurJke8ak713A.png" /><figcaption>Convergence of Centralized and Federated Training</figcaption></figure><h3>Conclusion</h3><p>Federated Learning is a compelling concept for co-development of ML solutions where training data cannot be shared. An obvious application area is privacy-preserving ML training. Other examples like the <a href="https://www.melloddy.eu/">MELLODY project</a> for drug discovery show applications where competing companies develop a joint model without having to worry about their intellectual property being compromised.</p><p>As maturity of the concept increases, including support for secure and robust federated aggregation, it becomes more prevalent in the enterprise and public sector organizations with their specific requirements.</p><p>The combination of Azure ML and NVIDIA NVFlare enables rapid realization even for global Federated Learning deployments and provides significant benefits in terms of compliance, data protection, manageability and traceability.</p><p>An end-to-end privacy preserving solution requires the combination of Federated Learning with technologies such as Differential Privacy.</p><p><em>All images unless otherwise noted are by the authors</em>.</p><p>[1] Pneumonia dataset: Paul Mooney. 2018. Chest X-Ray Images (Pneumonia). License: <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>. Source: <a href="https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia">Chest X-Ray Images (Pneumonia) | Kaggle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8807f9bd1a7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/practical-federated-learning-with-azure-machine-learning-8807f9bd1a7e">Practical Federated Learning with Azure Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting a Grip on Data and Model Drift with Azure Machine Learning]]></title>
            <link>https://medium.com/data-science/getting-a-grip-on-data-and-model-drift-with-azure-machine-learning-ebd240176b8b?source=rss-e712cdda5a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd240176b8b</guid>
            <category><![CDATA[data-drift]]></category>
            <category><![CDATA[azure-machine-learning]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[model-drift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andreas Kopp]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 10:50:08 GMT</pubDate>
            <atom:updated>2022-11-01T10:04:54.010Z</atom:updated>
            <content:encoded><![CDATA[<h4>Detect, analyze, and mitigate data and model drift in an automated fashion</h4><p><em>By </em><a href="https://www.linkedin.com/in/natasha-savic/"><em>Natasha Savic</em></a><em> and </em><a href="https://www.linkedin.com/in/andreas-kopp-1947183/"><em>Andreas Kopp</em></a></p><p>Change is the only constant in life. In machine learning, it shows up as drift of data, model predictions, and decaying performance, if not managed carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKA2vd6Nq4eDJGyKUcA_RA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@s_midili?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">serjan midili</a> on <a href="https://unsplash.com/s/photos/drift?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, we discuss data and model drift and how it affects the performance of production models. You will learn methods to identify and to mitigate drift and MLOps best practices to transition from static models to evergreen AI services using Azure Machine Learning.</p><p>We also include a <a href="https://github.com/Azure/data-model-drift/blob/main/tabular-data/DATA_MODEL_DRIFT_INTERACTIVE.ipynb">sample notebook</a> if you want to try out the concepts in practical examples.</p><h3>Understanding data and model drift</h3><p>Many machine learning projects conclude after a phase of extensive data and feature engineering, modeling, training, and evaluation with a satisfactory model that is deployed to production. However, the longer a model is in operation, the more problems can creep in that might remain undetected for quite a long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUM87HRY4OGLMp_r8XLAdg.png" /><figcaption>Data drift and performance degradation due to model drift</figcaption></figure><p><strong>Data drift</strong> means that distributions of input data change over time. Drift can lead to a gap between what the model has initially learned from the training data and the inferencing observations during production. Let’s look at a few examples of data drift:</p><ul><li><em>Real-world changes</em>: an originally small demographic group increasingly appears in the labor market (e.g., war refugees); new regulatory frameworks come into play influencing user consent (e.g., GDPR)</li><li><em>Data acquisition problems</em>: incorrect measurements due to a broken IoT sensor; an initially mandatory input field of a web form becomes optional for privacy reasons</li><li><em>Data engineering problems</em>: unintended coding or scaling changes or swap of variables</li></ul><p><strong>Model drift</strong> is accompanied by a decrease in model performance over time (e.g., accuracy drop in a supervised classification use case). There are two main sources of model drift:</p><ul><li><em>Real-world changes</em> are also referred to as <strong>concept drift</strong>: The relationship between features and target variables has changed in the real world. Examples: the collapse of travel activities during a pandemic and; rise of inflation impacts buying behavior.</li><li><em>Data drift</em>: The described drift of input data might also affect model quality. However, not every occurrence of data drift is necessarily a problem. When drift occurs on less important features the model might respond robustly, and performance is not affected. Let us assume that a demographic cohort (a specific combination of age, gender, and income) occurs more often during inferencing than seen during training. It won’t cause headaches if the model still predicts the outcomes for this cohort correctly. It is more problematic if the drift leads the model into less populated and/or more error-prone areas of the feature space.</li></ul><p>Model drift typically stays undetected until new ground truth labels are available. The original test data is no longer a reliable benchmark because the real-world function has changed.</p><p>The following illustration summarizes the various kinds of drift:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SbcVM2s9qld86Sdo7GGbw.png" /><figcaption>Types of drift. Adopted from <a href="https://towardsdatascience.com/dont-let-your-model-s-quality-drift-away-53d2f7899c09">Data and concept drifts in machine learning | Towards Data Science</a></figcaption></figure><p>The transition from normal behavior to drift can be vastly different. Demographic changes in the real world typically lead to gradual data or model drift. However, a broken sensor might cause abrupt deviations from the normal range. Seasonal fluctuations in buying behavior (e.g., Christmas season) are manifested as a recurring drift.</p><p>If we have timestamps for our observations (or the data points are at least arranged chronologically), the following can be done to detect, analyze and mitigate drift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bykWentbmgm9wuVUWa4PQ.png" /></figure><p>We will describe these methods in more detail below and experiment with them using a predictive maintenance case study.</p><h3>From static to evergreen models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svSMAIJppWQhNMWfp8TFiA.png" /><figcaption>From static to evergreen models</figcaption></figure><p>The options to analyze and mitigate data and model drift depend on the availability of current data over the machine learning model’s lifecycle.</p><p>Let us assume that a bank collected historical data to train a model to support credit lending decisions. The goal is to predict whether a loan application should be approved or rejected. Labeled training data was collected in the period from January to December 2020.</p><p>The bank’s data scientists have spent the first quarter of 2021 training and evaluating the model and decided to bring it to production in April 2021. Let us look at three options the team can use for collecting production data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1owHn0tAssdiwEKug9ilw.png" /><figcaption>Good drift management depends on data availability</figcaption></figure><p><strong>Scenario 1: Static model</strong></p><p>Here, the team doesn’t collect any production data. Perhaps they did not consider this at all since their project scope only covered delivering the initial model. Another reason could be open data privacy questions (storing regulated personal data).</p><p>Obviously, there is not much that can be done to detect data or model drift beyond analyzing the historical training data. Drift may only be uncovered when model users start complaining about the model predictions are becoming increasingly unsuitable for business decisions. However, since feedback is not systematically collected, gradual drift will likely remain undiscovered for a long time.</p><p>Interestingly, many productive machine learning models are run in this mode today. However, machine learning lifecycle management procedures like MLOps are getting more traction in practice to address issues like these.</p><p>The static model approach might be acceptable if the model is trained on representative data and the feature/target relationship is stable over time (e.g., biological phenomena which change at an evolutionary pace).</p><p><strong>Scenario 2: Collecting production data</strong></p><p>The team decides to collect observed input data (features) from the production phase together with the corresponding model predictions.</p><p>This approach is straightforward to implement if there are no data protection concerns or other organizational hurdles. By comparing the recent production data with original training observations, drift in features and predicted labels can be found. Significant shifts in key features (in terms of feature importance) can be used as a trigger for further investigation.</p><p>However, essential information is missing to find out if there is a problem with the model: we do not have new ground truth labels to evaluate the production predictions. This might lead to the following situations:</p><ul><li>Virtual drift (false positive): We observe data drift, but the model still works as desired. This may get the team to acquire new labeled data for retraining although it is unnecessary (from a model drift perspective).</li><li>Concept drift (false negative): While there is no drift in the input data, the real-world function has moved away from what the model had learned. Hence, an increasingly outdated model leads to inaccurate business decisions.</li></ul><p><strong>Scenario 3: Evergreen model</strong></p><p>In this scenario, the bank not only analyzes production input and predictions for potential drift but also collects labeled data. Depending on the business context, this can be done in one of the following ways:</p><ul><li>Business units contribute newly labeled data points (as was done for the initial training)</li><li>Human-in-the-loop feedback: The model predictions from the production phase are systematically reviewed. Especially false approvals and false rejections, found by domain experts, and the corresponding features with the corrected labels are collected for retraining.</li></ul><p>Incorporating human-in-the-loop feedback requires adjustment of processes and systems (e.g., business users can overwrite or flag incorrect predictions in their applications).</p><p>The main advantages are that concept drift can be identified with high reliability and the model can regularly be refreshed by retraining.</p><p>Incorporating business feedback and regular retraining is an essential part of mature MLOps practices (see our reference architecture example for Azure Machine Learning below).</p><h3>Data and model drift management in practice</h3><p>It is essential to have a detection mechanism that measures drift systematically. Ideally, such a mechanism is part of an integrated MLOps workflow that compares training and inference distributions on a continuous basis. We have compiled several mechanisms that support data and model drift management.</p><p>We are using a predictive maintenance use case based on a synthetic dataset in our <a href="https://github.com/Azure/data-model-drift/blob/main/tabular-data/DATA_MODEL_DRIFT.ipynb">sample notebook</a>. The goal is to predict equipment failure based on features like speed or heat deviations, operator, assembly line, days since the last service, etc.</p><p>To identify drift, we combine statistical techniques and distribution overlaps (data drift) as well as predictive techniques (model/concept drift). For both drift types, we will briefly introduce the method used.</p><p>Drift detection starts by partitioning a dataset of chronologically sorted observations into a reference and current window. The reference (or baseline) window represents older observations and is often identical to the initial training data. The current window typically reflects more recent data points seen in the production phase. This is not a strict 1:1 mapping as it might be needed to adjust the windows to better locate when drift occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVXaycwoCgN9GyYoV_t5RA.png" /><figcaption>Partitioning the chronological dataset into reference and current windows</figcaption></figure><p>We first need to differentiate between numerical and categorical/discrete data. For the statistical tests, both types of data will undergo distinct <a href="https://en.wikipedia.org/wiki/Nonparametric_statistics">non-parametric tests</a> that provide a p-value. We are handling different sample sizes and do not make assumptions about the actual distribution of our data. Therefore, non-parametric approaches are a handy way to test the similarity of two samples without needing to know the actual probability distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fysFpJiyg6M1LN5p3t4lQ.png" /></figure><p>Those tests allow us to accept or reject the null hypothesis with a degree of confidence, as defined by the p-value. As such, you can control the sensitivity of the test by adjusting the threshold for the p-value. We recommend a more conservative p-value such as 0.01 by default. The larger your sample gets, the more prone it is to pick up on noise. Other commonly used methods to figure out the drift between distributions are the Wasserstein Distance for continuous and the JS Divergence for probability distributions.</p><p>Here are some best practices to limit the number of false alarms in drift detection:</p><ol><li>Scope the drift analyses to a shortlist of key features if you have many variables in your dataset</li><li>Use a sub-sample instead of all data points if your dataset is large</li><li>Reduce the p-value threshold further or select an alternative test for larger data volumes</li></ol><p>While statistical tests are useful to identify drift, it is <strong>hard to interpret the magnitude of the drift as well as in which direction it occurs</strong>. Given a variable like age, did the sample get older or younger and how is the age spread? To answer those questions, it is useful to visualize the distributions. For this, we add another non-parametric method: the <a href="https://mathisonian.github.io/kde/"><strong>Kernel Density Estimation (KDE)</strong></a>. Since we have two different data types, we will perform a pre-processing step on the categorical data to convert it into a pseudo-numerical notation by encoding the variables. The same ordinal encoder object is used for both the reference and the current distributions to ensure consistency:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc70acdf41cc9f6193f99f895a133642/href">https://medium.com/media/bc70acdf41cc9f6193f99f895a133642/href</a></iframe><p>Now that we have encoded our data, we can visually inspect either the entire dataset or selected variables of interest. We use the Kernel Density Estimation functions of the reference and current samples to compute their intersection in percent. The following steps were adapted from <a href="https://stackoverflow.com/questions/68927580/finding-areas-of-non-overlapping-edges-of-two-distributions">this sample</a>:</p><ol><li>Pass the data into a KDE function as in <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html">scipy.stats.gaussian_kde()</a> with the bandwidth method “scott”. The parameter determines the degree of smoothing of the distribution.</li><li>Take the range (min and max of both distributions) and compute the intersection points of both KDE functions within this range by using the differential of both functions.</li><li>Perform pre-processing for variables that have a constant value to avoid errors and align the scale of both distributions.</li><li>Approximate the area under the intersection points using the <a href="https://en.wikipedia.org/wiki/Trapezoidal_rule">composite trapezoidal rule</a> as per <a href="https://numpy.org/doc/stable/reference/generated/numpy.trapz.html">numpy.trapz()</a>.</li><li>Plot the reference and current distributions, intersection points as well as the area of intersection with the percentage of overlap.</li><li>Add the respective statistical test (KS or Chi-Square) to the title and provide a drift indication (Drift vs. No Drift)</li></ol><p>The steps can be understood in more depth by checking out the code samples. The result of the KDE intersections looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kSsccXvMzSqp2P_DHPo-w.png" /><figcaption>Comparing KDE intersections to identify data drift</figcaption></figure><p>A brief inspection of the plots tells us:</p><ol><li>Which variables have significantly different distributions between the reference and current sample?</li><li>What is the magnitude and direction of the drift?</li></ol><p>If we look at the variable “operator”, we can see that there was a substantial change in terms of which employee was operating the machine between when the model was fitted versus today. For example, it could have happened that an operator has retired and, consequently, does not operate any machines anymore (operator 2). Conversely, we see that new operators have joined who were not present before (e.g., operator 6).</p><p>Now that we have seen how to uncover drift in features and labels, let us find out if the model is affected by data or concept drift.</p><p>Similar to before, we stack the historical (training) observations and recently <em>labeled</em> data points together in a chronological dataset. Then, we compare model performance based on the most recent observations, as the following overview illustrates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6JSjeP7rmlGLQzULGQSKw.png" /><figcaption>Predictive model drift detection</figcaption></figure><p>At the core, we want to answer the question: Does a newer model perform better in predicting on most recent data than a model trained on older observations?</p><p>We probably have no idea in advance if and where drift has crept in.</p><p>Therefore, in our first attempt, we might use the original training data as reference and the inference observations as current windows. If we find the existence of drift by this, we will likely try out different reference and current windows to pinpoint where exactly drift crept in.</p><p>A couple of options exist for predictive model drift detection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xo2ZsMTCHaOUdYXpUezS4Q.png" /></figure><p>Each option has specific advantages. As a result of the first alternative, you already have a trained candidate ready for deployment if model 2 outperforms model 1. The second option will likely reduce false positives, at the expense of being less sensitive to drift. Alternative 3 reduces unnecessary training cycles in cases where no drift is identified.</p><p>Let’s check out how to use option 1 to find drift in our predictive maintenance use case. The aggregated dataset consists of 45,000 timestamped observations which we spilt into 20,000 references, 20,000 current, and 5,000 most recent observations for the test.</p><p>We define a scikit-learn pipeline to preprocess numerical and categorical features and train two LightGBM classifiers for comparison:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9654f07b0819bd154f2f412221c3966/href">https://medium.com/media/c9654f07b0819bd154f2f412221c3966/href</a></iframe><p>After repeating the last step for the current classifier, we compare the performance metrics to find out if there is a noticeable gap between the models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BonHhMDjcnPEP0L66G754w.png" /></figure><p>The current model outperforms the reference model by a large margin. Therefore, we can conclude that we indeed have identified model drift and that the current model is a promising candidate for replacing the production model. A visual way of inspection is to compare the distributions of confidence scores of both classifiers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8B34uIjKFqX0QZaqsR7SQ.png" /><figcaption>Model drift impact on predicted class probabilities (left) with KDE intersection (right)</figcaption></figure><p>The histograms on the left show a clear difference between the predicted class probabilities of the reference and current models and therefore also confirm the existence of model drift.</p><p>Finally, we reuse our KDE plots and statistical tests from the data drift section to measure the extent of the drift. The intersection between the KDE plots for both classifiers amounts to only 85%. Furthermore, the results of the KS test suggest that the distributions are not identical.</p><p>In this example, the results were to be expected because we intentionally built drift into our synthetic predictive maintenance dataset. With a real-world dataset, results won’t always be as obvious. Also, it might be necessary to try different reference and current window splits to reliably find model drift.</p><h3>MLOps reference architecture for evergreen models</h3><p>We will now focus on embedding drift detection and mitigation in an MLOps architecture with Azure Machine Learning. The following section leverages concepts such as Azure ML Datasets, Models, and Pipelines. The <a href="https://github.com/Azure/data-model-drift">demo repository</a> provides an example of an Azure ML pipeline for generating the data drift detection plots. To automate the re-training of models, we recommend using the latest Azure MLOPs code samples and documentation. The following illustration provides a sample architecture including everything we learned about data and model drift so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfJlwRfA-g9kx7r-jqngag.png" /><figcaption>MLOps architecture for evergreen models</figcaption></figure><p>By considering drift mitigation as part of an automated <a href="https://docs.microsoft.com/en-us/azure/machine-learning/concept-model-management-and-deployment">Azure MLOps</a> workflow, we can maintain evergreen ML services with manageable effort. To do so, we perform the following steps:</p><ol><li><strong>Ingest and version data in Azure Machine Learning<br></strong> This step is crucial to maintain a lineage between the training data, machine learning experiments, and the resulting models. For automation, we use Azure Machine Learning pipelines which consume managed datasets. By specifying the version parameter (version=”latest”) you can ensure to obtain the most recent data.</li><li><strong>Train model<br></strong>In this step, the model is trained on the source data. This activity can also be part of an automated Azure Machine Learning pipeline. We recommend adding a few parameters like the dataset name and version to re-use the same pipeline object across multiple dataset versions. By doing so, the same pipeline can be triggered in case model drift is present. Once the training is finished, the model is registered in the Azure Machine Learning model registry.</li><li><strong>Evaluate model</strong><br>Model evaluation is part of the training/re-training pipeline. Besides looking at performance metrics to see how good a model is, a thorough evaluation also includes reviewing explanations, checking for bias and fairness issues, looking at where the model makes mistakes, etc. It will often include human verification.</li><li><strong>Deploy model</strong><br>This is where you deploy a specific version of the model. In the case of evergreen models, we would deploy the model that was fitted to the latest dataset.</li><li><strong>Monitor model</strong><br>Collection of telemetry about the deployed model. For example, an <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics">Azure AppInsights workbook</a> can be used to collect the number of requests made to the model instance as well as service availability and other user-defined metrics.</li><li><strong>Collect inference data and labels</strong><br>As part of a continuous improvement of the service, all the inferences that are made by the model should be saved into a repository (e.g., Azure Data Lake) alongside the ground truth (if available). This is a crucial step as it allows us to figure out the amount of drift between the inference and the reference data. Should the ground truth labels not be available, we can monitor data drift but not model drift.</li><li><strong>Measure data drift</strong><br>Based on the previous step, we can kick off the data drift detection by using the reference data and contrasting it against the current data using the methods introduced in the sections above.</li><li><strong>Measure model drift</strong><br>In this step, we determine if the model is affected by data or concept drift. This is done using one of the methods introduced above.</li><li><strong>Trigger re-training</strong><br>In case of model or concept drift, we can trigger a full re-training and deployment pipeline utilizing the same Azure ML pipeline we used for the initial training. This is the last step that closes the loop between a static and an evergreen model. The re-training triggers can either be:<br><strong>Automatic</strong> — Comparing performance between the reference model and current model and automatically deploying if the current model performance is better than the reference model.<br><strong>Human in the loop</strong> — Inspect data drift visualization alongside performance metrics between reference and current model and deploy with a data scientist/ model owner in the loop. This scenario would be suitable for highly regulated industries. This can be done using PowerApps, Azure DevOps pipelines, or GitHub Actions.</li></ol><h3>Next steps</h3><p>In this article, we have looked at practical concepts to find and mitigate the drift of data and machine learning models for tabular use cases. We have seen these concepts in action using our demo notebook with the predictive maintenance example. We encourage you to adapt these methods to your own use cases and appreciate any feedback.</p><p>Being able to systematically identify and manage the drift of production models is a big step toward mature MLOps practices. Therefore, we recommend integrating these concepts into an end-to-end production solution like the MLOps reference architecture introduced above. The last part of <a href="https://github.com/Azure/data-model-drift/blob/main/tabular-data/DATA_MODEL_DRIFT.ipynb">our notebook</a> includes examples of how to implement drift detection using automated Azure Machine Learning Pipelines.</p><p>Data and model drift management is only one building block of a holistic MLOps vision and architecture. Feel free to check out the <a href="https://docs.microsoft.com/en-us/azure/machine-learning/concept-model-management-and-deployment">documentation</a> for general information about MLOps and how to implement it using Azure Machine Learning.</p><p>In our examples, we have looked at tabular machine learning use cases. Drift mitigation approaches for unstructured data like images and natural language are also emerging. The <a href="https://github.com/microsoft/MedImaging-ModelDriftMonitoring">Drift Detection in Medical Imaging AI repository</a> provides a promising method of analyzing medical images in conjunction with metadata to detect model drift.</p><p><em>All images unless otherwise noted are by the authors</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd240176b8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/getting-a-grip-on-data-and-model-drift-with-azure-machine-learning-ebd240176b8b">Getting a Grip on Data and Model Drift with Azure Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>