<?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 Serge Retkowsky on Medium]]></title>
        <description><![CDATA[Stories by Serge Retkowsky on Medium]]></description>
        <link>https://medium.com/@sergems18?source=rss-d92e84d8be4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UUnJP28j19aTFBT3HmZSSw@2x.jpeg</url>
            <title>Stories by Serge Retkowsky on Medium</title>
            <link>https://medium.com/@sergems18?source=rss-d92e84d8be4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:28:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergems18/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[An introduction to Foundry Local]]></title>
            <link>https://medium.com/@sergems18/an-introduction-to-foundry-local-cc841d9d4fbe?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc841d9d4fbe</guid>
            <category><![CDATA[foundry-local]]></category>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[edge-ai]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 08:54:43 GMT</pubDate>
            <atom:updated>2026-03-02T08:54:43.299Z</atom:updated>
            <content:encoded><![CDATA[<p>Foundry Local is an on-device AI inference solution that lets you run AI models locally through a CLI, SDK, or REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P7E-HGZkOkVvM1Ej.jpg" /><figcaption>Foundry Local</figcaption></figure><h3>Introduction</h3><p>The AI industry has been dominated by cloud-based inference for years, but a growing number of developers, enterprises, and researchers need an alternative. Whether driven by data privacy regulations, latency constraints, unreliable connectivity, or simply the desire to reduce recurring cloud costs, on-device AI inference is becoming a first-class requirement.</p><p><strong>Microsoft Foundry Local</strong> answers this need. It is an on-device AI inference platform that lets you run modern generative AI models directly on your local hardware — Windows PCs, macOS (Apple Silicon), or servers — without ever sending a single prompt to the cloud. All processing happens entirely on your machine.</p><p>In this article, I will walk you through what Foundry Local is, how its architecture works under the hood, and present a collection of <strong>six Jupyter Notebook tutorials</strong> I created to help you get started quickly and explore advanced capabilities. All notebooks are available on GitHub at:</p><blockquote><a href="https://github.com/retkowsky/foundry-local">GitHub: github.com/retkowsky/foundry-local</a></blockquote><p>Foundry Local exposes an OpenAI-compatible REST API, meaning you can use the exact same code for local and cloud inference. Switching between local and Azure endpoints is as simple as changing a base URL.</p><blockquote><a href="http://www.foundrylocal.ai/">www.foundrylocal.ai</a></blockquote><h3>Why Foundry Local?</h3><p>Before diving into the architecture, let’s understand the core value propositions that make Foundry Local a compelling choice for developers and organizations:</p><ul><li><strong>Complete Data Privacy: </strong>All prompts and outputs stay on your device. Data never leaves your system, making it ideal for healthcare, government, finance, and other regulated workloads subject to HIPAA, GDPR, and similar frameworks.</li><li><strong>Low-Latency Inference: </strong>No network roundtrips means real-time, interactive AI experiences with minimal latency.</li><li><strong>Offline Operation: </strong>Once models are downloaded, everything works fully offline — perfect for air-gapped systems or unreliable connectivity.</li><li><strong>Cost Efficiency: </strong>Leverage existing hardware (CPU, GPU, NPU) for inference, eliminating recurring cloud costs.</li><li><strong>Automatic Hardware Optimization: </strong>Foundry Local detects your hardware and downloads the best-optimized model variant (NVIDIA CUDA, AMD DirectML, Apple Metal, Intel/Qualcomm NPU, or CPU with INT4/INT8 quantization).</li><li><strong>No Azure Subscription Required: </strong>Use it entirely standalone, though hybrid cloud-to-edge workflows with Azure AI Foundry are fully supported.</li></ul><h3>Architecture Deep Dive</h3><p>Foundry Local’s architecture is designed for efficient, private, and scalable on-device AI inference. It follows a layered design where each component has a clearly defined responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e0dBndt25BlNXGw8" /><figcaption>Architecture</figcaption></figure><h3>The Request Flow</h3><p>Understanding how a request travels through the system is key to appreciating the design:</p><p>1. <strong>Request — </strong>The developer sends a request via CLI, Python SDK, JavaScript SDK, .NET SDK, or REST API.</p><p>2. <strong>Routing — </strong>The Foundry Local Service receives the request through its OpenAI-compatible endpoint.</p><p>3. <strong>Model Operations — </strong>The Model Manager loads the requested model, downloading and caching it if needed.</p><p>4. <strong>Inference — </strong>ONNX Runtime executes the inference using the optimal hardware execution provider.</p><p>5. <strong>Response — </strong>Results are returned through the same API interface.</p><h3>Core Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*eNv7-htMuXnwLQm-mrPGxw.png" /><figcaption>Components</figcaption></figure><h3>Hardware Abstraction Layer</h3><p>One of Foundry Local’s most elegant design decisions is its hardware abstraction layer. Rather than requiring developers to write hardware-specific code, the platform automatically detects available compute resources and selects the optimal execution provider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*2xrJvbW3C8mOyaIsCLTMTQ.png" /></figure><p>This means the same application code runs identically on a developer’s MacBook with Apple Silicon, a Windows workstation with an NVIDIA GPU, or a server with only CPU resources — Foundry Local adapts automatically.</p><h3>Model Catalog and Lifecycle</h3><p>Foundry Local provides a curated catalog of over 25 pre-optimized, open-source AI models ready to run on your device. The model lifecycle follows a clear progression: <strong>Download</strong> from the catalog → <strong>Load</strong> into memory with configurable TTL → <strong>Run</strong> inference → <strong>Unload</strong> to free resources → <strong>Delete</strong> from cache when no longer needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*tTRfxdyOASF4Cd7i.jpg" /><figcaption>Model catalog</figcaption></figure><p>Managing models is straightforward via the CLI:</p><pre># List all available models<br>foundry model list<br><br># Download and run a model<br>foundry model run phi-4-mini<br><br># Get detailed info about a specific model<br>foundry model info phi-4-mini<br><br># Remove a cached model<br>foundry model remove phi-4-mini</pre><h3>The Notebook Collection: A Hands-On Journey</h3><p>To help developers get started and progressively explore more advanced capabilities, I created a collection of six Jupyter Notebooks. Each notebook builds on the previous one, taking you from installation basics to deploying custom models from Hugging Face.</p><p><a href="https://github.com/retkowsky/foundry-local">https://github.com/retkowsky/foundry-local</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*I6Krx99T_qHVmGzb3PL_GQ.png" /><figcaption>Notebooks</figcaption></figure><h4>Notebook 01 — Getting Started with Foundry Local</h4><p>The first notebook is your entry point. It walks you through verifying your Foundry Local installation, checking the service status, exploring the model catalog, and running your first inference call. You will learn how to use the foundry-local-sdk Python package to programmatically discover available models, check hardware capabilities, and understand the local endpoint architecture. This notebook ensures your environment is correctly configured before moving to more advanced topics.</p><h4>Notebook 02 — Chat Completions</h4><p>This notebook demonstrates how to use the chat completions API — the same interface familiar to anyone who has used the OpenAI SDK. Because Foundry Local exposes an OpenAI-compatible endpoint, you can use the standard openai Python package with just a base URL change. The notebook covers single-turn and multi-turn conversations, streaming responses, system prompts for behavior control, and parameter tuning (temperature, top_p, max_tokens). It showcases the seamless portability between local and cloud inference.</p><h4>Notebook 03 — Practical Applications</h4><p>Moving beyond basic API calls, this notebook showcases real-world applications you can build with Foundry Local: text summarization, language translation, sentiment analysis, code generation and explanation, creative writing, structured data extraction, and question answering. Each example is self-contained and demonstrates how a single local model can handle diverse tasks with production-quality results.</p><h4>Notebook 04 — Mistral 7B</h4><p>This notebook focuses specifically on the Mistral 7B model, one of the most capable open-source models in the Foundry Local catalog. It explores model-specific capabilities, benchmarks inference performance on local hardware, and demonstrates how different quantization levels affect both quality and speed. It is an excellent reference for understanding what a 7-billion parameter model can do entirely on your device.</p><h4>Notebook 05 — Advanced Function Calling</h4><p>Function calling (or tool use) is one of the most powerful capabilities of modern language models, enabling them to invoke external tools and APIs. This notebook demonstrates how to define custom functions, pass them to the local model, parse structured tool-call responses, execute the functions, and feed results back for natural language answers. Examples include weather lookups, calculations, and database queries — all processed entirely on-device with no cloud dependency.</p><h4>Notebook 06 — Custom Models with Microsoft Olive</h4><p>The final notebook is the most advanced. It walks through the complete workflow of taking a model from Hugging Face, converting it to ONNX format using <strong>Microsoft Olive</strong>, applying INT4 quantization for optimal performance, and registering it in Foundry Local’s cache for local inference. This is particularly valuable for organizations that have fine-tuned their own models and want to deploy them on-device. Olive handles graph optimization, quantization, and hardware-specific compilation, producing models that run efficiently on any supported platform.</p><h3>Getting Started</h3><p>Setting up is straightforward. Install Foundry Local from <strong>foundrylocal.ai</strong>, clone the repository, install the Python dependencies, and launch Jupyter:</p><pre># Install Foundry Local from foundrylocal.ai<br># Clone the notebooks<br>git clone https://github.com/retkowsky/foundry-local.git<br>cd foundry-local<br># Install Python dependencies<br>pip install -r requirements.txt<br># Launch Jupyter<br>jupyter notebook</pre><p><strong>🚀 Supported Platforms</strong></p><p>Windows 10/11 (x64, ARM), Windows Server 2025, and macOS with Apple Silicon (M1/M2/M3/M4). Minimum 8 GB RAM (16 GB recommended). NVIDIA, AMD, Intel, Qualcomm GPUs/NPUs, and Apple Metal are all supported.</p><h3>Foundry Local with VS Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0A5c2EbTX3nizGB02ryog.png" /><figcaption>Foundry Local with VS Code</figcaption></figure><h3>Conclusion</h3><p>Foundry Local represents a significant step forward in making AI inference accessible, private, and cost-effective. By running models directly on your hardware with an OpenAI-compatible API, it removes the barriers that have traditionally made local inference complex and fragmented.</p><p>The six notebooks in this repository provide a progressive learning path — from first setup to deploying custom models — and demonstrate that on-device AI is no longer a compromise. Whether you are prototyping a new application, handling sensitive data, or simply want to reduce cloud costs, Foundry Local delivers enterprise-grade local inference with minimal friction.</p><p>I encourage you to clone the repository, run the notebooks, and experience the power of on-device AI firsthand.</p><h3>Documentation</h3><p><a href="http://www.foundrylocal.ai/">www.foundrylocal.ai</a></p><ul><li><a href="https://www.foundrylocal.ai/">Foundry Local - Run AI Models Locally with Complete Privacy</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-local/concepts/foundry-local-architecture?view=foundry-classic">Foundry Local architecture - Foundry Local</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-local/what-is-foundry-local">What is Foundry Local? - Foundry Local</a></li></ul><p><a href="https://github.com/retkowsky/foundry-local/blob/main/models.xlsx">https://github.com/retkowsky/foundry-local/blob/main/models.xlsx</a></p><h3>Author</h3><p>Serge Retkowsky | <a href="/service/mailto:serge.retkowsky@microsoft.com">serge.retkowsky@microsoft.com</a> | <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a></p><p><em>📅 Last Updated: 27–02–2026</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc841d9d4fbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spec2Cloud: Accelerate your Azure development with production-ready templates]]></title>
            <link>https://medium.com/@sergems18/spec2cloud-accelerate-your-azure-development-with-production-ready-templates-2e7fab558e46?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e7fab558e46</guid>
            <category><![CDATA[spec2cloud]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[foundry]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 09:34:17 GMT</pubDate>
            <atom:updated>2026-01-16T09:34:17.673Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>A Comprehensive Guide to Accelerating Azure Development</em></h3><p><em>with Production-Ready Templates from the Microsoft AI &amp; Apps Global Black Belt team.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Iv6iCg4d9jLuP3fHZ3iE3g.png" /><figcaption>Spec2Cloud</figcaption></figure><h3>TL;DR</h3><p><a href="http://aka.ms/spec2cloud"><strong>Spec2Cloud </strong></a>is a Microsoft asset offering a curated catalog of<strong> production-ready templates to accelerate</strong> Azure application development made by <em>Microsoft AI &amp; Apps Global Black Belt team</em>.</p><ul><li><strong>Core Concept:</strong> Implements <strong><em>Spec-Driven Development (SDD)</em></strong> — start with structured specifications, then generate and deploy apps using AI-powered workflows.</li><li><strong>Use Cases:</strong> AI apps, legacy modernization, data-driven apps, and agentic DevOps.</li><li><strong>Business Impact:</strong> Reduces time-to-market, ensures compliance, and improves collaboration between business and technical teams.</li><li><strong>Technical Value:</strong> Eliminates boilerplate setup, automates repetitive tasks and optimizes workflows.</li></ul><h3>1. Introduction</h3><h4>What is Spec2Cloud?</h4><p><a href="http://aka.ms/spec2cloud"><strong>Spec2Cloud </strong></a>is a <strong>curated catalog of production-ready templates designed to help developers quickly build and deploy Azure applications</strong>.</p><p>Whether you’re building AI agents, modernizing applications, or creating data-centric solutions,<strong> Spec2Cloud provides the templates and tools to get you started faster.</strong></p><p><strong>Spec2Cloud</strong> is a transformative <strong>Microsoft </strong>asset that revolutionizes how developers build and deploy applications on Azure. At its core, <strong>Spec2Cloud is an AI-powered development workflow that transforms high-level product ideas into production-ready applications deployed on Azure, using specialized GitHub Copilot agents working together seamlessly.</strong></p><p>The platform provides a curated catalog of<strong> production-ready templates</strong> designed to help developers <strong>quickly bootstrap AI applications, modernize existing apps, and build data-centric solutions</strong>.</p><p>By combining the power of <strong>GitHub Copilot with Azure’s cloud capabilities</strong>, <strong>Spec2Cloud </strong>enables teams to go from idea to production in minutes rather than months.</p><p>The project uses the<strong> MIT license, making it freely available for both personal and commercial use</strong>.</p><p><strong>Note: Spec2Cloud </strong>is not an official Microsoft product and does not carry the standard guarantees associated with Microsoft offerings. Instead, it represents an opinionated framework for implementing SDD (<em>Spec Driven Development</em>), purposefully designed to be adaptable to each customer’s unique requirements.</p><blockquote><a href="https://github.com/Azure-Samples/Spec2Cloud">Azure-Samples/Spec2Cloud: Spec-Driven Development templates to build and deploy Apps/Agents to Azure</a></blockquote><h3>“Vibe Coding” vs “Spec-Driven Development”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*L12jH_t5YRdD9gjZN504Jg.png" /></figure><p><strong>Coding agents automate repetitive tasks</strong>, helping developers focus on architecture and design with AI-generated code snippets.</p><p><strong>Vibe coding </strong>— using <em>AI-driven prompts to quickly generate code</em> — can accelerate rapid prototyping and experimentation. It’s an excellent way to validate ideas fast and reduce initial development time.</p><p>However, when it comes to production systems, this approach introduces significant risks. The source of truth remains in the code, and without rigorous engineering practices, teams may face:</p><ul><li><strong>Security Vulnerabilities</strong> that expose systems to threats,</li><li><strong>Code Quality and Logical Errors</strong> impacting reliability,</li><li>Maintainability <strong>Issues and Technical Debt</strong> that slow future development,</li><li><strong>Debugging Challenge</strong>s making troubleshooting complex,</li><li><strong>Compliance and Governance Risks</strong> that jeopardize regulatory alignment.</li></ul><p><strong>Spec-Driven Development</strong> — introduces a transformative approach to software creation by making the specification the single source of truth.</p><p>Instead of relying on fragmented documentation or assumptions, <strong>all business and technical requirements are captured in the spec</strong>, which drives the entire development process. The workflow begins with a <strong>well-defined spec</strong> that includes both business requirements and technical requirements.</p><p>This <strong>spec is then used by coding agents and tools like Copilot to generate code</strong>, ensuring alignment and consistency. As development progresses, the spec is continuously enhanced with changes, fixes, and updates, maintaining its role as the authoritative reference.</p><h4>Why Spec-Driven Development Matters</h4><ul><li><strong>Clear Alignment Across Teams</strong> — Everyone works from the same source of truth, reducing miscommunication.</li><li><strong>Early Problem Detection</strong> — Documenting requirements upfront exposes risks and dependencies before coding begins.</li><li><strong>Accelerated Delivery </strong>— Precise instructions enable autonomous development and faster execution.</li><li><strong>Reduced Technical Debt</strong> — Technical requirements expressed in natural language simplify maintenance.</li><li><strong>Improved Governance &amp; Compliance</strong> — Specs embed standards, security policies, and audit trails.</li><li><strong>Reusable Templates for Scale </strong>— Proven patterns can be replicated across projects and industries.</li></ul><p>By embedding clarity, compliance, and scalability into the development lifecycle, <em>Spec-Driven Development</em> empowers teams to deliver high-quality software faster and with fewer risks. It’s not just an improvement — it’s the next evolutionary step in coding.</p><h3>The Vision Behind Spec2Cloud</h3><p><strong>Spec-Driven Development (SDD)</strong> represents a paradigm shift in enterprise software development.</p><p>Rather than jumping directly into code, <strong>SDD emphasizes upfront clarity through structured specifications</strong>, which leads to fewer regressions, easier maintenance, and better alignment between business requirements and technical implementation.</p><p><strong>Spec2Cloud </strong>embodies this philosophy by providing developers with <strong>templates that encode best practices, security guidelines, and compliance requirements</strong> directly into the development workflow.</p><p>This ensures that generated plans and code adhere to organizational constraints from the very beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xr-e-u7zUB7TWivqfqh3g.png" /><figcaption>What is spec driven development?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEu9_grNiDcyzDEnF9qhJw.png" /><figcaption>The New Blueprint for Building Software</figcaption></figure><h3>Key Benefits at a Glance</h3><p>• 🚀 <strong>Accelerated Development: </strong>Transform product ideas into deployed applications through structured specification-driven development.</p><ul><li>🤖 <strong>AI-Powered Automation: </strong>Specialized GitHub Copilot agents handle different aspects of the development lifecycle.</li><li>📦 <strong>Production-Ready Templates: </strong>Curated templates for AI apps, data solutions, and app modernization.</li><li>☁️ <strong>Azure Integration: </strong>Native support for Azure services including AI Foundry, Cosmos DB, and more.</li><li>🔧 <strong>Multiple Access Methods: </strong>Web interface, VS Code extension, and CLI (not yet available — coming soon).</li><li>📂 <strong>Using Existing Customer Data</strong><br>An important idea from the original <strong>Spec2Cloud </strong>value is that customers often have valuable data for their use case scattered across multiple sources. The approach is to consolidate this data into .md files and leverage it to create build instructions or an agents.md file. Additional details can be found in the Spec2Cloud Reference Implementation. More information: <a href="https://emeaappgbb.github.io/spec2cloud-reference/">Spec2Cloud Reference Implementation</a></li></ul><h3>2. Key Features and Capabilities</h3><h4>🤖 Specialized AI Agents</h4><p><strong>Spec2Cloud </strong>provides <strong>eight specialized AI agents</strong>, each designed for specific phases of the development lifecycle.</p><p>These agents work together to maintain consistency, traceability, and best practices throughout your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*vTGirwrtxWJgX3-UrVXqZQ.png" /></figure><h4>🔀 Workflow Prompts</h4><p><strong>Spec2Cloud </strong>includes <strong>13 workflow prompt</strong>s that guide agents through each phase of development.</p><p>These prompts ensure consistency and best practices are followed throughout the project lifecycle.</p><ul><li><strong>/prd </strong>— Generate Product Requirements Document</li><li><strong>/frd </strong>— Generate Functional Requirements Document</li><li><strong>/plan </strong>— Create development execution plan</li><li><strong>/deploy </strong>— Deploy application to Azure</li><li><strong>/rev-eng </strong>— Reverse engineer existing codebase into specs</li><li><strong>/modernize </strong>— Create modernization plan for legacy applications</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFeAKZ5ddKLcvMxyvoNhBg.png" /><figcaption>Building agents at scale with Spec2Cloud</figcaption></figure><h3>Gallery and Template Discovery</h3><p>The <strong>VS Code extension </strong>provides a <strong>beautiful gallery interface</strong> for browsing templates with full-featured template cards displaying thumbnails, real-time search across all template properties, multiple filter options including category, industry, services, languages, and frameworks, sorting capabilities by name or date, and video previews with detailed information modals.</p><blockquote><a href="http://aka.ms/spec2cloud">http://aka.ms/spec2cloud</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPJzA5OZ5RKH2xSETUjBjQ.png" /><figcaption><a href="http://aka.ms/spec2cloud">http://aka.ms/spec2cloud</a></figcaption></figure><p><strong>Note: Templates </strong>serve as one of the main entry points to <strong>Spec2Cloud</strong>, providing customers with a starting point to build upon. If a suitable template doesn’t exist, the alternative entry point is the GitHub repository, which includes public templates for shells (.NET and Python) and Spec2Cloud itself.</p><h3>MCP Tool Support</h3><p><strong>Spec2Cloud provides Model Context Protocol (MCP) </strong>tools for finding templates and estimating costs on Azure.</p><p>This integration enables AI assistants to discover and recommend templates based on project requirements, making the development workflow even more intelligent and automated.</p><h3><strong>Specialized AI Agents and Spec2Cloud</strong></h3><p><strong>Spec2Cloud</strong>, often referred to as the <strong>orchestrator</strong>, stands out as a key feature when discussing specialized AI agents.</p><h3>3. Use Cases and Industry Applications</h3><h4>Template Categories</h4><p><strong>Spec2Cloud </strong>organizes templates into <strong>four primary categories</strong>, each targeting specific development scenarios:</p><h4>1. 🤖 AI Apps and Agents</h4><p><strong>Build intelligent applications with Azure AI services</strong>, including chatbots, AI agents, and AI-powered workflows. These templates leverage <strong>Microsoft Foundry, OpenAI models, and other cognitive services</strong> to create sophisticated AI solutions. Use cases include customer service bots, intelligent document processing, marketing campaign generators, and multi-agent collaboration systems.</p><h4>2. 🔄 App Modernization</h4><p><strong>Migrate and modernize existing applications to Azure</strong> with cloud-native architectures and best practices. The brownfield workflow allows teams to reverse engineer existing codebases into comprehensive product and technical documentation, then optionally modernize the codebase using AI-guided recommendations. This is ideal for organizations looking to move legacy applications to the cloud while maintaining business continuity.</p><h4>3. 📊 Data Centric Apps</h4><p><strong>Create data-driven applications leveraging Azure data services</strong> like Cosmos DB, SQL databases, and analytics platforms. These templates are designed for scenarios requiring robust data handling, real-time analytics, and scalable storage solutions. Industries such as finance, healthcare, and retail benefit from these patterns for building data warehouses, analytics dashboards, and transaction processing systems.</p><h4>4. ⚙️ Agentic DevOps</h4><p><strong>Implement automated DevOps workflows with AI-powered agents for CI/CD</strong>, monitoring, and infrastructure management. These templates help organizations establish modern DevOps practices with intelligent automation that learns and adapts to your deployment patterns.</p><h4>🚀 Industry Applications</h4><p><strong>Spec2Cloud templates</strong> are designed to be industry-agnostic while providing specific configurations for various sectors. The template metadata includes industry categorization, allowing developers to quickly find solutions tailored to their domain.</p><ul><li>🏥 <strong>Healthcare: </strong>Patient engagement apps, clinical decision support, medical imaging analysis.</li><li>💳 <strong>Financial Services: </strong>Fraud detection, risk assessment, customer service automation.</li><li>🛒 <strong>Retail: </strong>Personalization engines, inventory management, customer analytics.</li><li>🏭<strong>Manufacturing: </strong>Predictive maintenance, quality control, supply chain optimization.</li><li>🌐 <strong>Cross-Industry: </strong>General-purpose templates applicable to any business domain.</li></ul><h3>4. Integration with VS Code and Azure Ecosystem</h3><h4>VS Code Extension</h4><p>The <strong>Spec2Cloud Toolkit extension for Visual Studio Code</strong> provides an integrated template experience directly within your development environment.</p><p>Installation is straightforward through the <em>VS Code Marketplace</em>, and the extension offers seamless access to the entire template catalog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0qEUZ71N7_ThwnRqaeHjA.png" /><figcaption>VSCode extension</figcaption></figure><blockquote><a href="https://marketplace.visualstudio.com/items?itemName=ms-gbb-tools.spec2cloud-toolkit">https://marketplace.visualstudio.com/items?itemName=ms-gbb-tools.spec2cloud-toolkit</a></blockquote><p><strong>Extension Features:</strong></p><ul><li><strong>Download templates</strong> directly to your workspace with overwrite protection,</li><li>Stay up to date with the<strong> latest templates </strong>through automatic refresh,</li><li><strong>IntelliSense </strong>and validation for template metadata,</li><li><strong>Built-in template creation tools</strong> for contributors,</li><li><strong>Configurable </strong>resource links to documentation.</li></ul><h4>Web Experience</h4><p>The<strong> web catalog </strong>at <a href="http://aka.ms/spec2cloud">http://aka.ms/spec2cloud</a> provides an<strong> intuitive interface for browsing templates with advanced search and filtering, video demonstrations</strong>, tag-based discovery, GitHub stars and activity tracking, and a mobile-friendly responsive design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zh5PA58zogKGjF7MuZ1eA.png" /><figcaption><a href="http://aka.ms/spec2cloud">http://aka.ms/spec2cloud</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*Bvs2Y7CaF7cXba_lwbK4Uw.png" /><figcaption>Template</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*DhELSXRDNNOfY3xTVplAYA.png" /><figcaption>Template</figcaption></figure><h4>Azure Service Integration</h4><p><strong>Spec2Cloud templates leverage over 60 Azure services</strong>, with dedicated icons and metadata for each.</p><p>The extension includes SVG icons for services (blue badges), programming languages (orange badges), and frameworks (purple badges), making it easy to identify the technology stack at a glance.</p><p><strong>Common Azure Services in Templates:</strong></p><ul><li><strong>Azure AI Foundry</strong> for building intelligent applications.</li><li><strong>Azure OpenAI Service</strong> for large language model integration from OpenAI.</li><li><strong>Azure Cosmos DB</strong> for globally distributed databases.</li><li><strong>Azure App Service</strong> for web application hosting.</li><li><strong>Azure Functions</strong> for serverless compute.</li><li><strong>Azure Container Apps </strong>for containerized applications.</li></ul><h4>GitHub Copilot Integration</h4><p><strong>Spec2Cloud works seamlessly with GitHub Copilot for Azure</strong>, which enables developers to use natural language to learn about Azure features, deploy Azure resources, get information about resources, and diagnose and troubleshoot problems.</p><p>The <strong>Azure Model Context Protocol (MCP) Server enables interaction with Azure services</strong> to carry out specific tasks on your behalf.</p><h3>5. Technical Architecture and Workflows</h3><h4>Development Workflows</h4><p><strong>Spec2Cloud </strong>supports multiple development workflows to accommodate different project scenarios. Each workflow is designed to leverage AI agents effectively while maintaining human oversight and control.</p><h4>Greenfield Development (Build New)</h4><p>Transform product ideas into deployed applications through structured specification-driven development. The workflow begins with describing your app idea, then follows a guided process through requirements gathering, architecture design, implementation, and deployment.</p><ul><li>Use the repository as a template or create a new project.</li><li>Open in Dev Container (preconfigured environment).</li><li>Describe your app idea in detail.</li><li>Use /prd prompt to generate Product Requirements Document.</li><li>Use /frd prompt to generate Functional Requirements Document.</li><li>Use /plan prompt to create development execution plan.</li><li>Use /deploy prompt to deploy to Azure.</li></ul><h4>Shell-Based Development</h4><p>Start from a predefined shell baseline and let coding agents translate natural language requirements to fill in the gaps via code.</p><p>Shell templates are available for .NET and Python, including agentic variants for building AI agent applications.</p><h4>Brownfield Development (Modernize Existing)</h4><p>Reverse engineer existing codebases into comprehensive product and technical documentation, then optionally modernize the codebase.</p><p>This workflow is ideal for legacy application migration to Azure.</p><ul><li>Copy existing codebase into the new repository.</li><li>Run /rev-eng to reverse engineer codebase into specs.</li><li>Run /modernize to create modernization plan (optional).</li><li>Run /plan to execute modernization tasks.</li></ul><h4>Template Structure</h4><p>Every <strong>Spec2Cloud </strong>template follows a standardized structure that includes a <strong>SPEC2CLOUD.md metadata file</strong> with YAML front matter, a .github folder containing GitHub Copilot configuration files, agents, and prompts, and Specs directories with markdown specification files.</p><p><strong>Required Metadata Fields:</strong></p><ul><li><strong>title: </strong>Template name (max 40 characters).</li><li><strong>description: </strong>Brief summary (max 140 characters).</li><li><strong>category: </strong>AI Apps and Agents, App Modernization, Data Centric Apps, or Agentic DevOps.</li><li><strong>industry: </strong>Target industry or Cross-Industry.</li><li><strong>Optional Metadata Fields: </strong>authors, services, languages, frameworks, tags, thumbnail, video, version.</li></ul><blockquote><a href="https://github.com/EmeaAppGbb/spec2cloud">EmeaAppGbb/spec2cloud</a></blockquote><h3>6. Getting Started Guide</h3><h4>Prerequisites</h4><ul><li>Visual Studio Code 1.85.0 or later.</li><li>GitHub Copilot subscription.</li><li>Azure subscription for deployment.</li><li>Internet connection for fetching templates.</li></ul><h4>Installation Methods</h4><p><strong>Method 1: VS Code Extension (Recommended)</strong></p><ul><li>Open Visual Studio Code.</li><li>Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X).</li><li>Search for “Spec2Cloud Toolkit”.</li><li>Click Install.</li></ul><p><strong>Method 2: Web Catalog</strong></p><ul><li>Visit <a href="http://aka.ms/spec2cloud">http://aka.ms/spec2cloud</a></li><li>Browse templates using filters.</li><li>Click “Use in” and select your preferred option:</li><li>Open in VS Code — Download directly to local workspace</li><li>GitHub Codespaces — Launch in cloud development environment</li><li>vscode.dev — Open in VS Code for the Web</li><li>Clone — Copy the git clone command</li></ul><p><strong>Method 3: GitHub Template</strong></p><ul><li>Navigate to <a href="https://github.com/Azure-Samples/Spec2Cloud">https://github.com/Azure-Samples/Spec2Cloud</a></li><li>Click “Use this template” to create your own repository.</li><li>Open in Dev Container for preconfigured environment.</li></ul><p><strong>Method 4: Quick Install Script</strong></p><pre># Full installation (agents, prompts, devcontainer, MCP)<br>curl -fsSL https://raw.githubusercontent.com/EmeaAppGbb/spec2cloud/main/scripts/quick-install.sh | bash<br><br># Minimal installation (agents and prompts only)<br>curl -fsSL https://raw.githubusercontent.com/EmeaAppGbb/spec2cloud/main/scripts/quick-install.sh | bash -s -- --minimal<br><br># Install to specific directory<br>curl -fsSL https://raw.githubusercontent.com/EmeaAppGbb/spec2cloud/main/scripts/quick-install.sh | bash -s -- --target /path/to/project</pre><p>For manual download</p><pre># Download latest release<br>curl -L https://github.com/EmeaAppGbb/spec2cloud/releases/latest/download/spec2cloud-full-latest.zip -o spec2cloud.zip<br><br># Extract<br>unzip spec2cloud.zip -d spec2cloud<br><br># Run installer<br>cd spec2cloud<br>./scripts/install.sh --full<br><br># Or on Windows<br>.\scripts\install.ps1 -Full</pre><blockquote><a href="https://github.com/EmeaAppGbb/spec2cloud/blob/main/INTEGRATION.md">spec2cloud/INTEGRATION.md at main · EmeaAppGbb/spec2cloud</a></blockquote><h4>First Steps After Installation</h4><ul><li><strong>Browse Templates: </strong>Open Command Palette and type “Spec2Cloud: Browse Templates”,</li><li><strong>Select a Template: </strong>Choose based on your project requirements,</li><li><strong>Download to Workspace: </strong>Template files will be cloned to your current workspace,</li><li><strong>Follow README: </strong>Each template includes setup instructions.</li></ul><h3>7. Best Practices and Tips</h3><h4>Effective Prompting</h4><p>When working with <strong>Spec2Cloud </strong>agents, follow these best practices for optimal results:</p><ul><li><strong>Use Agent Mode: </strong>For the best experience, use Agent mode rather than Ask mode.</li><li><strong>Include Azure Context: </strong>Include the word “Azure” in prompts to help Copilot understand cloud deployment needs.</li><li><strong>Be Specific: </strong>The more detailed your requirements, the better the output.</li><li><strong>Iterate: </strong>Work with the copilot through several iterations until it understands your needs.</li><li><strong>Review Plans: </strong>Always review the generated plan before authorizing execution.</li></ul><h4>Template Selection</h4><ul><li>Match templates to your technology stack using language and framework filters.</li><li>Consider industry-specific templates for compliance and best practices.</li><li>Watch demo videos to understand template capabilities before downloading.</li><li>Check GitHub stars and activity for template popularity and maintenance.</li></ul><h4>Workflow Optimization</h4><ul><li><strong>Start with Specifications: </strong>Always generate PRD and FRD before coding.</li><li><strong>Use Dev Containers: </strong>Leverage preconfigured environments for consistency.</li><li><strong>Review Bicep Templates: </strong>Always inspect generated infrastructure code before deployment.</li><li><strong>Maintain Traceability: </strong>Link code changes back to specifications.</li></ul><h4>Security Considerations</h4><ul><li>Review all generated code for security best practices.</li><li>Use Azure RBAC to control template spec access.</li><li>Validate deployment templates against organizational policies.</li><li>Keep secrets and credentials out of specification documents.</li></ul><h3>8. Future Roadmap and Community</h3><h4>Upcoming Features</h4><h4>🔜 <strong>CLI Experience (Coming Soon)</strong></h4><p><strong>A command-line interface</strong> for developers who prefer terminal-based workflows is in development.</p><p>Planned features include listing and searching templates from the terminal, cloning templates with a single command, generating new templates from scaffolding, and automating template deployment workflows.</p><h4>🌐 Community Resources</h4><p>Visit the GitHub repository to open issues, submit pull requests, or join discussions about the future of <strong>Spec2Cloud</strong>.</p><p>The project uses the<strong> MIT license, making it freely available for both personal and commercial use</strong>.</p><h4>📖 Links and Resources</h4><ul><li>🌐 Web Catalog <a href="http://aka.ms/spec2cloud">http://aka.ms/spec2cloud</a></li><li>🔧 VS Code Extension <a href="https://marketplace.visualstudio.com/items?itemName=ms-gbb-tools.spec2cloud-toolkit">Spec2Cloud Toolkit</a></li><li>🔗 GitHub Repository <a href="https://github.com/Azure-Samples/Spec2Cloud">Azure-Samples/Spec2Cloud</a></li><li>📋 Template Guidelines <a href="https://github.com/EmeaAppGbb/spec2cloud">EmeaAppGbb/spec2cloud</a></li></ul><h3>9. Conclusion</h3><h4>💰 Business Impact</h4><p><strong>Spec2Cloud</strong> represents a <strong>significant advancement in enterprise application development.</strong></p><p>By combining the <strong>power of AI-driven development with production-ready templates and Azure’s robust cloud infrastructure</strong>, organizations can <strong>dramatically reduce time-to-market </strong>for new applications while maintaining<strong> high standards for quality, security, and compliance</strong>.</p><p>The Spec-Driven Development approach ensures that business requirements are clearly captured and traced throughout the development lifecycle. This not only improves communication between business stakeholders and technical teams but also provides valuable documentation for future maintenance and enhancement efforts.</p><h4>⚙️ Technical Value</h4><p>For developers, <strong>Spec2Cloud eliminates the boilerplate work of setting up new projects and configuring Azure services.</strong></p><p><strong>The specialized AI agents </strong>handle repetitive tasks while still allowing human oversight and control over the final output. This enables developers to focus on business logic and innovation rather than infrastructure concerns.</p><p>The integration with<strong> GitHub Copilot and the Azure MCP Server</strong> provides a seamless development experience that learns and adapts to your organization’s patterns and preferences.</p><p>Whether you’re building a new AI application, modernizing a legacy system, or creating a data-centric solution, <strong>Spec2Cloud </strong>provides the templates and tools to accelerate your journey.</p><h4>🚀 Getting Started Today!</h4><p>The best way to experience <a href="http://aka.ms/spec2cloud">Spec2Cloud </a>is to dive in.</p><p>Visit the web catalog at <a href="http://aka.ms/spec2cloud,"><strong>http://aka.ms/spec2cloud,</strong></a> install the V<strong>S Code extension</strong>, and start exploring the template catalog.</p><p>With multiple access methods and comprehensive documentation, there’s never been a better time to accelerate your Azure development.</p><p>Have a good day!</p><blockquote><strong><em>From idea to production in minutes, not months.</em></strong></blockquote><blockquote><em>Built with </em>❤ ️ <em>by the Microsoft Global Black Belt Team</em></blockquote><h3>👥 Article authors</h3><ul><li><a href="https://www.linkedin.com/in/farid-el-attaoui/"><strong>Farid El Attaoui</strong></a><strong> — Microsoft France</strong></li><li><a href="https://www.linkedin.com/in/alibek-jakupov-30305b61/"><strong>Alibek Jakupov</strong></a><strong> — Microsoft France</strong></li><li><a href="https://www.linkedin.com/in/serger"><strong>Serge Retkowsky</strong></a><strong> — Microsoft France</strong></li></ul><h3>📌Spec2Cloud infographics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sq1iDt1kuSIw8SA6lxCY-g.png" /><figcaption>Infographics</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e7fab558e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Multimodal Visual Search Engine with Cohere Embed 4 and Microsoft Foundry]]></title>
            <link>https://medium.com/@sergems18/building-a-multimodal-visual-search-engine-with-cohere-embed-4-and-microsoft-foundry-37476066e0d9?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/37476066e0d9</guid>
            <category><![CDATA[cohere]]></category>
            <category><![CDATA[foundry]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[visual-search]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 15:00:15 GMT</pubDate>
            <atom:updated>2025-12-11T15:36:36.566Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete guide to creating a multilingual fashion search application with text and image queries</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GGX5Xvc8_RDi1S0Zhx2chA.jpeg" /><figcaption>Cohere Embed v 4.0</figcaption></figure><blockquote>🔥<strong>All code is available here: </strong><a href="https://github.com/retkowsky/visual-search-cohere-embed-v-4-0/tree/main">retkowsky/visual-search-cohere-embed-v-4–0: Visual Search with Microsoft Foundry and Cohere Embed 4</a></blockquote><p>In the age of AI-powered applications, <strong>multimodal search</strong> represents one of the most exciting frontiers. Imagine searching for products not just with text, but with images — or even mixing both in the same system. Today, I’ll walk you through building a complete visual search solution using <strong>Cohere’s Embed 4</strong> model deployed on <strong>Microsoft Foundry</strong>, paired with <strong>Azure AI Search</strong> for lightning-fast vector retrieval.</p><p>This tutorial is based on a series of Jupyter notebooks I developed for a fashion catalog use case, but the principles apply to any domain: e-commerce, medical imaging, real estate, or creative portfolios.</p><h3>Why Cohere Embed 4?</h3><p>Before diving into code, let’s understand what makes Cohere’s Embed 4 special:</p><p><strong>🌍 100+ Language Support</strong>: The model supports over 100 languages for text embeddings. A query in French can retrieve relevant documents written in English, enabling true cross-lingual search out of the box.</p><p><strong>🖼️ Multimodal Embeddings</strong>: Embed 4 handles both text and images, projecting them into the same vector space. This means you can search images with text queries or find similar images using another image as input.</p><p><strong>🪆 Matryoshka Embeddings</strong>: The model produces embeddings that can be truncated to smaller dimensions (64, 128, 256…) with minimal quality loss — perfect for optimizing storage and query speed.</p><p><strong>⚡ Enterprise Optimizations</strong>: Native int8 quantization and binary embeddings reduce storage footprint while maintaining accuracy. State-of-the-art results on MTEB benchmarks.</p><h3>Architecture Overview</h3><blockquote>🔥<strong>All code is available here: </strong><a href="https://github.com/retkowsky/visual-search-cohere-embed-v-4-0/tree/main">retkowsky/visual-search-cohere-embed-v-4–0: Visual Search with Microsoft Foundry and Cohere Embed 4</a></blockquote><p>Our solution consists of four main components:</p><pre>┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐<br>│  Azure Blob     │────▶│ Cohere Embed 4   ────▶│ Azure AI Search │<br>│  Storage        │     │ (Foundry)        │     │ (Vector Index)  │<br>└─────────────────┘     └──────────────────┘     └─────────────────┘<br>       ▲                        ▲                        │<br>       │                        │                        ▼<br>       │                  ┌─────────────┐          ┌──────────┐<br>       └──────────────────│   Gradio    │◀─────────│  Results │<br>                          │   Web App   │          └──────────┘<br>                          └─────────────┘</pre><h3>Part 1: Setting Up Multimodal Embeddings</h3><p>First, let’s establish connections to Cohere Embed 4 deployed in Azure AI Foundry:</p><pre>import os<br><br>from azure.ai.inference import EmbeddingsClient, ImageEmbeddingsClient<br>from azure.ai.inference.models import ImageEmbeddingInput<br>from azure.core.credentials import AzureKeyCredential<br>from dotenv import load_dotenv<br><br>load_dotenv(&quot;azure.env&quot;)<br><br># Configuration<br>api_key = os.getenv(&quot;api_key&quot;)<br>endpoint = os.getenv(&quot;endpoint&quot;)<br>deployment_name = &quot;embed-v-4-0&quot;<br></pre><pre># Text embedding client<br>text_clientpyt = EmbeddingsClient(<br>    endpoint=endpoint,<br>    credential=AzureKeyCredential(api_key),<br>    model=deployment_name<br>)<br><br># Image embedding client<br>image_client = ImageEmbeddingsClient(<br>    endpoint=endpoint,<br>    credential=AzureKeyCredential(api_key),<br>    model=deployment_name<br>)</pre><h4>Generating Text Embeddings</h4><pre>def get_text_embeddings(text: str) -&gt; list[float]:<br>    &quot;&quot;&quot;<br>    Generate text embeddings using Cohere Embed V4.<br>    <br>    Args:<br>        text: Input text to embed<br>    <br>    Returns:<br>        Dense vector representation capturing semantic meaning<br>    &quot;&quot;&quot;<br>    if not text or not text.strip():<br>        raise ValueError(&quot;Input text cannot be empty&quot;)<br><br>  response = text_client.embed(<br>    input=[text.strip()],<br>    model=deployment_name,<br>   )<br><br>  return response.data[0].embeddingp</pre><h4>Generating Image Embeddings</h4><pre>def get_image_embeddings(image_path: str) -&gt; list[float]:<br>    &quot;&quot;&quot;<br>    Generate image embeddings using Cohere Embed V4.<br>    <br>    Args:<br>        image_path: Path to a JPG image file<br>    <br>    Returns:<br>        Dense vector capturing visual semantics<br>    &quot;&quot;&quot;<br><br>    image_input = ImageEmbeddingInput.load(<br>        image_file=image_path,<br>        image_format=&quot;jpg&quot;,<br>    )<br>    response = image_client.embed(input=[image_input])<br><br>    return response.data[0].embedding</pre><h4>Computing Similarity</h4><p>The magic happens when we compare embeddings using cosine similarity:</p><pre>def get_cosine_similarity(vector1: list[float], vector2: list[float]) -&gt; float:<br>    &quot;&quot;&quot;<br>    Compute cosine similarity between two vectors.<br>    <br>    Returns:<br>        Score between -1 (opposite) and 1 (identical)<br>    &quot;&quot;&quot;<br>    norm1 = np.linalg.norm(vector1)<br>    norm2 = np.linalg.norm(vector2)<br>    <br>    if norm1 == 0 or norm2 == 0:<br>        return 0.0<br>    <br>    return np.dot(vector1, vector2) / (norm1 * norm2)</pre><h3>Part 2: Building the Azure AI Search Index</h3><p>Now let’s create a vector search index to store our fashion catalog embeddings.</p><h4>Index Schema Definition</h4><pre>from azure.search.documents.indexes import SearchIndexClient<br>from azure.search.documents.indexes.models import (<br>    HnswAlgorithmConfiguration,<br>    HnswParameters,<br>    SearchField,<br>    SearchFieldDataType,<br>    SearchIndex,<br>    SimpleField,<br>    VectorSearch,<br>    VectorSearchAlgorithmKind,<br>    VectorSearchProfile,<br>)</pre><pre># Initialize the client<br>search_client = SearchIndexClient(<br>    endpoint=azure_search_endpoint,<br>    credential=AzureKeyCredential(azure_search_key)<br>)</pre><pre># Define the index<br>index = SearchIndex(<br>    name=&quot;fashion-demo-2025&quot;,<br>    fields=[<br>        # Unique identifier<br>        SimpleField(<br>            name=&quot;idfile&quot;, <br>            type=SearchFieldDataType.String, <br>            key=True<br>        ),<br>        # Image filename reference<br>        SimpleField(<br>            name=&quot;imagefile&quot;, <br>            type=SearchFieldDataType.String<br>        ),<br>        # Cohere Embed 4 vector embeddings<br>        SearchField(<br>            name=&quot;imagevector&quot;,<br>            type=SearchFieldDataType.Collection(SearchFieldDataType.Single),<br>            searchable=True,<br>            vector_search_dimensions=1536,<br>            vector_search_profile_name=&quot;embedding_profile&quot;<br>        )<br>    ],<br>    vector_search=VectorSearch(<br>        algorithms=[<br>            HnswAlgorithmConfiguration(<br>                name=&quot;hnsw_config&quot;,<br>                kind=VectorSearchAlgorithmKind.HNSW,<br>                parameters=HnswParameters(metric=&quot;cosine&quot;),<br>            )<br>        ],<br>        profiles=[<br>            VectorSearchProfile(<br>                name=&quot;embedding_profile&quot;,<br>                algorithm_configuration_name=&quot;hnsw_config&quot;<br>            )<br>        ],<br>    ),<br>)</pre><pre># Create the index<br>result = search_client.create_or_update_index(index)<br>print(f&quot;✅ Index &#39;{result.name}&#39; created successfully&quot;)</pre><h4>Processing Images from Blob Storage</h4><p>With our fashion images stored in Azure Blob Storage, we generate embeddings in batches</p><h4>Batch Processing Pipeline</h4><pre># Process images in batches<br>batch_size = 100<br>processed_count = 0<br><br>print(f&quot;🚀 Processing {len(images_list)} images...&quot;)<br>for batch_start in range(0, len(input_data), batch_size):<br>    batch_data = input_data[batch_start:batch_start + batch_size]<br>    <br>    for item in batch_data:<br>        item[&quot;imagevector&quot;] = get_image_embeddings_from_blob(item[&quot;imagefile&quot;])<br>        processed_count += 1<br>    <br>    # Progress update<br>    pct_done = round(processed_count / len(input_data) * 100)<br>    print(f&quot;[{datetime.now()}] Processed {processed_count} | {pct_done}% complete&quot;)<br>print(f&quot;✅ Processed {processed_count} images&quot;)</pre><p><strong>Performance stats from our demo:</strong></p><ul><li>📊 <strong>2,000 fashion images</strong> indexed</li><li>💾 <strong>30.25 MB</strong> total index size</li></ul><h3>Part 3: Visual Search Implementation</h3><p>With our index populated, let’s build the search functions.</p><h4>Text-to-Image Search</h4><p>Search the catalog using natural language descriptions:</p><pre>from azure.search.documents import SearchClient<br>from azure.search.documents.models import VectorizedQuery<br><br>def visual_search_text(text: str, topn: int = 5) -&gt; list[tuple[str, float]]:<br>    &quot;&quot;&quot;<br>    Search for images using text description.<br>    <br>    Args:<br>        text: Natural language query (supports 100+ languages!)<br>        topn: Number of results to return<br>    <br>    Returns:<br>        List of (filename, similarity_score) tuples<br>    &quot;&quot;&quot;<br>    # Generate query embedding<br>    query_vector = get_text_embeddings(text)<br>    <br>    # Execute vector search<br>    search_client = SearchClient(<br>        azure_search_endpoint, <br>        index_name,<br>        AzureKeyCredential(azure_search_key)<br>    )<br>    <br>    results = search_client.search(<br>        search_text=None,<br>        vector_queries=[<br>            VectorizedQuery(<br>                vector=query_vector,<br>                k_nearest_neighbors=topn,<br>                fields=&quot;imagevector&quot;<br>            )<br>        ]<br>    )<br>    <br>    return [(doc[&quot;imagefile&quot;], doc[&quot;@search.score&quot;]) for doc in results]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_0lchcHQeV6smGDzov82Q.jpeg" /><figcaption>Visual search example</figcaption></figure><h4>Image-to-Image Search</h4><p>Find visually similar items using an image query:</p><pre>def visual_search_image(query_image: str, topn: int = 5) -&gt; list[tuple[str, float]]:<br>    &quot;&quot;&quot;<br>    Search for similar images using an image as query.<br>    <br>    Args:<br>        query_image: Path to query image<br>        topn: Number of results<br>    <br>    Returns:<br>        List of (filename, similarity_score) tuples<br>    &quot;&quot;&quot;<br>    query_vector = get_image_embeddings(query_image)<br>    <br>    search_client = SearchClient(<br>        azure_search_endpoint, <br>        index_name,<br>        AzureKeyCredential(azure_search_key)<br>    )<br>    <br>    results = search_client.search(<br>        search_text=None,<br>        vector_queries=[<br>            VectorizedQuery(<br>                vector=query_vector,<br>                k_nearest_neighbors=topn,<br>                fields=&quot;imagevector&quot;<br>            )<br>        ]<br>    )<br>    <br>    return [(doc[&quot;imagefile&quot;], doc[&quot;@search.score&quot;]) for doc in results]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*cu5LZUBpYYB-30HfHshWcQ.jpeg" /><figcaption>Visual search example using a reference image</figcaption></figure><h4>Multilingual Search Examples</h4><p>One of Embed 4’s killer features are its multilingual capability:</p><pre># English<br>results = visual_search_text(&quot;A blue shirt for a man&quot;)<br><br># French<br>results = visual_search_text(&quot;Une chemise bleue pour homme&quot;)<br><br># Chinese<br>results = visual_search_text(&quot;男士藍襯衫&quot;)<br><br># Arabic<br>results = visual_search_text(&quot;قميص أزرق للرجال&quot;)</pre><p>All queries return semantically similar results! 🌍</p><h3>Part 4: Building the Gradio Web Application</h3><p>Let’s wrap everything in a beautiful, shareable web interface:</p><pre>import gradio as gr<br><br>def unified_search(text_input, image_input, search_type, top_n):<br>    &quot;&quot;&quot;<br>    Unified search handler for both text and image queries.<br>    &quot;&quot;&quot;<br>    images_list = []<br>    imgsize = 360<br>    <br>    if search_type == &quot;Text&quot; and text_input:<br>        query_vector = get_text_embeddings(text_input)<br>        status = f&quot;🔍 Searching for: &#39;{text_input}&#39;&quot;<br>    elif search_type == &quot;Image&quot; and image_input:<br>        query_vector = get_image_embeddings(image_input)<br>        status = &quot;🖼️ Searching by image similarity&quot;<br>    else:<br>        return [], &quot;⚠️ Please provide a search query&quot;<br>    <br>    # Execute search<br>    search_client = SearchClient(<br>        azure_search_endpoint, <br>        index_name,<br>        AzureKeyCredential(azure_search_key)<br>    )<br>    <br>    results = search_client.search(<br>        search_text=None,<br>        vector_queries=[<br>            VectorizedQuery(<br>                vector=query_vector,<br>                k_nearest_neighbors=int(top_n),<br>                fields=&quot;imagevector&quot;<br>            )<br>        ]<br>    )<br>    <br>    # Fetch and display images<br>    for doc in results:<br>        blob_client = container_client.get_blob_client(doc[&quot;imagefile&quot;])<br>        blob_image = blob_client.download_blob().readall()<br>        img = Image.open(io.BytesIO(blob_image)).resize((imgsize, imgsize))<br>        caption = f&quot;Score: {doc[&#39;@search.score&#39;]:.4f}&quot;<br>        images_list.append((img, caption))<br>    <br>    return images_list, f&quot;✅ Found {len(images_list)} results&quot;<br><br># Build the interface<br>with gr.Blocks(title=&quot;Visual Search&quot;, theme=gr.themes.Soft()) as webapp:<br>    gr.Markdown(&quot;# 🔍 Multimodal Visual Search&quot;)<br>    gr.Markdown(&quot;Search our fashion catalog with text or images!&quot;)<br>    <br>    with gr.Row():<br>        with gr.Column(scale=1):<br>            search_type = gr.Radio(<br>                choices=[&quot;Text&quot;, &quot;Image&quot;],<br>                value=&quot;Text&quot;,<br>                label=&quot;Search by:&quot;<br>            )<br>            <br>            with gr.Group(visible=True) as text_group:<br>                text_input = gr.Textbox(<br>                    label=&quot;Description&quot;,<br>                    placeholder=&quot;e.g., a red dress, blue shirt...&quot;<br>                )<br>            <br>            with gr.Group(visible=False) as image_group:<br>                image_input = gr.Image(<br>                    label=&quot;Upload Image&quot;,<br>                    type=&quot;filepath&quot;<br>                )<br>            <br>            top_n = gr.Slider(<br>                minimum=1, maximum=20, value=8, step=1,<br>                label=&quot;Number of results&quot;<br>            )<br>            <br>            search_btn = gr.Button(&quot;🔍 SEARCH&quot;, variant=&quot;primary&quot;)<br>            status_msg = gr.Markdown()<br>        <br>        with gr.Column(scale=2):<br>            results_gallery = gr.Gallery(<br>                columns=4,<br>                rows=5,<br>                object_fit=&quot;cover&quot;<br>            )<br>    <br>    # Toggle input visibility<br>    def toggle_input(choice):<br>        return (<br>            gr.Group(visible=(choice == &quot;Text&quot;)),<br>            gr.Group(visible=(choice == &quot;Image&quot;))<br>        )<br>    <br>    search_type.change(<br>        toggle_input,<br>        inputs=search_type,<br>        outputs=[text_group, image_group]<br>    )<br>    <br>    search_btn.click(<br>        unified_search,<br>        inputs=[text_input, image_input, search_type, top_n],<br>        outputs=[results_gallery, status_msg]<br>    )<br><br></pre><pre># Launch<br>webapp.launch(share=True, theme=gr.themes.Soft())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDPn4Mw7C0jwSBGZLTBVrQ.jpeg" /><figcaption>Visual search example using a webapp (text input)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cH4bb1kMBzN7GHbv4x_taQ.jpeg" /><figcaption>Visual search example using a webapp (reference image)</figcaption></figure><h3>Key Takeaways</h3><ol><li>🎯 <strong>Unified Embedding Space</strong>: Cohere Embed 4 projects text and images into the same vector space, enabling true multimodal search.</li><li>🌍 <strong>Multilingual by Default</strong>: No need for translation — queries in any of 100+ languages find relevant results.</li><li>☁️ <strong>Azure Integration</strong>: Microsoft Foundry + Azure AI Search provide a scalable, production-ready infrastructure.</li><li>📦 <strong>Matryoshka Flexibility</strong>: Trade embedding dimensions for speed/storage when needed.</li><li>🚀 <strong>Easy Deployment</strong>: Gradio makes it trivial to share your search engine with stakeholders.</li></ol><h3>Documentation</h3><ul><li><strong>Cohere Embed 4 on Azure AI Foundry</strong>: <a href="https://ai.azure.com/explore/models/embed-v-4-0">Model Registry</a></li><li><strong>Azure AI Search Documentation</strong>: <a href="https://learn.microsoft.com/azure/search/vector-search-overview">Vector Search</a></li><li><strong>All code is available here:</strong> <a href="https://github.com/retkowsky/visual-search-cohere-embed-v-4-0/tree/main">retkowsky/visual-search-cohere-embed-v-4–0: Visual Search with Microsoft Foundry and Cohere Embed 4</a></li><li><strong>Fashion images dataset used in this demo</strong>: <a href="https://www.kaggle.com/datasets/tbierhance/hm-fashion-images-squared-896">Kaggle — H&amp;M Fashion Images</a></li></ul><blockquote><em>🔗 </em><strong><em>Get started now</em></strong><em>: </em><a href="https://github.com/retkowsky/visual-search-cohere-embed-v-4-0">https://github.com/retkowsky/visual-search-cohere-embed-v-4-0</a></blockquote><h3>Author</h3><p>Serge Retkowsky | <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a> | <a href="https://github.com/retkowsky">https://github.com/retkowsky</a></p><p><em>📅 Last Updated: 11-Dec-2025</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37476066e0d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Azure Content Understanding: A Complete Hands-On Guide]]></title>
            <link>https://medium.com/@sergems18/mastering-azure-content-understanding-a-complete-hands-on-guide-04a3a5eeeb52?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/04a3a5eeeb52</guid>
            <category><![CDATA[content-understanding]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[foundry]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 08:43:00 GMT</pubDate>
            <atom:updated>2025-12-03T08:43:00.143Z</atom:updated>
            <content:encoded><![CDATA[<h4>Transform unstructured documents, videos, audio, and images into structured, actionable data using Azure’s newest GA AI service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VQ0ebMD4zb0_DfUG.png" /><figcaption>Azure Content Understanding</figcaption></figure><h4>📌 Introduction</h4><p>In <strong>November 2025</strong>, Microsoft announced the <strong>General Availability</strong> of <strong>Azure Content Understanding</strong> with API version 2025-11-01. This milestone marks a significant evolution in how enterprises can process and extract intelligence from unstructured content at scale.</p><p><strong>Azure Content Understanding </strong>is a <strong>Generally Available (GA) </strong>Azure AI service that uses generative AI to transform unstructured content into structured, searchable data. This repository contains practical, ready-to-run notebooks that demonstrate various capabilities of the service across different content types.</p><p>I’ve created a comprehensive repository of <strong>Jupyter notebooks</strong> that demonstrate the full capabilities of this powerful service. Whether you’re processing invoices, analyzing videos, transcribing audio files, or extracting data from complex documents.</p><blockquote><em>🔗 </em><strong><em>Repository</em></strong><em>: </em><a href="https://github.com/retkowsky/azure-content-understanding-ga">retkowsky/azure-content-understanding-ga: Azure Content Understanding demos notebooks</a></blockquote><h4>🤔 What is Azure Content Understanding?</h4><p><strong>Azure Content Understanding</strong> is an AI service available as part of the <strong>Microsoft Foundry Resource</strong> in Azure. It uses <strong>generative AI</strong> to process and ingest content of many types into user-defined output formats.</p><p>The service offers a streamlined approach to reasoning over large amounts of unstructured data, accelerating time-to-value by generating structured output that integrates seamlessly into automation and analytical workflows.</p><h4>✨ Key Features at a Glance</h4><h4>📄 Multi-Modal Content Processing</h4><p>Azure Content Understanding processes diverse content types through a <strong>unified API</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Q5uIZiGiB_NSpb7KmSBr4g.png" /></figure><h4>🎯 Intelligent Field Extraction</h4><p>Define exactly what data you need with <strong>three flexible extraction methods</strong>:</p><blockquote><em>📥 </em><strong><em>extract</em></strong><em> — Pull values exactly as they appear in content (literal text extraction)</em></blockquote><blockquote><em>🧠 </em><strong><em>generate</em></strong><em> — Use AI to understand and synthesize complex information</em></blockquote><blockquote><em>🏷️ </em><strong><em>classify</em></strong><em> — Categorize values against predefined options using enums</em></blockquote><ul><li>✅Support for <strong>up to 200 content categories</strong> in a single analyzer</li><li>✅ <strong>Automatic document segmentation</strong> with enableSegment for multi-document files</li><li>✅ <strong>Intelligent routing</strong> to specialized analyzers based on classification results</li></ul><h4>🔧 70+ Production-Ready Prebuilt Analyzers</h4><p>Immediately available analyzers across multiple domains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*54jstTkEEu2m9jqSLCph7Q.png" /></figure><h4>🤖 Flexible Model Selection (GA Feature)</h4><p>The GA release gives you <strong>full control</strong> over AI model usage:</p><ul><li>🎛️ <strong>Choose your model</strong>: GPT-4.1, GPT-4.1-mini, or other supported models</li><li>💳 <strong>Deployment flexibility</strong>: Pay-as-you-go or Provisioned Throughput Units (PTU)</li><li>💡 <strong>Cost optimization</strong>: Select the right model for your quality/cost trade-off</li></ul><h4>📊 Confidence Scores &amp; Source Grounding</h4><p>Enable estimateFieldSourceAndConfidence for:</p><ul><li>✅ <strong>Confidence scores</strong> per extracted field</li><li>✅ <strong>Source locations</strong> with bounding box coordinates</li><li>✅ <strong>Validation support</strong> for downstream processing decisions</li></ul><h4>🔒 Enterprise Security &amp; Governance</h4><p>Production-ready security features:</p><ul><li>🔐 Microsoft Entra ID authentication</li><li>🆔 Managed identities support</li><li>🔑 Customer-managed keys</li><li>🌐 Virtual networks and private endpoints</li><li>🛡️ Content filtering with Azure AI Content Safety</li></ul><h4>💰 Transparent Pricing Model</h4><p>Clear cost components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*Tj4xVK1QCbErgtbPgWta6g.png" /><figcaption>Pricing model</figcaption></figure><h3>📋 Detailed Capabilities</h3><h4>📑 Document Processing</h4><ul><li>🔤 <strong>OCR &amp; Text Extraction</strong>: Supporting 309 printed and 12 handwritten languages</li><li>📐 <strong>Layout Analysis</strong>: Detection of paragraphs, headers, tables, figures</li><li>📊 <strong>Table Recognition</strong>: Multi-page table support with structure preservation</li><li>🔗 <strong>Hyperlink Extraction</strong>: Capture embedded links within documents</li></ul><h4>🎬 Video Analysis</h4><ul><li>🖼️ <strong>Key Frame Extraction</strong>: Intelligent sampling (~1 FPS) aligned with scene boundaries</li><li>✂️ <strong>Shot Detection</strong>: Automatic identification of camera cuts and transitions</li><li>💬 <strong>Speech Transcription</strong>: WebVTT format with precise timestamps</li><li>📝 <strong>Scene Summarization</strong>: AI-generated descriptions of visual content</li></ul><h4>🎙️ Audio Processing</h4><ul><li>🗣️ <strong>Transcription</strong>: High-accuracy speech-to-text with timestamps</li><li>👥 <strong>Speaker Diarization</strong>: Distinguish between multiple speakers</li><li>🌍 <strong>Multilingual Support</strong>: Automatic language detection</li></ul><h4>👤 Face Capabilities (Limited Access)</h4><ul><li>🔲 <strong>Face Blurring</strong>: Privacy-preserving automatic face detection</li><li>📝 <strong>Face Description</strong>: Textual descriptions of facial attributes</li></ul><h4>📓 Repository Overview</h4><p>The repository contains <strong>seven comprehensive notebooks</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*6mToUrwEAclA9jY6Vs-NuQ.png" /></figure><h4>⚙️ Getting Started: Client Setup</h4><p>All notebooks share a common setup pattern. Here’s the foundation code:</p><pre>from azure.identity import DefaultAzureCredential<br>from datetime import datetime<br>from dotenv import load_dotenv<br>from helper.content_understanding_client import AzureContentUnderstandingClient<br><br>load_dotenv(&quot;azure.env&quot;)<br>AZURE_AI_ENDPOINT = os.getenv(&quot;AZURE_AI_ENDPOINT&quot;)<br>API_VERSION = &quot;2025-11-01&quot;  # GA API version<br>GPT_4_1_DEPLOYMENT = &quot;gpt-4.1&quot;<br>GPT_4_1_MINI_DEPLOYMENT = &quot;gpt-4.1-mini&quot;<br>TEXT_EMBEDDING_3_LARGE_DEPLOYMENT = &quot;text-embedding-3-large&quot;</pre><h4>🔑 Token Provider and Client Initialization</h4><pre>def token_provider():<br>    &quot;&quot;&quot;Provides fresh Azure Cognitive Services tokens.&quot;&quot;&quot;<br>    try:<br>        credential = DefaultAzureCredential()<br>        token = credential.get_token(<br>            &quot;https://cognitiveservices.azure.com/.default&quot;)<br>        return token.token<br>    except Exception as e:<br>        print(f&quot;❌ Token acquisition failed: {e}&quot;)<br>        raise<br><br>try:<br>    if not AZURE_AI_ENDPOINT or not API_VERSION:<br>        raise ValueError(&quot;AZURE_AI_ENDPOINT and API_VERSION must be set&quot;)<br>    print(&quot;Initializing Azure Content Understanding Client...&quot;)<br>    client = AzureContentUnderstandingClient(<br>        endpoint=AZURE_AI_ENDPOINT,<br>        api_version=API_VERSION,<br>        token_provider=token_provider,<br>        x_ms_useragent=&quot;azure-ai-content-understanding-python-sample-ga&quot;)<br>    print(&quot;✅ Done&quot;)<br><br>except ValueError as e:<br>    print(f&quot;❌ Configuration error: {e}&quot;)<br>    raise<br><br>except Exception as e:<br>    print(f&quot;❌ Client creation failed: {e}&quot;)<br>    raise</pre><h4>🔧 Configuring Model Deployments</h4><pre>print(f&quot;📋 Configuring default model deployments...&quot;)<br>print(f&quot;   GPT-4.1 deployment: {GPT_4_1_DEPLOYMENT}&quot;)<br>print(f&quot;   GPT-4.1-mini deployment: {GPT_4_1_MINI_DEPLOYMENT}&quot;)<br>print(f&quot;   text-embedding-3-large deployment: {TEXT_EMBEDDING_3_LARGE_DEPLOYMENT}&quot;)<br><br>result = client.update_defaults({<br>    &quot;gpt-4.1&quot;: GPT_4_1_DEPLOYMENT,<br>    &quot;gpt-4.1-mini&quot;: GPT_4_1_MINI_DEPLOYMENT,<br>    &quot;text-embedding-3-large&quot;: TEXT_EMBEDDING_3_LARGE_DEPLOYMENT<br>})</pre><h4>1️⃣ Managing Analyzers</h4><p>The first notebook demonstrates how to <strong>create, list, and manage analyzers</strong>.</p><h4>2️⃣ Field Extraction with Prebuilt Analyzers</h4><h4>📄 Analyzing a Document</h4><pre>DOCS_DIR = &quot;documents&quot;<br>document_file = os.path.join(DOCS_DIR, &quot;contoso.pdf&quot;)<br>analyzer_id = &quot;prebuilt-document&quot;<br><br>print(f&quot;🔍 Analyzing &#39;{document_file}&#39; with &#39;{analyzer_id}&#39;...&quot;)<br>response = client.begin_analyze_binary(<br>    analyzer_id=analyzer_id,<br>    file_location=document_file,<br>)<br>print(f&quot;⏳ Please wait...&quot;)<br>analysis_result = client.poll_result(response)<br>print(f&quot;✅ Done&quot;)</pre><h4>3️⃣ Custom Field Extraction</h4><h4>🎨 Creating a Custom Invoice Analyzer</h4><pre>analyzer_id = f&quot;custom_analyzer_{datetime.today().strftime(&#39;%d%b%Y_%H%M%S&#39;)}&quot;<br><br>custom_analyzer = {<br>    &quot;baseAnalyzerId&quot;: &quot;prebuilt-document&quot;,<br>    &quot;description&quot;: &quot;Invoice analyzer for vendor info and line items&quot;,<br>    &quot;config&quot;: {<br>        &quot;returnDetails&quot;: True,<br>        &quot;enableOcr&quot;: True,<br>        &quot;enableLayout&quot;: True,<br>        &quot;estimateFieldSourceAndConfidence&quot;: True<br>    },<br>    &quot;fieldSchema&quot;: {<br>        &quot;name&quot;: &quot;InvoiceFields&quot;,<br>        &quot;fields&quot;: {<br>            &quot;VendorName&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;method&quot;: &quot;extract&quot;,<br>                &quot;description&quot;: &quot;Name of the vendor or supplier&quot;<br>            },<br>            &quot;Items&quot;: {<br>                &quot;type&quot;: &quot;array&quot;,<br>                &quot;method&quot;: &quot;generate&quot;,<br>                &quot;description&quot;: &quot;List of items on the invoice&quot;,<br>                &quot;items&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;Description&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;Item description&quot;<br>                        },<br>                        &quot;Amount&quot;: {<br>                            &quot;type&quot;: &quot;number&quot;,<br>                            &quot;description&quot;: &quot;Line total amount&quot;<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    },<br>    &quot;models&quot;: {&quot;completion&quot;: &quot;gpt-4.1&quot;}<br>}<br>response = client.begin_create_analyzer(<br>    analyzer_id=analyzer_id,<br>    analyzer_template=custom_analyzer,<br>)<br>print(f&quot;⏳ Waiting for analyzer creation...&quot;)<br>client.poll_result(response)<br>print(f&quot;✅ Done&quot;)</pre><h4>4️⃣ Document Classification</h4><h4>🏷️ Creating a Classifier with Content Categories</h4><pre>analyzer_id = f&quot;sample_classifier_{datetime.today().strftime(&#39;%d%b%Y_%H%M%S&#39;)}&quot;<br><br>content_analyzer = {<br>    &quot;baseAnalyzerId&quot;: &quot;prebuilt-document&quot;,<br>    &quot;description&quot;: f&quot;Custom classifier: {analyzer_id}&quot;,<br>    &quot;config&quot;: {<br>        &quot;returnDetails&quot;: True,<br>        &quot;enableSegment&quot;: True,<br>        &quot;contentCategories&quot;: {<br>            &quot;Loan application&quot;: {<br>                &quot;description&quot;: &quot;Documents for funding requests with financial history&quot;<br>            },<br>            &quot;Invoice&quot;: {<br>                &quot;description&quot;: &quot;Billing documents for goods or services&quot;<br>            },<br>            &quot;Bank_Statement&quot;: {<br>                &quot;description&quot;: &quot;Bank statements summarizing account activity&quot;<br>            }<br>        }<br>    },<br>    &quot;models&quot;: {&quot;completion&quot;: &quot;gpt-4.1&quot;},<br>    &quot;tags&quot;: {&quot;demo_type&quot;: &quot;url_classification&quot;}<br>}<br>print(f&quot;🔧 Creating custom classifier &#39;{analyzer_id}&#39;...&quot;)<br>response = client.begin_create_analyzer(<br>    analyzer_id=analyzer_id,<br>    analyzer_template=content_analyzer,<br>)<br>print(f&quot;⏳ Waiting for classifier creation...&quot;)<br>client.poll_result(response)<br>print(f&quot;✅ Done&quot;)</pre><h4><strong>Sample Output:</strong></h4><pre>🔹 Segment 1:<br>   📁 Category: Invoice<br>   📄 Start Page: 1<br>   📄 End Page: 1</pre><pre>🔹 Segment 2:<br>   📁 Category: Bank_Statement<br>   📄 Start Page: 2<br>   📄 End Page: 3</pre><pre>🔹 Segment 3:<br>   📁 Category: Loan application<br>   📄 Start Page: 4<br>   📄 End Page: 4</pre><h4>5️⃣ Audio Content Extraction</h4><h4>🎙️ Analyzing Audio Files</h4><pre>audio_file = &quot;documents/audio.mp3&quot;<br>analyzer_id = &#39;prebuilt-audioSearch&#39;<br><br>print(f&quot;🔍 Analyzing audio: {audio_file} with &#39;{analyzer_id}&#39;...&quot;)<br>print(f&quot;🎬 Starting audio analysis...&quot;)<br><br>analysis_response = client.begin_analyze_binary(<br>    analyzer_id=analyzer_id,<br>    file_location=audio_file,<br>)<br><br>print(f&quot;⏳ Waiting for audio analysis...&quot;)<br>analysis_result = client.poll_result(analysis_response)<br>print(f&quot;✅ Done&quot;)</pre><h4>📝 Displaying Transcription</h4><pre>contents = analysis_result.get(&quot;result&quot;, {}).get(&quot;contents&quot;, [])<br>if contents:<br>    content = contents[0]<br>    markdown = content.get(&quot;markdown&quot;, &quot;&quot;)<br>    print(markdown)</pre><p><strong>✅ Sample Output:</strong></p><pre>Transcript<br>WEBVTT<br>00:00.080 --&gt; 00:00.640<br>&lt;v Speaker 1&gt;Good day.<br>00:00.880 --&gt; 00:02.240<br>&lt;v Speaker 1&gt;Welcome to Contoso.<br>00:02.560 --&gt; 00:03.760<br>&lt;v Speaker 1&gt;My name is John Doe.<br>00:05.440 --&gt; 00:06.320<br>&lt;v Speaker 2&gt;Yes, good day.<br>00:06.640 --&gt; 00:08.160<br>&lt;v Speaker 2&gt;My name is Maria Smith.</pre><h4>6️⃣ Video Content Extraction</h4><h4>🎬 Analyzing Video Files</h4><pre>video_file = os.path.join(DOCS_DIR, &quot;video.mp4&quot;)<br>analyzer_id = &#39;prebuilt-videoSearch&#39;<br><br>print(f&quot;🔍 Analyzing video: {video_file} with &#39;{analyzer_id}&#39;...&quot;)<br>print(f&quot;🎬 Starting video analysis...&quot;)<br><br>analysis_response = client.begin_analyze_binary(<br>    analyzer_id=analyzer_id,<br>    file_location=video_file,<br>)<br><br>print(f&quot;⏳ Waiting for video analysis...&quot;)<br>analysis_result = client.poll_result(analysis_response)<br>print(f&quot;✅ Video analysis completed!&quot;)</pre><p><strong>✅ Sample Output:</strong></p><pre>Transcript<br>WEBVTT<br>00:46.320 --&gt; 00:49.920<br>&lt;Speaker 6&gt;Please confirm the patient&#39;s name, site and procedure.<br>00:50.480 --&gt; 00:55.520<br>&lt;Speaker 1&gt;Right, we&#39;ve got Mary Murray, date of birth 26/1/38.</pre><h4>💡 Best Practices</h4><h4>✅ Analyzer Selection Tips</h4><blockquote><em>🎯 </em><strong><em>Always explore prebuilt analyzers first.</em></strong><em> Build custom analyzers only when prebuilt options don’t meet your specific requirements.</em></blockquote><p>Azure Content Understanding provides <strong>70+ production-ready prebuilt analyzers</strong>:</p><ul><li>⚡ <strong>Immediately Available</strong> — No training needed</li><li>🏆 <strong>Battle-Tested</strong> — Built on thousands of real-world examples</li><li>🔄 <strong>Continuously Improved</strong> — Regularly updated by Microsoft</li><li>💰 <strong>Cost-Effective</strong> — Save development time and resources</li></ul><h4>📋 Prerequisites</h4><p>Before running these notebooks, ensure you have:</p><ul><li>1️⃣<strong>Azure Subscription</strong><a href="https://azure.microsoft.com/free/">Create one for free</a></li><li>2️⃣<strong>Azure AI Foundry Resource</strong><a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesAIFoundry">Create in Azure Portal</a></li><li>3️⃣<strong>Model Deployments</strong>GPT-4.1, GPT-4.1-mini, text-embedding-3-large</li><li>4️⃣<strong>Role Assignment</strong>Cognitive Services User role</li><li>5️⃣<strong>Python Environment</strong>Python 3.8+ with Jupyter</li></ul><h4>📚 Resources</h4><ul><li><a href="https://learn.microsoft.com/azure/ai-foundry/">Azure AI Foundry Documentation</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-services/content-understanding/overview">Azure Content Understanding</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-services/content-understanding/whats-new">Latest Updates</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-services/content-understanding/pricing-explainer">Pricing Explaine</a>r</li><li><a href="https://learn.microsoft.com/en-us/azure/ai-services/content-understanding/language-region-support">Language &amp; Region Suppor</a>t</li><li><a href="https://github.com/Azure-Samples/azure-ai-content-understanding-python">Official Python Samples</a></li><li><a href="https://github.com/Azure-Samples/azure-ai-content-understanding-dotnet">Official .NET Samples</a></li><li><a href="https://learn.microsoft.com/azure/ai-foundry/responsible-ai/content-understanding/transparency-note">Responsible AI Guidelines</a></li></ul><h3>🎯 Conclusion</h3><p><strong>Azure Content Understanding</strong> represents a significant leap forward in processing unstructured content at enterprise scale. The GA release brings:</p><ul><li>✅ <strong>Production-ready capabilities</strong></li><li>✅ <strong>Flexible model selection</strong></li><li>✅ <strong>Enhanced security</strong></li><li>✅ <strong>70+ prebuilt analyzers</strong></li></ul><p>These notebooks in this repository provide a practical foundation for exploring these capabilities. Whether you’re building document processing pipelines, video analysis systems, or multimodal search applications — these examples will help you get started quickly!</p><blockquote><em>🔗 </em><strong><em>Get started now</em></strong><em>: </em><a href="https://github.com/retkowsky/azure-content-understanding-ga"><em>github.com/retkowsky/azure-content-understanding-ga</em></a></blockquote><h3>Author</h3><p>Serge Retkowsky | <a href="/service/mailto:serge.retkowsky@microsoft.com">serge.retkowsky@microsoft.com</a> | <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a></p><p><em>📅 Last Updated: 03-Dec-2025</em></p><p><strong>#Azure #AI #ContentUnderstanding #MachineLearning #DocumentProcessing #GenerativeAI #Microsoft #Python</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04a3a5eeeb52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Instance Segmentation with Azure AutoML for Images: A Complete Guide]]></title>
            <link>https://medium.com/@sergems18/mastering-instance-segmentation-with-azure-automl-for-images-a-complete-guide-6780110e8a3b?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6780110e8a3b</guid>
            <category><![CDATA[azure-machine-learning]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[instance-segmentation]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 17:15:41 GMT</pubDate>
            <atom:updated>2025-11-14T17:15:41.175Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Serge Retkowsky</em></p><p>This article will discuss about instance segmentation vision models using AutoML for Images with Azure Machine Learning.</p><blockquote><em>Find all the code from this tutorial and more examples at:<br></em><a href="https://github.com/retkowsky/instance-segmentation-azure-automl-for-images/tree/main">retkowsky/instance-segmentation-azure-automl-for-images: Instance segmentation with AutoML for Images</a></blockquote><h3>Introduction to Instance Segmentation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TdXFvD_2qMpYzfw6" /><figcaption>Instance segmentation example using Azure AutoML for Images</figcaption></figure><p><strong>Instance segmentation</strong> is a computer vision technique that identifies each distinct object in an image at the<strong> pixel level</strong>. In other words, it not only detects objects like traditional object detection (which draws a bounding box around an object) but<em> also delineates the exact shape of each object instance by creating a segmentation mask for every individual object</em>.</p><p>This is more advanced than semantic segmentation, which labels pixels by category but doesn’t differentiate between separate objects of the same class. With instance segmentation, each object — even multiple objects of the same type — is separately identified and masked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*3km_4ev1CZ9fGY8v.jpg" /><figcaption>Computer vision — Source: <a href="https://iq.opengenus.org/instance-segmentation/">Instance Segmentation</a></figcaption></figure><h4>Common use cases</h4><p><em>Instance segmentation </em>has a wide range of applications across industries:</p><ul><li><strong>Autonomous Driving</strong>: Self-driving car systems use instance segmentation to precisely detect and classify road objects (cars, pedestrians, lane markings, traffic signs) and understand their boundaries. This pixel-level detail helps the vehicle gauge distances and free space more accurately than with boxes alone.</li><li><strong>Medical Imaging:</strong> In healthcare, instance segmentation is used to locate and outline particular structures in scans or microscope images — for example, isolating each cell in a microscopy image or delineating the exact contour of a tumor in an MRI. This helps in quantifying size or volume and tracking changes over time.</li><li><strong>Retail and Robotics: </strong>In retail analytics, instance segmentation can identify and count individual products on shelves (even if they overlap) for inventory management. In robotics and manufacturing, segmenting each object or part in a scene (and even detecting defects on them) allows robots to grasp or navigate around items with fine precision.</li><li><strong>Satellite Imagery: </strong>It can distinguish and outline each building, vehicle, or land parcel in aerial images, which is useful for urban planning or environmental monitoring.</li></ul><p>Under the hood, many modern instance segmentation models combine object detection with pixel-wise masking. A prominent example is <em>Mask R-CNN</em>, a two-stage model that first uses a detector (like Faster R-CNN) to find object bounding boxes and then predicts a precise mask for each detected instance. There are also single-stage approaches (e.g. YOLACT) that do detection and segmentation in one step for faster runtime at some cost to accuracy. Transformer-based models (like DETR) have also emerged for segmentation, but traditional CNN-based architectures with Feature Pyramid Networks (FPNs) remain popular, especially Mask R-CNN due to its balance of accuracy and reliability. In practice, the choice of model involves a trade-off between speed and accuracy: lightweight models (single-stage or smaller backbones) run faster — useful for real-time needs — while heavier models (two-stage or deeper backbones) achieve higher accuracy, critical for applications like medical diagnosis.</p><h4>Summary</h4><p><em>Instance segmentation </em>provides <em>richer</em> output than bounding boxes by delineating each object’s shape. This granular understanding of visual scenes is crucial for tasks where knowing the precise extent of objects matters — enabling more intelligent navigation, measurement, and interaction in computer vision applications.</p><h3>AutoML for Images in Azure Machine Learning</h3><p><em>Azure Machine Learning’s Automated ML (AutoML) for images</em> is a service that automatically trains computer vision models, including those for instance segmentation, without the user having to manually code the model architecture and training loop.</p><p>It leverages Azure’s cloud AI infrastructure to search for an optimal model and hyperparameter configuration for your dataset. This greatly simplifies the development of an instance segmentation model: you prepare your data, invoke AutoML with desired settings, and let Azure handle model selection, training, and tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dSNo0sciqTrSxCID" /><figcaption>AutoML for Images (Azure ML)</figcaption></figure><h3>Capabilities and Workflow</h3><p>Supported tasks and models: Azure AutoML supports several vision tasks — <em>image classification, object detection</em>, and importantly image<em> instance segmentation</em>.</p><p>For instance segmentation, AutoML currently focuses on the <strong>Mask R-CNN model family</strong> (which is a state-of-the-art approach for segmentation). In particular, it offers a range of Mask R-CNN architectures with different ResNet backbones (<em>ResNet-18, 34, 50, 101, 152</em>) and Feature Pyramid Networks (FPN).</p><p>These vary in capacity: for example, a ResNet-18 Mask R-CNN is smaller and faster (suitable if you need quicker training or inference, or have limited compute), whereas ResNet-152 is much deeper, usually yielding higher accuracy at the cost of speed and memory. By default, AutoML can start with a reasonably balanced choice (Mask R-CNN with ResNet-50 is a common default) and then optionally explore others.</p><h4><strong>Hyperparameter optimization</strong></h4><p>AutoML can perform a<strong> hyperparameter sweep</strong> to tune the model for better performance. You can enable a <em>sweep</em> (hyperparameter tuning) which will train multiple model variants with different hyperparameters (and even different backbones) to find the best combination.</p><p>AutoML supports specifying a search space — for example, trying different learning rates, optimizers (SGD, Adam, etc.), number of training epochs, image sizes, etc. — and uses strategies like random search or Bayesian optimization to explore these combinations.</p><p>You can also set an early <em>stopping policy</em> (for instance, Azure’s <em>Bandit </em>policy can terminate poor-performing trials early to save time/cost).</p><h4><strong>“Copilot” mode (model selection)</strong></h4><p>In addition to tuning hyperparameters, AutoML for images can evaluate multiple model architectures in parallel — effectively searching not just within one model type, but across different types.</p><p>In the context of instance segmentation, this could mean AutoML will try all the Mask R-CNN backbone variants (ResNet18, 34, 50, 101, 152) and see which yields the best result. The demo later refers to this as <em>“</em><strong><em>copilot mode,</em></strong><em>”</em> indicating that AutoML is exploring the full portfolio of models to pick the best one for you automatically.</p><p>This is useful if you’re not sure which model complexity is appropriate for your data; AutoML will test a diverse set (from fastest to most accurate) and report which performed best.</p><h4><strong>Workflow</strong></h4><p>Using AutoML for instance segmentation in Azure ML typically involves the following steps:</p><ul><li><strong>Data Preparation:</strong> Prepare your labeled images in the required format. Azure ML uses MLTable with JSON Lines (.jsonl) for vision tasks. For instance segmentation, your annotations (bounding polygons or masks for each object with class labels) need to be converted into a JSONL file for each dataset split (train/validation). Tools or scripts can help convert common formats (COCO, Pascal VOC) to JSONL. In our case, we will see that the data was prepared and stored in an Azure Blob Storage and referenced via MLTable. AutoML expects at least a training dataset, and you can also provide a validation dataset; if you don’t, it will by default split your training data to create one.</li><li><strong>Configure Experiment:</strong> Through the Azure ML Python SDK, you define an AutoML image job. This includes specifying the task type (image_instance_segmentation), pointing to the training and validation data MLTables, and setting the target column (in this case, &quot;label&quot; which is where the mask/box annotations are stored in the JSONL). You also choose a primary metric that AutoML will try to maximize – for segmentation, the default and most appropriate metric is <em>Mean Average Precision (mAP)</em>, which measures detection/segmentation accuracy across IoU thresholds (similar to COCO’s evaluation). Optionally, you can tag the job with descriptors (like project name or version) for tracking.</li><li><strong>Compute Resources:</strong> Select an Azure ML compute cluster with GPU capabilities to run the training. Instance segmentation models are computationally intensive; <strong>training usually requires a GPU VM</strong>. In the demo, a cluster of type Standard_NC4as_T4_v3 (with NVIDIA T4 GPU) was used. You can either create a new cluster or use an existing one. AutoML will handle distributing the training if multiple trials are run in parallel.</li><li><strong>Run AutoML:</strong> Submit the job to Azure ML. AutoML will then start the training process. If you set max_trials &gt; 1, it will run multiple training trials (each trial is a model training run with a particular hyperparameter set or model). These can run sequentially or concurrently (max_concurrent_trials) depending on your setup. During this process, AutoML logs metrics from each run (like training loss per epoch, and validation mAP, precision, recall, etc.). It may also leverage advanced features like early stopping (stopping a trial early if it&#39;s not promising) to avoid overfitting and save time. Azure ML’s tracking will record these and select the best model (the one with highest validation mAP, in our case).</li><li><strong>Outputs — Best Model &amp; Metrics</strong>: When AutoML finishes, you will have a trained model artifact for the best trial. AutoML registers this model in the workspace’s model registry if specified, making it easy to deploy later. You can review the metrics and training curves either in Azure ML Studio or via the SDK/MLflow. For instance segmentation, AutoML also outputs per-class metrics (e.g., mAP for each class, precision/recall for each class) and even plots showing how metrics improved over epochs. This is part of Azure ML’s built-in experiment tracking and model explainability features — while “explainability” in vision doesn’t mean feature importance as in tabular data, it means you get detailed insights into performance (like confusion matrices or precision-recall curves) to understand how your model is doing.</li><li><strong>Deployment (optional):</strong> With the best model ready, you can deploy it as an endpoint. Azure AutoML models can be deployed to an Azure Managed Online Endpoint with a few lines of code (or via UI). This sets up a scalable REST API where you can send images and receive predictions (segmentation results). AutoML also provides the scoring script or uses built-in scoring functionality since it knows the model type. In our case, the model is a segmentation model expecting an image input; the endpoint will handle base64-encoded images and return the predicted boxes, masks, and class labels for each detected object.</li></ul><p><strong>AutoML for images tries to streamline the entire pipeline </strong>— from data to deployment — while still allowing customization. For example, you can define your own validation strategy or even bring custom models (via the new MLflow model integration, or by specifying models from the model zoo as shown in Azure’s docs where MMDetection and HuggingFace models can be used).</p><p>But out-of-the-box, it covers the common <strong>Mask R-CNN </strong>approaches which suffice for many applications. It also automatically uses transfer learning: the segmentation models are typically initialized with pretrained weights (e.g., on COCO dataset) under the hood, which significantly helps when training on a smaller custom dataset, improving accuracy and reducing training time.</p><h4><strong>Model explainability</strong></h4><p>While interpretability in deep vision models is challenging, Azure ML provides some tools. For classification tasks, AutoML can generate feature attribution explanations using algorithms like SHAP, but for instance segmentation the concept is a bit different. Instead, <em>Explainability</em> comes from examining model metrics and outputs. In practice, you should look at mean <strong>Average Precision (mAP</strong>) as the primary metric — this combines precision and recall across IoU thresholds and is the standard for object detection/segmentation quality. High mAP means the model is both detecting objects correctly (high recall) and not littering the image with false positives (high precision).</p><p>Azure AutoML will report the mAP, and also precision and recall at the default IoU threshold (e.g. 50%). You can also dive into class-wise performance (did it do better on “car” vs “pedestrian”?), which might highlight any biases or difficulties the model has. For example, if precision on one class is much lower, you might have more false positives for that class, possibly due to class imbalance or confusing imagery. These insights guide you in improving the training data or adjusting model parameters.</p><h4><strong>Workflow Summary</strong></h4><p>In short, AutoML for instance segmentation allows you to train a sophisticated Mask R-CNN model on your dataset with minimal code.</p><p>You prepare your data and then configure the AutoML job in a few lines, specifying things like experiment name, compute, and evaluation metric. AutoML handles training (potentially trying various hyperparameters and model sizes), tracking metrics throughout.</p><p>The result is a trained model along with detailed metrics, ready to be deployed or further evaluated. This lets you focus on the data and problem, rather than on writing training loops or tuning learning rates by hand — a big productivity boost for practitioners.</p><h3>Demo Explanation</h3><p>To illustrate these concepts, let’s walk through a practical example using Azure AutoML for instance segmentation.</p><p>The demonstration is organized into three parts (corresponding to three Python scripts/notebooks) that cover the end-to-end process: <strong>(1) data preparation, (2) model training with AutoML, and (3) model inference and deployment.</strong></p><p>The use case here is segmenting objects in street-view images — specifically, identifying cars and pedestrians in pictures. We’ll explain the key steps and logic in each part of the demo, along with code snippets.</p><h4>1. Data Preparation (1 Download images files and labels)</h4><p>The first script focuses on downloading and preparing the dataset for training. In our demo, the dataset consists of street scene images taken from a research repository (<em>StreetScenes</em> or similar).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*sdH49XHn68AeQTLKbcRbOw.png" /><figcaption>Our catalog images (some samples)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*osAGB3ypwn7Y_jLgPQwSDg.png" /><figcaption>Cars distribution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*u2rEgqO5HI_c6826Mr1O3A.png" /><figcaption>Pedestrians distribution</figcaption></figure><ul><li><strong>Downloading images: </strong>The code fetches a ZIP file from a Dropbox link containing the images. For example, it uses a helper function download_dropbox_file(dropbox_url, output_filename) to download the archive. After downloading, it unzips the file to extract the images into a local directory (named &quot;images&quot;). The script confirms the download and extraction succeeded by printing file counts and perhaps listing a few files.</li><li><strong>Exploratory Data Analysis (EDA):</strong> Before diving into modeling, the script does a quick EDA on the images. It uses Python libraries like PIL and pandas to gather stats such as image dimensions, aspect ratios, file sizes, and color modes. It prints out summary statistics (like how many images, distributions of widths/heights) and even plots histograms for properties like <em>total pixels per image</em> or <em>aspect ratio frequencies</em>. For example, one plot shows the distribution of image resolutions in megapixels, and another shows common aspect ratios (e.g. 4:3, 16:9 proportions) in the dataset. This step is important to understand data characteristics — for instance, if images are extremely high-resolution, you might decide to resize or be mindful of memory usage. In our case, the EDA revealed a mix of image sizes and that most images are in standard formats (JPEG) and color (RGB).</li><li><strong>Train/Validation split:</strong> The dataset is split into training and validation sets. The code likely had JSON annotation files prepared (perhaps provided with the dataset) for training and validation. In our example, after downloading, we have two JSON Lines files: train_jsonl.jsonl and val_jsonl.jsonl in a labels directory, which contain the annotations for each image (file path plus labeled polygons for each object). The script copies these files into separate folders (training-mltable-folder and validation-mltable-folder) and then creates MLTable files in each, so that Azure ML can recognize them as MLTable datasets. An MLTable file is basically a YAML that points to the JSONL and describes how to parse it. The script programmatically writes out an MLTable specification that tells Azure ML to read the JSONL lines as the source of data. Once this is done, we effectively have two MLTable data assets ready: one for training data and one for validation data.</li><li><strong>Registering data (optional):</strong> In Azure ML, you can register datasets for reuse. The script uses Azure ML SDK to upload the images and labels to the cloud workspace. It creates (or uses) a datastore (Azure Blob Storage container) named, for instance, &quot;streetimagestore&quot;, and uploads the images/ directory there. Similarly, it may register the JSONL as a <em>Tabular Dataset</em> with the appropriate datatypes (ensuring the image paths point to the blob storage). This allows the AutoML job to access the data from the cloud. In summary, after this preparation, we have our image dataset stored and referenced in Azure ML in a format that AutoML expects.</li></ul><p><strong>The data preparation script </strong>sets the stage for AutoML by ensuring the images and annotations are in place, and gives us confidence in data quality (through EDA). At this point, we have a folder of images and two MLTable datasets: one for training (e.g., 80% of images) and one for validation (remaining 20%). Each annotation in the JSONL includes the coordinates of the polygon (mask) around each object and its label (“car” or “pedestrian”).</p><p>Labels examples (jsonl file format):</p><pre>{<br>  &quot;image_url&quot;: &quot;AmlDatastore://streetimagestore/aml_images/SSDB00537.JPG&quot;,<br>  &quot;label&quot;: [<br>    {<br>      &quot;label&quot;: &quot;car&quot;,<br>      &quot;isCrowd&quot;: false,<br>      &quot;polygon&quot;: [<br>        [<br>          0.09375,<br>          0.703125,<br>          0.53984375,<br>          0.678125,<br>          0.53984375,<br>          0.53125,<br>          0.41484375,<br>          0.478125,<br>          0.23828125,<br>          0.484375,<br>          0.21015625,<br>          0.5520833333333334,<br>          0.096875,<br>          0.59375,<br>          0.096875,<br>          0.59375<br>        ]<br>      ],<br>      &quot;bbox&quot;: [<br>        0.09375,<br>        0.478125,<br>        0.53984375,<br>        0.703125<br>      ]<br>    },<br>    {<br>      &quot;label&quot;: &quot;car&quot;,<br>      &quot;isCrowd&quot;: false,<br>      &quot;polygon&quot;: [<br>        [<br>          0.54921875,<br>          0.6572916666666667,<br>          0.55546875,<br>          0.5479166666666667,<br>          0.63046875,<br>          0.5364583333333334,<br>          0.69921875,<br>          0.478125,<br>          0.82109375,<br>          0.478125,<br>          0.83515625,<br>          0.49895833333333334,<br>          0.88515625,<br>          0.5125,<br>          0.8890625,<br>          0.6333333333333333,<br>          0.8890625,<br>          0.6333333333333333<br>        ]<br>      ],<br>      &quot;bbox&quot;: [<br>        0.54921875,<br>        0.478125,<br>        0.8890625,<br>        0.6572916666666667<br>      ]<br>    }<br>  ],<br>  &quot;label_confidence&quot;: [<br>    1.0,<br>    1.0<br>  ],<br>  &quot;image_height&quot;: 960,<br>  &quot;image_width&quot;: 1280<br>}</pre><pre>{<br>  &quot;image_url&quot;: &quot;AmlDatastore://streetimagestore/aml_images/SSDB01744.JPG&quot;,<br>  &quot;label&quot;: [<br>    {<br>      &quot;label&quot;: &quot;pedestrian&quot;,<br>      &quot;isCrowd&quot;: false,<br>      &quot;polygon&quot;: [<br>        [<br>          0.01015625,<br>          0.56875,<br>          0.01015625,<br>          0.7197916666666667,<br>          0.04296875,<br>          0.7197916666666667,<br>          0.04296875,<br>          0.5572916666666666<br>        ]<br>      ],<br>      &quot;bbox&quot;: [<br>        0.01015625,<br>        0.5572916666666666,<br>        0.04296875,<br>        0.7197916666666667<br>      ]<br>    }<br>  ],<br>  &quot;label_confidence&quot;: [<br>    1.0<br>  ],<br>  &quot;image_height&quot;: 960,<br>  &quot;image_width&quot;: 1280<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lYjIsnrv9H_Goevh" /><figcaption>Images with labels (Azure ML)</figcaption></figure><blockquote><a href="https://learn.microsoft.com/en-us/azure/machine-learning/reference-automl-images-schema?view=azureml-api-2">JSONL format for computer vision tasks — Azure Machine Learning | Microsoft Learn</a></blockquote><h4>2. AutoML Training (2 AutoML for Instance segmentation)</h4><p>The second script is the heart of the process: it uses Azure’s Python SDK to configure and run the AutoML job for instance segmentation.</p><p>Let’s break down its key components and steps:</p><ul><li><strong>Environment Setup: </strong>The script begins by loading environment variables (like subscription_id, resource_group, workspace) from a config file (azure.env). Using these, it creates an Azure ML client:</li></ul><pre>from azure.ai.ml import MLClientfrom azure.ai.ml import MLClient</pre><p>This ml_client will be our interface to work with Azure ML. It then ensures the compute cluster is available. In our case, compute_name = &quot;gpucluster&quot; refers to a GPU compute cluster.</p><ul><li><strong>Data Inputs: </strong>The MLTable datasets prepared earlier are loaded as inputs:</li></ul><pre>my_training_data_input = Input(type=AssetTypes.MLTABLE, path=&quot;path/to/training-mltable-folder&quot;)<br>my_validation_data_input = Input(type=AssetTypes.MLTABLE,</pre><p>These Input objects encapsulate our data for AutoML. The script confirms they’re set up (it might print them or their contents to verify). Now we have my_training_data_input and my_validation_data_input ready.</p><ul><li><strong>Configure AutoML job:</strong> Now the script defines the AutoML image instance segmentation job. This is done via the automl.image_instance_segmentation() function from Azure ML SDK. It provides parameters such as compute, data, and metrics.</li></ul><h4>Available models with AutoML for Instance segmentation</h4><h4>maskrcnn_resnet18_fpn</h4><ul><li>Backbone: ResNet-18 (18 layers)</li><li>Speed: ⚡⚡⚡⚡⚡ Fastest</li><li>Accuracy: ⭐⭐⭐ Good</li><li>Parameters: ~12M (Lightest)</li><li>Best for: Real-time applications, edge devices, quick prototyping</li><li>Trade-off: Lower accuracy but excellent speed and low memory usage</li></ul><h4>maskrcnn_resnet34_fpn</h4><ul><li>Backbone: ResNet-34 (34 layers)</li><li>Speed: ⚡⚡⚡⚡ Very Fast</li><li>Accuracy: ⭐⭐⭐⭐ Very Good</li><li>Parameters: ~23M</li><li>Best for: Balanced performance, production deployments with moderate resources</li><li>Trade-off: Sweet spot between speed and accuracy</li></ul><h4>maskrcnn_resnet50_fpn</h4><ul><li>Backbone: ResNet-50 (50 layers)</li><li>Speed: ⚡⚡⚡ Fast</li><li>Accuracy: ⭐⭐⭐⭐⭐ Excellent</li><li>Parameters: ~44M (Most Popular)</li><li>Best for: Most common choice — great balance of accuracy and performance</li><li>Trade-off: Industry standard, widely used and well-tested</li></ul><h4>maskrcnn_resnet101_fpn</h4><ul><li>Backbone: ResNet-101 (101 layers)</li><li>Speed: ⚡⚡ Moderate</li><li>Accuracy: ⭐⭐⭐⭐⭐⭐ Superior</li><li>Parameters: ~63M</li><li>Best for: High-accuracy requirements, complex scenes, research</li><li>Trade-off: Higher computational cost but better feature extraction</li></ul><h4>maskrcnn_resnet152_fpn</h4><ul><li>Backbone: ResNet-152 (152 layers)</li><li>Speed: ⚡ Slower</li><li>Accuracy: ⭐⭐⭐⭐⭐⭐⭐ Best</li><li>Parameters: ~78M (Heaviest)</li><li>Best for: Maximum accuracy, challenging datasets, when computational resources aren’t a constraint</li><li>Trade-off: Highest accuracy but slowest inference and highest memory usage</li></ul><p>We can use a specific model:</p><pre>singlemodel_instance_segmentation_job = automl.image_instance_segmentation(<br>    compute=compute_name,  # My GPU cluster<br>    experiment_name=exp_name,  # Azure ML job name<br>    training_data=my_training_data_input,  # Training data<br>    validation_data=my_validation_data_input,  # Validation data<br>    target_column_name=&quot;label&quot;,  # Target column name<br>    primary_metric=InstanceSegmentationPrimaryMetrics.MEAN_AVERAGE_PRECISION,  # Metric<br>    tags=tags,  # Use of descriptive tags (optional)<br>)</pre><pre>singlemodel_instance_segmentation_job.set_limits(<br>    max_trials=1,  # Only 1 here in this example.<br>    timeout_minutes=60, # Timeout in min. Default value is 7 days (max allowed is 60 days)<br>)<br><br>print(&quot;Submitting AutoML job&quot;)<br><br>returned_job = ml_client.jobs.create_or_update(<br>    singlemodel_instance_segmentation_job)<br><br>print(&quot;✅ Done&quot;)</pre><p>We can do some hyperparameter tuning as well:</p><p>This sets up an experiment named exp_name (something like &quot;street-view-automl-instance-segmentation-job-2025&quot; in the code) and tells AutoML to optimize for mean average precision. We also see that max_trials=8 and max_concurrent_trials=4 – meaning AutoML will try up to 8 different configurations and can run 4 in parallel on our cluster. The script also sets instance_seg_job.set_training_parameters(...) to enable early stopping (early_stopping=True) so that if a trial isn’t improving, it can halt it early.</p><p>In plain terms, this tells AutoML: <em>“Try using Mask R-CNN with ResNet50 FPN and with ResNet101 FPN. For each, try different initial learning rates between 1e-4 and 1e-3, experiment with optimizers (SGD, Adam, AdamW), and possibly adjust other training settings like input image size and number of epochs (15, 30, or 50).”</em> This is a fairly wide search that covers model selection and training hyperparams simultaneously. With max_trials=8, AutoML will sample 8 combinations out of this space.</p><pre>ht_instance_segmentation_job = automl.image_instance_segmentation(<br>    compute=compute_name,  # Compute instance<br>    experiment_name=exp_name,  # Experiment name<br>    training_data=my_training_data_input,  # Training images<br>    validation_data=my_validation_data_input,  # Validation images<br>    target_column_name=&quot;label&quot;,  # Target to predict<br>    primary_metric=InstanceSegmentationPrimaryMetrics.MEAN_AVERAGE_PRECISION,  # Metric<br>    tags=tags,  # Descriptive tags (optional)<br>)<br><br># Set limits<br>ht_instance_segmentation_job.set_limits(<br>    max_trials=8,  # Sets the maximum number of trials that AutoML will try.<br>    max_concurrent_trials=4,  # Sets the maximum number of trials that can run in parallel.<br>    #timeout_minutes=240,  #  Default value is 7 days (max allowed is 60 days)<br>)<br><br>ht_instance_segmentation_job.set_training_parameters(<br>    early_stopping=True,  # Enables the early stopping feature during training.<br>    evaluation_frequency=1  # How often (in epochs or iterations) the model’s performance is evaluated on the validation set during training.<br>)<br><br># Configure sweep settings<br>ht_instance_segmentation_job.set_sweep(<br>    sampling_algorithm=&quot;random&quot;,  # values are: random, grid, bayesian<br>    early_termination=BanditPolicy(<br>        evaluation_interval=2,  # The frequency (in number of iterations or epochs) at which the policy checks the performance of each trial.<br>        slack_factor=0.2,  # Determines how much worse a trial can perform compared to the best trial before being terminated.<br>        delay_evaluation=6  # Delays the start of early termination checks until after 6 iterations.<br>    ),<br>)<br><br># Define search space<br>ht_instance_segmentation_job.extend_search_space([<br>    SearchSpace(<br>        model_name=Choice([&quot;maskrcnn_resnet50_fpn&quot;, &quot;maskrcnn_resnet101_fpn&quot;]),  # Models to use<br>        learning_rate=Uniform(0.0001, 0.001),  # Randomly sampled from a uniform range. Controls the step size during optimization.<br>        optimizer=Choice([&quot;sgd&quot;, &quot;adam&quot;, &quot;adamw&quot;]),  # Chooses the optimization algorithm to update model weights.<br>        min_size=Choice([600, 800]),  # Selects the minimum input size for the model from [600, 800].<br>        number_of_epochs=Choice([15, 30, 50]),  # Picks the number of full training passes over the dataset from [15, 30, 50].<br>        warmup_cosine_lr_warmup_epochs=Choice([0, 3]),  # Adding warmup steps can stabilize training<br>    ),<br>])</pre><p>If one wanted a “copilot mode” that tests all Mask R-CNN variants, they could have included ResNet18,34,50,101,152 in the Choice for model_name and perhaps more hyperparam ranges.</p><pre>copilot_instance_segmentation_job = automl.image_instance_segmentation(<br>    compute=compute_name,  # GPU compute cluster<br>    experiment_name=exp_name,  # Experimentation name <br>    training_data=my_training_data_input,  # Training images<br>    validation_data=my_validation_data_input,  # Validation images<br>    target_column_name=&quot;label&quot;,  # Target<br>    primary_metric=&quot;MeanAveragePrecision&quot;,  # Metric<br>    tags=tags,<br>)<br><br>copilot_instance_segmentation_job.set_limits(<br>    max_trials=8,  # Sets the maximum number of trials that AutoML will try.<br>    max_concurrent_trials=4,  # Sets the maximum number of trials that can run in parallel.<br>    #timeout_minutes=420,  # Default value is 7 days (max allowed is 60 days)<br>)</pre><p>Azure ML will now queue the AutoML run. The script enters a monitoring loop, printing the job status periodically (using the statuses and emojis defined, e.g., printing a checkmark when the job completes, or intermediate statuses). This gives real-time feedback in the notebook about training progress.</p><ul><li><strong>Training process (under the hood):</strong> AutoML will spin up training runs on the compute cluster. Each trial uses the training data, trains the Mask R-CNN model for the specified epochs (unless early stopped), and evaluates on the validation set. Metrics like <em>precision</em>, <em>recall</em>, and <em>mAP</em> are computed at the end of training (and possibly after each epoch, since evaluation_frequency=1). The Azure ML logs show these metrics. Our script uses MLflow to retrieve the metrics of the best model after completion.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0nbcz6lRhKhzGwyi" /><figcaption>AutoML results (Azure ML)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HiEMjRBU-bBd6iwn" /><figcaption>AutoML results (Azure ML)</figcaption></figure><p>After the job finishes, it identifies the best run (child run) via:</p><pre>metrics = best_run.data.metrics<br><br>print(f&quot;Model Performance Summary for {best_child_run_id}\n&quot;)<br>print(f&quot;🔒 Log Loss (Train)   = {metrics[&#39;log_loss_train&#39;]:.4f}&quot;)<br>print(f&quot;✅ Precision          = {metrics[&#39;precision&#39;]:.4f}&quot;)<br>print(f&quot;🔍 Recall             = {metrics[&#39;recall&#39;]:.4f}&quot;)<br>print(f&quot;🌟 Mean Avg Precision = {metrics[&#39;mean_average_precision&#39;]:.4f}&quot;)<br><br><br><br>Model Performance Summary for silver_cherry_ct241y2jt5_HD_7<br><br>🔒 Log Loss (Train)   = 0.3444<br>✅ Precision          = 0.5067<br>🔍 Recall             = 0.9665<br>🌟 Mean Avg Precision = 0.8720</pre><p>This prints out the final Precision, Recall, and Mean Average Precision of the best model on the validation data. Precision here means the fraction of predicted object instances that were correct, while recall means the fraction of true objects that were detected by the model.</p><p>mAP is a comprehensive metric (the primary one used to rank the model) — it was likely around e.g. 0.87+ in our case (87% mAP, indicating very good overall detection/segmentation performance).</p><ul><li><strong>Results and model selection: </strong>Suppose Mask R-CNN ResNet50 with certain hyperparameters ended up the best (which is plausible due to a balance of power and not overfitting). The system would lock in that model. The code also compiled a pandas DataFrame df_automl with the best metrics from each trial, allowing a comparison between, say, the ResNet50 vs ResNet101 trial metrics. If ResNet101 was only marginally better mAP but took longer or overfit slightly (lower precision maybe), one might prefer ResNet50. These details can be observed from the logged metrics.</li><li><strong>Visualization:</strong> The notebook also visualized training curves: it downloaded the per_label_metrics.json artifact from the run (which contains, per class, the precision/recall over epochs). Using Matplotlib, it plotted charts of how precision and recall for the car and pedestrian classes improved each epoch. These showed that by the final epoch, both precision and recall were quite high for both classes (e.g., precision for cars might be 0.95+, and for pedestrians similar, with recall not far behind). Such plots help confirm the model converged and wasn’t still improving drastically (ensuring the number of epochs was sufficient). They also often reveal if one class was harder – perhaps the pedestrian curves might be slightly lower than car due to smaller objects being slightly harder to segment.</li><li><strong>Register the model: </strong>After identifying the best model, the script registers it with the workspace’s model registry, giving it a name and description (e.g., &quot;streetview-automl-instance-segmentation-cvmodel&quot;). This step packages the model (including the MLflow model files, which wrap the actual PyTorch model checkpoint) and saves it in Azure ML for easy retrieval. The code used:</li></ul><pre>model = Model(path=f&quot;azureml://jobs/{best_run_id}/outputs/artifacts/outputs/mlflow-model/&quot;,<br>              name=model_name,<br>              description=model_description,<br>              type=AssetTypes.MLFLOW_MODEL)<br>registered_model = ml_client.models.create_or_updateregistered_model = ml_client.models.create_or_update(model)</pre><p>Now the model is versioned and stored — you can refer to it later by name and version. This is good practice, as it allows deployment in the next step to pull the model from the registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vhBETWQ-SoQPV_9z" /><figcaption>Best trained model is available in the model repository of Azure ML</figcaption></figure><ul><li><strong>Deployment to endpoint: </strong>Still in the same script, they proceed to deploy the model as a real-time endpoint. They create a Managed Online Endpoint with a given name (e.g., &quot;streetview-vision-mngd-endpoint&quot;). The script calls ml_client.begin_create_or_update(endpoint) to create the endpoint (which is basically a HTTPS endpoint with an auto-scaling backend in Azure). Once the endpoint exists, a deployment is created for it, specifying the model and the compute instance type. In our case, they deploy the model to an instance type &quot;Standard_NC4as_T4_v3&quot; (one T4 GPU) and name the deployment &quot;streetview-mlflow&quot;. The deployment is then set to receive 100% of the endpoint’s traffic. This means the model is now live – the endpoint has a scoring URI where we can POST images and get back segmentation results.</li></ul><p>The script prints out the scoring URI and confirms the deployment state is healthy. By the end of this step, we have a fully trained and deployed instance segmentation model in Azure. The heavy lifting (model training and selection) was done by AutoML, and we simply orchestrated it with a few API calls and then deployed the chosen model.</p><p>With ~8 trials, AutoML likely found an optimal model that balances accuracy and complexity. The metrics presumably indicated strong performance — e.g., mAP ~0.87, meaning the model is correctly detecting and masking the vast majority of cars and pedestrians in the validation set. The best model was registered and deployed, which sets us up to test it on new images.</p><p>Before moving to inference, it’s worth highlighting AutoML took care of potential overfitting by using a separate validation set and early stopping. If our training data had any class imbalance, AutoML’s objective (mAP) inherently balances precision/recall, and Azure ML’s logging would have let us notice if one class was lagging (which might suggest bias or insufficient data for that class).</p><p>We didn’t have to manually code any of the Mask R-CNN training procedure or worry about learning rate schedules — AutoML handled it, likely using reasonable defaults (and our hyperparam sweep fine-tuned it). This demonstrates the efficiency of using AutoML for complex tasks like instance segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gnpdZSAhXKCj0VhV" /><figcaption>Deployed model (Azure ML)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5_-kMaitdwJyCfRx" /><figcaption>Deployed model (Azure ML)</figcaption></figure><h4>3. Inference and Testing (3 Instance segmentation model inferencing)</h4><p>The third script focuses on using the trained model to perform instance segmentation on images and showcasing the results. This includes calling the deployed endpoint and visualizing the predictions, as well as a simple web application to interact with the model. Here are the key parts of this script:</p><ul><li><strong>Connecting to the endpoint: </strong>Similar to the training script, it first establishes an MLClient and references the same online endpoint name (&quot;streetview-vision-mngd-endpoint&quot;). Instead of training, we will invoke the endpoint for inference. The script defines a helper get_predictions(image_file: str) -&gt; dict that reads an image file, encodes it in base64, and calls the endpoint’s REST API:</li></ul><pre>def get_predictions(image_file: str) -&gt; dict:<br>    # Read image and base64 encode<br>    with open(image_file, &quot;rb&quot;) as img:<br>        encoded_image = base64.b64encode(img.read()).decode(&quot;utf-8&quot;)<br>    # Create a JSON payload as expected by the endpoint<br>    request_json = {<br>        &quot;input_data&quot;: {<br>            &quot;columns&quot;: [&quot;image&quot;],<br>            &quot;data&quot;: [ encoded_image ]<br>        }<br>    }<br><br>    # Save payload to a file and invoke the endpoint<br>    with open(&quot;model/request.json&quot;, &quot;w&quot;) as f:<br>        json.dump(request_json, f)<br><br>    response = ml_client.online_endpoints.invoke(<br>        endpoint_name=online_endpoint_name,<br>        deployment_name=deployment_name,<br>        request_file=&quot;model/request.json&quot;<br>    )<br><br>    return json.loads(response)</pre><p>This shows how the endpoint expects input: it’s a JSON with an &quot;image&quot; column containing the base64 string of the image. The invoke() call sends this to the endpoint and returns the prediction result. The result is parsed from JSON. The output is typically a dictionary with a structure containing detected boxes, labels, and confidence scores, and possibly the segmentation polygons for each detection (since our model outputs masks). Indeed, AutoML’s standard output for instance seg might look like:</p><pre>{ &quot;boxes&quot;: [<br>      {&quot;label&quot;: &quot;car&quot;, &quot;score&quot;: 0.988, &quot;box&quot;: {&quot;topX&quot;:0.25,...}, &quot;polygon&quot;: [[...]] },<br>      {&quot;label&quot;: &quot;pedestrian&quot;, &quot;score      {&quot;label&quot;: &quot;pedestrian&quot;, &quot;score&quot;: 0.910, &quot;box&quot;: {...}, &quot;polygon&quot;: [[...]] },<br>      ... <br>  ]</pre><p>(The coordinates are typically normalized [0,1] relative to image dims.)</p><ul><li><strong>Processing prediction results: </strong>The script defines functions to interpret and visualize these results:</li><li><strong>print_results(image_file, results)</strong> – This prints a summary of detections for a given image. For example, it counts how many &quot;car&quot; and how many &quot;pedestrian&quot; were found, and prints those numbers along with a total. It also prints each detection’s label and confidence nicely. This is useful for a quick textual check. Running this on a test image might output: <em>“Detected cars = 3, Detected pedestrians = 1, Total = 4”</em>.</li><li><strong>view_results(image_path, results, min_conf=0.5)</strong> – This creates a visualization by overlaying the predicted masks and bounding boxes on the image. The code uses OpenCV and Matplotlib to draw each detection if its confidence is above min_conf (default 0.5). Each object is drawn with a colored bounding box (e.g., green for car, blue for pedestrian) and a semi-transparent mask polygon (e.g., a filled region over the object). It also labels each object with the class name and confidence percentage. The function returns the path to an image file saved with these annotations. This is extremely helpful for visually verifying that the model is doing the right thing – you can see the outlined cars and pedestrians on the image.</li><li><strong>extract_and_display_objects(image_path, predictions)</strong> – This takes the image and prediction and crops out each detected object’s region, displaying each as a separate small image. This helps to quickly see each object instance close-up.</li><li><strong>extract_and_display_polygons(image_path, predictions)</strong> – Similarly, this one extracts just the mask shape of each object (essentially applying the predicted polygon as a mask on the original image and cropping it) to show the shape of objects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*BQBo7f74BEwVnFxrvyjwdA.png" /><figcaption>Image to analyse</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*dBK6YZGTZIuCqCKYkTUKwQ.png" /><figcaption>Results from the instance segmentation model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*RYET8GeNuLwT2niBPOv1FA.png" /><figcaption>Results from the instance segmentation model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*ghcujsFpp95trreWwkVrTA.png" /><figcaption>Results from the instance segmentation model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*tlDIA5gbTzmNH_ZfiC7YfQ.png" /><figcaption>Results from the instance segmentation model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*25hoONmLvwPGK0nOzx0pQA.png" /><figcaption>Another example</figcaption></figure><p><strong>Building a simple web app (Gradio): </strong>To make the demo interactive, the script uses Gradio, a Python library that creates UI components for machine learning models easily. The code creates a Gradio Blocks interface with an image upload widget and a confidence threshold slider. When the user clicks “Run Instance Segmentation”, it will:</p><ul><li><strong>Pass the uploaded image and threshold to the </strong><strong>process_image function.</strong> This function essentially calls our get_predictions (either via file or directly on the PIL image) and then calls view_results to get an annotated image, and prepares a text summary of results (listing each detection’s label and confidence).</li><li><strong>The Gradio interface then displays the annotated image and the text summary right in the browser.</strong></li></ul><p>The UI also provides some example images (the ones in tests/) as quick demos and some tips about adjusting the confidence threshold to see how including lower-confidence predictions might add more detections (but potentially some false ones). The Gradio app is launched (with share=True to get a public link for demo).</p><p>Essentially, this allows anyone to try the model on any image — you could upload a new street scene photograph and see the segmentation output live, without any coding. This is a powerful way to showcase the model to non-technical stakeholders or in a Medium article (imagine embedding a short video of the app in use).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vw0FtvQc8tvcLdiW" /><figcaption>Gradio webapp</figcaption></figure><h3>Risks and Best Practices</h3><p>Implementing instance segmentation with AutoML (or any approach) involves considering certain risks and following best practices to mitigate them:</p><h4>1. Data Bias and Representativeness</h4><p><em>Risk:</em> The model will learn whatever biases are present in the training data. If our dataset is not representative of the real-world operating environment, the model may perform poorly on unseen scenarios or may systematically ignore certain object types in some contexts. For example, if all “pedestrian” examples in training were adults, the model might struggle with children or differently shaped pedestrians; or if the dataset mostly had light-colored cars, maybe dark-colored cars at night are harder for it (an edge case). Bias in the data can also show up as the model disproportionately failing on certain backgrounds or lighting conditions.</p><p><em>Mitigation:</em> Ensure diversity in the training data. Gather more images from different conditions — varying lighting (morning, noon, evening, night), various weather (sunny, rainy, snowy), different cities or environments — so the model sees a wide range of examples. Also, explicitly check performance on subgroups of data. In our case, we’d test the model on a subset of images with heavy pedestrian traffic to ensure it works when there are many people close together, or on highways to see if it detects cars at high density. If biases are found, incorporate those scenarios into training. Data augmentation can help too (AutoML might do some augmentation by default, like random flips or scales, but you can also add more if needed) to synthetically balance conditions.</p><p>In terms of fairness, since this is object detection, traditional demographic fairness issues are not directly relevant, but if one extends this to something like person detection in security footage, be mindful of not introducing biases that could, say, more easily detect one type of clothing over another (making sure the dataset of “pedestrians” has variety in apparel, poses, etc.). Essentially, review your data for bias and correct it before training — this is a human step AutoML cannot do for you.</p><h4>2. Overfitting</h4><p><em>Risk:</em> Overfitting occurs when the model learns the training images too specifically (including noise or minor details) and doesn’t generalize to new images. Signs of overfitting would be very high accuracy on training data but much lower on validation. In segmentation, an overfit model might, for instance, memorize backgrounds of training images — if all training pedestrians were on city sidewalks, maybe it fails to detect a pedestrian on a beach because the background is unfamiliar.</p><p><em>Mitigation:</em> Use a separate validation set (which we did) to monitor performance. AutoML by default sets aside validation data (we provided one explicitly) to track generalization. It also supports cross-validation if data is limited, which is a best practice to get a robust estimate of performance. In our training, we enabled early stopping and limited epochs which is good — you should avoid training too long if validation metrics stop improving. Another practice is to simplify the model if overfitting is observed — e.g., use ResNet50 instead of 101, or introduce regularization. AutoML tried both sizes; if the larger model had overfit, presumably its validation mAP would be worse, and AutoML would have picked the smaller one. This is indeed what may have happened given ResNet50 was chosen (perhaps ResNet101 had a slight tendency to overfit given our data size).</p><p>AutoML also performs some regularization and hyperparameter tuning that help (like searching for an optimal learning rate and maybe trying <em>dropouts or weight decay behind the scenes</em>). Ensuring you don’t overfit also ties back to data — more training data naturally helps reduce overfitting. In our case, we got lucky that ~500 images (for example) with ~1000 objects might suffice. If we saw marginal or unstable validation performance, the answer would often be “get more labeled images.”</p><h4>3. Cost Considerations</h4><p><em>Risk:</em> Training and deploying models in the cloud incurs costs. AutoML, in particular, can launch multiple training runs in parallel, which means multiple GPU machines running concurrently — costs can add up quickly if not managed. Deployment also costs money per uptime and per inference call.</p><h4>4. Model Maintenance</h4><p><em>Risk:</em> Once deployed, models can “drift” in performance if the data over time changes (e.g., new car models on the road, people wearing new styles of clothing that the model never saw, etc.). Also, as a risk, any machine learning model can occasionally fail in unexpected ways — e.g., weird reflections or shadows might cause a false detection. Relying blindly on the model in a critical system (like a self-driving car) without monitoring can be dangerous.</p><p><em>Mitigation:</em> Monitor the model’s predictions in production. Set up logging of the inference outputs and perhaps a system to flag when the model is very uncertain or when it outputs something unusual (like suddenly detecting 100 objects in a frame where usually it’s 10 — could indicate a glitch). Periodically evaluate the model on fresh data. If performance degrades or new types of errors appear, plan for re-training. With AutoML, retraining can be as simple as collecting more labeled examples for the failure cases and rerunning the pipeline. It might also be useful to schedule AutoML runs periodically (e.g., every quarter) to see if a newer model or hyperparam configuration can improve things as more data becomes available.</p><p>For our specific case, a best practice is to incorporate a test set separate from both train and val, used only for final evaluation (we implicitly did that with our informal tests). Always keep some data held-out to objectively measure performance after all tuning is done, to ensure your reported metrics (mAP ~0.92) hold on truly unseen data. This prevents overly optimistic estimates due to possibly tuning to the validation set. We should treat the numbers we have as validation performance; a final test might be slightly lower (or similar, if all went well).</p><h4>5. Deployment and Scaling Best Practices</h4><p>Although not a “risk” in terms of model accuracy, there are best practices to deploying such a model:</p><ul><li>Use Azure ML’s managed endpoints for ease, but for high-scale production, you might consider an AKS (Kubernetes) deployment if you need more control.</li><li>Ensure the endpoint is secured (we used auth_mode=&quot;key&quot;, meaning you need an API key to call it; never leave it completely open).</li><li>Test the throughput and latency under expected load. If many concurrent requests come in, monitor that the GPU is not overwhelmed. You may use autoscaling rules (Azure can scale out the number of replicas based on CPU/GPU utilization or queue length).</li><li>Optimize the model if needed: e.g., converting the trained model to ONNX format and enabling GPU acceleration can sometimes double inference speed. This might be an advanced step — Azure AutoML registers an MLflow model which typically uses PyTorch under the hood. If needed, one could extract the underlying PyTorch model and apply optimization libraries.</li><li>Keep an eye on model size: A ResNet50 Mask R-CNN model is tens of millions of parameters (~170 MB file perhaps). If deploying to edge devices or constrained env, you might need a smaller model (AutoML could be instructed to try ResNet18 which is lighter). For cloud deployment this is fine, but it’s something to consider for portability.</li></ul><h4>6. Additional Considerations — Label Quality &amp; Annotation Errors</h4><p>Bad labels (annotation errors) are a risk — if some training masks are incorrect, the model can actually be <em>better</em> than the ground truth in some cases, which will look like it’s making a mistake when it’s actually the label that’s wrong. Always double-check a subset of annotations. AutoML can’t know about label errors; it will trust the labels. Best practice is to perform data cleaning: remove or fix inconsistent labels. Tools like azure’s dataset profiling might help find issues (e.g., if an image has zero objects labeled but clearly has some). In our case, we assumed the provided annotations were good.</p><h4>7. Use of AutoML and Human-in-the-loop</h4><p>AutoML greatly simplified this project, but it’s not completely hands-off. A best practice is to review AutoML’s choices. For example, check the metrics of all trials — did one trial overfit? Did another have nearly as good performance with significantly less training time? Perhaps you might choose a slightly lower mAP model if it’s much smaller or faster — depending on project needs (e.g., ResNet18 trial might have gotten 0.90 mAP but be twice as fast; if real-time speed was critical, one could favor that). So use the AutoML results to inform decisions, not blindly.</p><p>Finally, document and version everything (AutoML tags runs with parameters, and we added tags and descriptions). This is a best practice for reproducibility. If someone else needs to reproduce the experiment or analyze why the model made a certain error, having the training logs, data version, and code saved is crucial. Azure ML automatically keeps a lot of this (the returned_job.name and the registered model with a version allows us to trace back). We should also save this final model’s evaluation (the metrics we got on test data) as a benchmark for future models.</p><h3>References and Resources</h3><p>For further reading and to deepen your understanding, here are some relevant resources:</p><ul><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/?view=azureml-api-2">Azure Machine Learning documentation | Microsoft Learn</a></li><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/concept-automated-ml?view=azureml-api-2#computer-vision-preview">What is automated ML? AutoML — Azure Machine Learning | Microsoft Learn</a></li><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models?view=azureml-api-2&amp;tabs=cli">Set up AutoML for computer vision — Azure Machine Learning | Microsoft Learn</a></li><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/component-reference-v2/image-instance-segmentation?view=azureml-api-2">AutoML Image Instance Segmentation Component in Microsoft Azure Machine Learning Designer — Azure Machine Learning | Microsoft Learn</a></li><li><a href="https://learn.microsoft.com/en-us/python/api/azure-ai-ml/azure.ai.ml.automl.imageinstancesegmentationjob?view=azure-python">azure.ai.ml.automl.ImageInstanceSegmentationJob class | Microsoft Learn</a></li><li><em>Mask R-CNN Paper (He et al. 2017):</em> <a href="https://arxiv.org/abs/1703.06870">[1703.06870] Mask R-CNN</a></li><li><a href="https://azure.microsoft.com/en-us/pricing/details/machine-learning/">Pricing — Azure Machine Learning | Microsoft Azure</a></li></ul><p>Happy detecting!</p><h3>Author</h3><p>Serge Retkowsky | <a href="/service/mailto:serge.retkowsky@microsoft.com">serge.retkowsky@microsoft.com</a> | <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a></p><h3>Code Repository</h3><blockquote><em>Find all the code from this tutorial and more examples at:<br></em><a href="https://github.com/retkowsky/instance-segmentation-azure-automl-for-images/tree/main">retkowsky/instance-segmentation-azure-automl-for-images: Instance segmentation with AutoML for Images</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6780110e8a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Swimming Pools from Satellite Images with Azure AutoML for Images]]></title>
            <link>https://medium.com/@sergems18/detecting-swimming-pools-from-satellite-images-with-azure-automl-for-images-0865708fa21b?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0865708fa21b</guid>
            <category><![CDATA[automl-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-ml]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 13:55:32 GMT</pubDate>
            <atom:updated>2025-10-30T13:55:32.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making Object Detection Accessible to Everyone</h4><p><strong>Object detection</strong> has traditionally been a complex task requiring deep expertise in machine learning, computer vision, and deep learning frameworks. But what if I told you that you could build a production-ready object detection model to identify swimming pools from satellite images in just a couple of hours?</p><p>Welcome to the world of <strong>Azure AutoML for Images</strong> — where cutting-edge computer vision meets simplicity and accessibility.</p><blockquote>All python code is available here: <a href="https://github.com/retkowsky/object-detection-azure-automl-for-images">retkowsky/object-detection-azure-automl-for-images: Object detection with Azure AutoML for Images</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*Xsjnlwbo8kc-24OG" /><figcaption>Object detection example using Azure AutoML for Images for object detection</figcaption></figure><h3>The Use Case: Swimming Pool Detection</h3><p>Imagine you’re working for a municipality, insurance company, or real estate firm. You need to identify properties with swimming pools across thousands of satellite images. Doing this manually would take weeks. Training a custom object detection model from scratch? That’s months of work requiring specialized ML expertise.</p><p>With <strong>Azure AutoML for Images</strong>, you can accomplish this in an afternoon. Let me show you how.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vkAYuR_oAKSlJKxmcqkQg.png" /><figcaption>Swimming pool use-case detection</figcaption></figure><h3>What is AutoML for Images?</h3><p>Azure AutoML for Images is a powerful feature within <strong>Azure Machine Learning</strong> that automatically:</p><p>- Selects the best model <strong>architecture </strong>(<em>YOLO, Faster R-CNN, etc.</em>)<br>- Optimizes <strong>hyperparameters </strong>through intelligent search<br>- Manages <strong>data preprocessing and augmentation</strong><br>- Trains and evaluates models on powerful <strong>GPU </strong>compute<br>- Deploys models as REST APIs <strong>for real-time inference</strong></p><p>All you need to do is provide labeled training data and configure a few simple parameters. <strong>AutoML for Images</strong> does the heavy lifting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hBw3Y2lSDvm3BNhp" /><figcaption>Azure AutoML for Images</figcaption></figure><p>A graphical user interface for <strong>AutoML for Images</strong> is available as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6O6x8cXdSYXmnsfNDsVptg.png" /><figcaption>User Interface for AutoML for Images in Azure ML</figcaption></figure><h3>What is AutoML for Images?</h3><p>AutoML for Images is a feature in <strong>Azure Machine Learning</strong> that automates the process of training computer vision models for tasks such as:</p><ul><li><strong>Image Classification</strong> (multi-class and multi-label)</li><li><strong>Object Detection</strong></li><li><strong>Instance Segmentation</strong></li></ul><p>It removes the complexity of manual model selection and hyperparameter tuning by running multiple trials in parallel, selecting the best-performing model based on your chosen metric.</p><h3>The 4-Step Journey</h3><p>Our swimming pool detection project follows a clean, four-step workflow:</p><p>1. Download Images and Labels📥<br>2. Train the Model with AutoML 🎯<br>3. Run Inference on New Images 🔍<br>4. Deploy to Edge with ONNX 🚀</p><p>Let’s dive into each step!</p><h4>Step 1: Download Images and Labels</h4><p>First, we need training data.</p><p>For object detection, this means:<br>- <strong>Images</strong>: Satellite imagery containing swimming pools<br>- <strong>Labels</strong>: Bounding box annotations in a structured format</p><p><strong>Azure AutoML for Images </strong>expects data in a specific format called <strong>MLTable </strong>with annotations in <strong>JSONL (JSON Lines) </strong>format.</p><h4>Setting Up Your Environment</h4><pre># Import essential libraries<br>from azure.ai.ml import MLClient<br>from azure.identity import DefaultAzureCredential<br>from azure.ai.ml import Input<br>from azure.ai.ml.constants import AssetTypes<br>import os<br><br># Connect to your Azure ML workspace<br>ml_client = MLClient(<br> DefaultAzureCredential(),<br> subscription_id=&quot;&lt;your-subscription-id&gt;&quot;,<br> resource_group_name=&quot;&lt;your-resource-group&gt;&quot;,<br> workspace_name=&quot;&lt;your-workspace-name&gt;&quot;<br>)<br><br>print(&quot;Connected to workspace:&quot;, ml_client.workspace_name)</pre><h4>Data Format: JSONL Annotations</h4><p>Each image needs an <strong>annotation file </strong>that looks like this:</p><pre>{<br> &quot;image_url&quot;: &quot;azureml://subscriptions/…/satellite_001.jpg&quot;,<br> &quot;label&quot;: [<br>   {<br>     &quot;label&quot;: &quot;swimming_pool&quot;,<br>     &quot;topX&quot;: 0.25,<br>     &quot;topY&quot;: 0.30,<br>     &quot;bottomX&quot;: 0.45,<br>     &quot;bottomY&quot;: 0.50,<br>     &quot;isCrowd&quot;: 0<br>   }<br> ]<br>}</pre><p>The bounding boxes are defined as <strong>normalized coordinates</strong> (0 to 1) representing the position of each swimming pool in the image.</p><h4>Uploading Your Dataset into Azure ML</h4><pre># Create training and validation data inputs<br>training_mltable_path = &quot;./data/training/&quot;<br>validation_mltable_path = &quot;./data/validation/&quot;<br><br>my_training_data_input = Input(<br>  type=AssetTypes.MLTABLE, <br>  path=training_mltable_path<br>)<br><br>my_validation_data_input = Input(<br>  type=AssetTypes.MLTABLE, <br>  path=validation_mltable_path<br>)<br><br>print(&quot;✓ Training and validation data prepared&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oNxsC4R4_Mf4G7Cw" /><figcaption>Images dataset in Azure ML</figcaption></figure><h4>Step 2: Train Your Object Detection Model</h4><p>This is where the magic happens! With just a few lines of code, AutoML will:<br>- Test multiple model architectures<br>- Tune hyperparameters automatically<br>- Find the best model for your specific dataset</p><h4>Configure Your Compute</h4><p>First, ensure you have GPU compute available (object detection models are compute-intensive):</p><pre>from azure.ai.ml.entities import AmlCompute<br><br># Create or retrieve GPU compute cluster<br><br>compute_name = &quot;gpu-cluster&quot;<br><br>try:<br>  gpu_cluster = ml_client.compute.get(compute_name)<br>  print(f&quot;Found existing compute: {compute_name}&quot;)<br>except:<br>  print(f&quot;Creating new compute: {compute_name}&quot;)<br>  gpu_cluster = AmlCompute(<br>  name=compute_name,<br>  size=&quot;Standard_NC6&quot;, # 1 GPU<br>  min_instances=0,<br>  max_instances=4,<br>)<br><br>ml_client.compute.begin_create_or_update(gpu_cluster)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XanAHfT6z3oEIvcy" /><figcaption>Azure ML GPU compute clusters</figcaption></figure><h4>Create the AutoML Job</h4><p>Now for the exciting part — creating your <strong>automated ML training job:</strong></p><pre>from azure.ai.ml import automl<br>from azure.ai.ml.automl import ObjectDetectionPrimaryMetrics<br><br># Define the AutoML object detection job<br>image_object_detection_job = automl.image_object_detection(<br>  compute=compute_name,<br>  experiment_name=&quot;swimming-pool-detection&quot;,<br>  training_data=my_training_data_input,<br>  validation_data=my_validation_data_input,<br>  target_column_name=&quot;label&quot;,<br>  primary_metric=ObjectDetectionPrimaryMetrics.MEAN_AVERAGE_PRECISION,<br>  tags={&quot;project&quot;: &quot;swimming-pools&quot;, &quot;version&quot;: &quot;1.0&quot;},<br>)<br><br>print(&quot;✓ AutoML job configured&quot;)</pre><h4>Set Training Limits</h4><p>Control how long and how many experiments <strong>AutoML</strong> runs:</p><pre># Set job limits to control training time and cost<br>image_object_detection_job.set_limits(<br>  timeout_minutes=60, # Maximum 1 hour<br>  max_trials=10, # Try 10 different configurations<br>  max_concurrent_trials=2 # Run 2 experiments in parallel<br>)<br><br>print(&quot;✓ Training limits set&quot;)</pre><h4>Define the Search Space (Optional)</h4><p>Want more control? Specify which models and hyperparameters to try:</p><pre>from azure.ai.ml.sweep import Choice, Uniform<br><br># Extend search space for specific models<br>image_object_detection_job.extend_search_space([<br>  {<br>    &quot;model_name&quot;: Choice([&quot;yolov5&quot;]),<br>    &quot;learning_rate&quot;: Uniform(0.0001, 0.01),<br>    &quot;model_size&quot;: Choice([&quot;small&quot;, &quot;medium&quot;]),<br>     },<br>  {<br>   &quot;model_name&quot;: Choice([&quot;fasterrcnn_resnet50_fpn&quot;]),<br>   &quot;learning_rate&quot;: Uniform(0.0001, 0.001),<br>   &quot;optimizer&quot;: Choice([&quot;sgd&quot;, &quot;adam&quot;, &quot;adamw&quot;]),<br>   &quot;min_size&quot;: Choice([600, 800]),<br>   }<br>  ]<br>)</pre><h4>Configure Hyperparameter Sweep</h4><p>Tell AutoML how to search for the best hyperparameters:</p><pre>from azure.ai.ml.sweep import BanditPolicy<br><br># Configure sweep strategy<br>image_object_detection_job.set_sweep(<br>  sampling_algorithm=&quot;random&quot;,<br>  early_termination=BanditPolicy(<br>  evaluation_interval=2,<br>  slack_factor=0.2,<br>  delay_evaluation=6<br>  ),<br>)<br><br>print(&quot;✓ Hyperparameter sweep configured&quot;)</pre><h4>What happens next?</h4><p>AutoML will:<br>1. Provision GPU compute resources<br>2. Train multiple models (YOLO, Faster R-CNN, etc.)<br>3. Test different hyperparameter combinations<br>4. Evaluate each model on your validation data<br>5. Select the best performing model based on mean Average Precision (mAP)</p><p>This typically takes <strong>30–90 minutes</strong> depending on your data size and compute power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ErV-KAuBApz29VlA" /><figcaption>AutoML job in Azure ML</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eYX-ftGXSW1YUhgu" /><figcaption>AutoML Job results in Azure ML</figcaption></figure><h3>Step 3: Model Inference — Detecting Pools in New Images</h3><p>Congratulations! Your model is trained. Now let’s use it to detect swimming pools in new satellite images.</p><h4>Retrieve the Best Model from the AutoML experiment</h4><pre># Get the best model from the AutoML run<br>best_child_run_id = returned_job.name + &quot;_best_model&quot;<br>best_run = ml_client.jobs.get(best_child_run_id)<br>print(f&quot;Best model run ID: {best_child_run_id}&quot;)<br>print(f&quot;Best model mAP: {best_run.properties[&#39;score&#39;]}&quot;)</pre><h4>Download the Trained Model to your local machine</h4><pre># Download the model to local directory<br>model_output_dir = &quot;./outputs&quot;<br><br>ml_client.jobs.download(<br>  name=best_child_run_id,<br>  download_path=model_output_dir,<br>  output_name=&quot;model_output&quot;<br>)<br><br>print(f&quot;✓ Model downloaded to {model_output_dir}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hLivqKmZP4da3Ejx" /><figcaption>Saved model in Azure ML</figcaption></figure><h4>Run Inference</h4><p>Now let’s detect swimming pools in a new image:</p><pre>import torch<br>from PIL import Image<br>import matplotlib.pyplot as plt<br>import matplotlib.patches as patches<br><br># Load the model<br>model_path = os.path.join(model_output_dir, &quot;model.pt&quot;)<br>model = torch.load(model_path)<br>model.eval()<br><br># Load and preprocess a new satellite image<br>test_image_path = &quot;./test_images/satellite_new_001.jpg&quot;<br>image = Image.open(test_image_path).convert(&quot;RGB&quot;)<br><br># Run inference<br>with torch.no_grad():<br>  predictions = model([image])<br>  # Extract predictions<br>  boxes = predictions[0][&#39;boxes&#39;].cpu().numpy()<br>  labels = predictions[0][&#39;labels&#39;].cpu().numpy()<br>  scores = predictions[0][&#39;scores&#39;].cpu().numpy()<br>  # Filter predictions by confidence threshold<br>  confidence_threshold = 0.5<br>  filtered_indices = scores &gt;= confidence_threshold<br>  final_boxes = boxes[filtered_indices]<br>  final_scores = scores[filtered_indices]<br>  print(f&quot;✓ Detected {len(final_boxes)} swimming pools&quot;</pre><h4>Visualize the Results</h4><pre># Visualize detections<br>fig, ax = plt.subplots(1, figsize=(12, 9))<br>ax.imshow(image)<br><br>for box, score in zip(final_boxes, final_scores):<br>  x1, y1, x2, y2 = box<br>  width = x2 - x1<br>  height = y2 - y1<br> <br>  # Draw bounding box<br>  rect = patches.Rectangle(<br>   x1, y1), width, height,<br>   linewidth=2, edgecolor=&#39;cyan&#39;, facecolor=&#39;none&#39;<br>   )<br>  ax.add_patch(rect)<br> <br>   # Add confidence score<br>   ax.text(<br>     x1, y1–5,<br>     f&#39;Pool: {score:.2f}&#39;,<br>     color=&#39;cyan&#39;,<br>     fontsize=10,<br>     weight=&#39;bold&#39;,<br>     bbox=dict(facecolor=&#39;black&#39;, alpha=0.5)<br>   )<br><br>ax.axis(&#39;off&#39;)<br>plt.title(&quot;Swimming Pool Detection Results&quot;, fontsize=16)<br>plt.tight_layout()<br>plt.savefig(&quot;detection_results.png&quot;, dpi=150, bbox_inches=&#39;tight&#39;)<br>plt.show()<br>print(&quot;✓ Visualization saved as detection_results.png&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wY0kGK851vmyHftcNgK6aA.png" /><figcaption>Inference example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myZILq2nEQ2OSoZwv6oI4A.png" /><figcaption>Exemple 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7YRYBP9vL3VNXZBIgtunA.png" /><figcaption>Exemple 2</figcaption></figure><h3>Step 4: Edge Deployment with ONNX</h3><p>Want to run your model on edge devices or in environments <strong>without Azure or cloud connectivity</strong>? Convert it to <strong>ONNX</strong> format!</p><h4>Why ONNX?</h4><p><strong>ONNX (Open Neural Network Exchange)</strong> is an open format that allows models to run on various platforms:<br>- Edge devices (IoT, drones, cameras)<br>- Mobile phones<br>- Web browsers<br>- On-premises servers</p><h4>Export to ONNX</h4><pre>from azure.ai.ml import Input, Output<br><br># Create an ONNX export job<br>onnx_export_job = ml_client.jobs.create_or_update(<br>  inputs={<br>    &quot;model_name&quot;: &quot;fasterrcnn_resnet50_fpn&quot;,<br>    &quot;batch_size&quot;: 1,<br>    &quot;height_onnx&quot;: 600,<br>    &quot;width_onnx&quot;: 800,<br>    &quot;job_name&quot;: returned_job.name,<br>    &quot;task_type&quot;: &quot;image-object-detection&quot;,<br>   }<br>)<br><br>print(&quot;✓ ONNX export job submitted&quot;)</pre><h4>Run Inference with ONNX</h4><pre>import onnxruntime as ort<br>import numpy as np<br><br># Load ONNX model<br>onnx_model_path = &quot;./outputs/model.onnx&quot;<br>session = ort.InferenceSession(onnx_model_path)<br><br># Prepare input<br>image = Image.open(test_image_path).convert(&quot;RGB&quot;)<br>image = image.resize((800, 600))<br>image_array = np.array(image).astype(np.float32)<br>image_array = np.transpose(image_array, (2, 0, 1)) # HWC to CHW<br>image_array = np.expand_dims(image_array, axis=0) # Add batch dimension<br><br># Run inference<br>input_name = session.get_inputs()[0].name<br>outputs = session.run(None, {input_name: image_array})<br>boxes = outputs[0]<br>labels = outputs[1]<br>scores = outputs[2]<br><br>print(f&quot;✓ ONNX inference complete&quot;)<br>print(f&quot;✓ Detected {len(boxes[scores &gt; 0.5])} swimming pools&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX-ZxmF5pcCv2MOOW1otDg.png" /><figcaption>ONNX example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNh7atwy9ceCC0LwXzXZ3g.png" /><figcaption>ONNX example 2</figcaption></figure><p>We can build a webapp to use the model from a graphical user interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2rXXAFO3xn6kW-1x" /><figcaption>Webapp example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dWQOGcvftL4u8822" /><figcaption>Webapp example 2</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVlC9Puc_6Vc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVlC9Puc_6Vc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVlC9Puc_6Vc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f0338f8f5d28ea5bce24e480fde2b5/href">https://medium.com/media/12f0338f8f5d28ea5bce24e480fde2b5/href</a></iframe><h3>Best Practices and Tips</h3><h4>1. Data Quality Matters</h4><p>- Use high-resolution satellite images (at least 1024x1024 pixels)<br>- Ensure diverse examples: different pool sizes, shapes, and environments<br>- Aim for at least 100–200 labeled images for good results. Then you can add more images to improve the model.</p><h4>2. Handling Small Objects</h4><p>Swimming pools in satellite images can be small. You can use <strong>tiling </strong>to improve detection using some dedicated models:</p><pre>image_object_detection_job.extend_search_space([<br> {<br>   &quot;model_name&quot;: Choice([&quot;fasterrcnn_resnet50_fpn&quot;]),<br>   &quot;tile_grid_size&quot;: Choice([&quot;3x2&quot;, &quot;5x3&quot;]),<br>   &quot;tile_overlap_ratio&quot;: 0.25,<br> }<br>])</pre><h4>3. Monitor Training Progress</h4><p>Track your training in Azure ML Studio:<br>- View real-time metrics (mAP, loss curves)<br>- Compare different model runs<br>- Visualize predictions on validation data</p><h4>4. Cost Optimization</h4><p>- Start with smaller compute (Standard_NC6) for experimentation<br>- Use max_trials=5 initially to test quickly<br>- Scale up to larger GPU clusters only when needed</p><h4>5. Model Evaluation Metrics</h4><p>Focus on these metrics:<br>- <strong>mAP (mean Average Precision)</strong>: Overall detection accuracy<br>- <strong>Recall:</strong> How many pools were found (important for completeness)<br>- <strong>Precision:</strong> How many detections were correct (important to avoid false alarms)</p><h3>Real-World Applications</h3><p>This swimming pool detection approach extends to countless use cases:</p><p>🏗️ <strong>Construction Monitoring:</strong> Detect building progress from aerial imagery <br>🚗 <strong>Parking Management:</strong> Count available parking spaces <br>🌳 <strong>Environmental Monitoring:</strong> Track deforestation or vegetation health <br>🏭 <strong>Industrial Inspection: </strong>Detect equipment or structural defects <br>🚁 <strong>Agricultural Analysis: </strong>Monitor crop health and field conditions <br>⚠️<strong> Disaster Response: </strong>Identify damaged structures after natural disasters</p><h3>Conclusion</h3><p><strong>Azure AutoML for Images</strong> democratizes object detection. You don’t need a PhD in computer vision or years of experience with deep learning frameworks. With just:</p><p>- ✅ Labeled training data<br>- ✅ Azure Machine Learning workspace<br>- ✅ Basic Python knowledge<br>- ✅ A few hours of time</p><p>You can build production-ready object detection models that rival solutions built by specialized ML teams.</p><p>The swimming pool detection example we walked through can be adapted to virtually any object detection problem. The key is having quality labeled data and letting AutoML handle the complex model training and optimization.</p><h3>Resources and Next Steps</h3><p>📚<strong> Learn More:</strong><br>- Azure AutoML for Images Documentation(<a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models">https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models</a>)<br>- Object Detection Tutorial(<a href="https://learn.microsoft.com/en-us/azure/machine-learning/tutorial-auto-train-image-models">https://learn.microsoft.com/en-us/azure/machine-learning/tutorial-auto-train-image-models</a>)<br>- Sample Notebooks on GitHub(<a href="https://github.com/Azure/azureml-examples">https://github.com/Azure/azureml-examples</a>)</p><p>🚀<strong> Try It Yourself:</strong><br>1. Clone the swimming pool detection notebooks from the repository<br>2. Set up your Azure ML workspace. Update the .env file.<br>3. Label some images using Azure ML Data Labeling(<a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-image-labeling-projects">https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-image-labeling-projects</a>)<br>4. Run the notebooks and see your model in action!</p><p>Happy detecting! 🏊‍♂️🛰️</p><h3>Author</h3><p>Serge Retkowsky | <a href="/service/mailto:serge.retkowsky@microsoft.com">serge.retkowsky@microsoft.com</a> | <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a></p><h3>Code Repository</h3><blockquote>Find all the code from this tutorial and more examples at:<br><a href="https://github.com/retkowsky/object-detection-azure-automl-for-images">retkowsky/object-detection-azure-automl-for-images: Object detection with Azure AutoML for Images</a></blockquote><h3>Documentation</h3><ul><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/concept-automated-ml">Azure AutoML for Images Overview</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models">How to Auto-Train Image Models</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-use-automl-small-object-detect">Object Detection with AutoML</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models#supported-model-algorithms">Supported Model Algorithms</a></li><li><a href="https://azure.microsoft.com/en-us/services/machine-learning/">Azure Machine Learning</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-inference-onnx-automl-image-models">ONNX Inference for AutoML Image Models</a></li><li><a href="https://docs.microsoft.com/en-us/azure/machine-learning/how-to-deploy-and-where">Deploy Models to IoT Edge</a></li><li><a href="https://onnxruntime.ai/">ONNX Runtime Documentation</a></li><li><a href="https://azure.microsoft.com/en-us/services/iot-edge/">Azure IoT Edge</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0865708fa21b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Image Classification with Azure AutoML for Images: A Practical Guide]]></title>
            <link>https://medium.com/@sergems18/simplifying-image-classification-with-azure-automl-for-images-a-practical-guide-ceb40393a8d8?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceb40393a8d8</guid>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[automl-vision]]></category>
            <category><![CDATA[azure-ml]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 07:17:31 GMT</pubDate>
            <atom:updated>2025-10-22T07:17:31.879Z</atom:updated>
            <content:encoded><![CDATA[<p>Building production-ready computer vision models has never been easier. Here’s how <strong>Azure AutoML</strong> transforms image classification from complex to simple. Azure AutoML for Images is available with Azure ML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V1OIvn1zZ3_Hf0ci" /><figcaption>Azure AutoML for Images with Azure ML</figcaption></figure><h3>The Challenge of Traditional Image Classification</h3><p>Anyone who has worked with computer vision knows the drill: you need to classify images, so you dive into TensorFlow or PyTorch, spend days architecting a convolutional neural network, experiment with dozens of hyperparameters, and hope your model generalizes well. It’s time-consuming, requires deep expertise, and often feels like searching for a needle in a haystack.</p><p>What if there was a better way?</p><h3>Enter Azure AutoML for Images</h3><p>Azure AutoML for Images is a game-changer in the computer vision space. It’s a feature within Azure Machine Learning that automatically builds high-quality vision models from your image data with minimal code. Think of it as having an experienced ML engineer working alongside you, handling all the heavy lifting while you focus on your business problem.</p><h4>What Makes AutoML for Images Special?</h4><h4>1. Automatic Model Selection</h4><p>Instead of manually choosing between <strong>ResNet, EfficientNet, or dozens of other architectures</strong>, <strong>AutoML for Images (Azure ML) </strong>evaluates multiple state-of-the-art deep learning models and selects the best one for your specific dataset. It’s like having access to an entire model zoo with an intelligent curator.</p><h4>2. Intelligent Hyperparameter Tuning</h4><p>The system doesn’t just pick a model — it optimizes it. Learning rates, batch sizes, augmentation strategies, and more are automatically tuned to squeeze out the best possible performance. What would take weeks of manual experimentation happens in hours.</p><h4>3. Built-in Best Practices</h4><p>Data preprocessing, augmentation techniques, and training strategies that would require extensive domain knowledge are pre-configured and applied automatically. You get enterprise-grade ML without needing to be an ML expert.</p><h4>Key Capabilities</h4><p>The repository demonstrates several powerful features:</p><ul><li><strong>Multi-class and Multi-label Classification: </strong>Whether you need to classify an image into a single category or tag it with multiple labels, AutoML manages both scenarios seamlessly.</li><li><strong>Format Flexibility:</strong> Works with standard image formats including JPEG and PNG, making it easy to integrate with existing datasets.</li><li><strong>Full Transparency</strong>: Unlike black-box solutions, you maintain complete visibility and control over the training process. You can monitor metrics, understand model decisions, and fine-tune as needed.</li><li><strong>Production-Ready Deployment:</strong> Once trained, models can be easily deployed to Azure endpoints, ready to serve predictions at scale.</li></ul><h3>Real-World Applications</h3><p>The practical applications are vast:</p><ul><li><strong>E-commerce</strong>: Automatically categorize product images for better search and recommendations.</li><li><strong>Healthcare</strong>: Classify medical images for diagnostic support.</li><li><strong>Manufacturing</strong>: Detect defects in production line images.</li><li><strong>Agriculture</strong>: Identify crop diseases or estimate yield from aerial imagery.</li><li><strong>Content Moderation:</strong> Automatically flag inappropriate visual content.</li></ul><h3>A Practical Example: Metal Defect Detection</h3><p>The repository includes a complete end-to-end example of detecting defects in metal surfaces — a critical quality control task in manufacturing. The notebooks demonstrate how to:</p><ol><li><strong>Download and organize image </strong>data from sources like Kaggle,</li><li>Create <strong>training </strong>and <strong>validation splits </strong>with proper directory structure,</li><li><strong>Upload data to Azure ML</strong> as versioned datasets,</li><li><strong>Configure GPU</strong> compute that scales based on demand,</li><li><strong>Train multiple models</strong> with <strong>automated hyperparameter tuning,</strong></li><li><strong>Evaluate results </strong>with comprehensive metrics and visualizations,</li><li><strong>Deploy the best model </strong>as a production-ready REST API,</li><li><strong>Export to ONNX for edge </strong>deployment scenarios.</li></ol><p>The metal defect use case is particularly instructive because it mirrors real industrial applications where quality control is critical but expertise is scarce. The notebooks show how a small team can build production-grade computer vision systems without a dedicated ML research team.</p><h3>Getting Started: What You Need</h3><p>The prerequisites are straightforward:</p><ul><li>An Azure subscription (free tier available for experimentation)</li><li>An Azure Machine Learning workspace</li><li>Python 3.7 or later</li></ul><p>That’s it. No local GPU clusters to configure, no complex deep learning frameworks to master.</p><h3>Repository Structure</h3><p>The repository is thoughtfully organized into three progressive notebooks:</p><ol><li><strong>Downloading images.ipynb</strong></li></ol><ul><li>Shows how to acquire and prepare image datasets</li><li>Demonstrates proper directory structure for classification tasks</li><li>Includes data exploration and visualization techniques</li></ul><blockquote><a href="https://github.com/retkowsky/image-classification-azure-automl-for-images/blob/main/1.%20Downloading%20images.ipynb">image-classification-azure-automl-for-images/1. Downloading images.ipynb at main · retkowsky/image-classification-azure-automl-for-images</a></blockquote><p><strong>2. Azure ML AutoML for Images.ipynb</strong></p><ul><li>The core workflow: connect to Azure ML, upload data, configure training</li><li>Covers both simple model training and advanced hyperparameter tuning</li><li>Shows how to evaluate models and select the best performing one<br>Demonstrates deployment to managed online endpoints</li></ul><blockquote><a href="https://github.com/retkowsky/image-classification-azure-automl-for-images/blob/main/2.%20Azure%20ML%20AutoML%20for%20Images.ipynb">image-classification-azure-automl-for-images/2. Azure ML AutoML for Images.ipynb at main · retkowsky/image-classification-azure-automl-for-images</a></blockquote><p><strong>3. Edge with ONNX local model.ipynb</strong></p><ul><li>Exports trained models to ONNX format</li><li>Shows how to run inference locally without cloud connectivity</li><li>Perfect for edge computing and IoT scenarios</li></ul><blockquote><a href="https://github.com/retkowsky/image-classification-azure-automl-for-images/blob/main/3.%20Edge%20with%20ONNX%20local%20model.ipynb">image-classification-azure-automl-for-images/3. Edge with ONNX local model.ipynb at main · retkowsky/image-classification-azure-automl-for-images</a></blockquote><p>Each Python notebook is self-contained with clear explanations, making it easy to understand each step of the process. You can run them sequentially to build a complete solution, or jump to specific sections relevant to your use case.</p><h3>The Developer Experience</h3><p>What sets this approach apart is the developer experience. The repository provides Python notebooks that guide you through the entire workflow. You’re not just reading documentation — you’re working with practical, runnable examples that demonstrate real scenarios.</p><p>Let’s walk through the code to see how straightforward this actually is.</p><h3>Use-case description</h3><p>This image classification model is designed to <strong>identify and classify defects on metal surfaces</strong> in a manufacturing context.</p><p>We want to classify defective images into <strong>Crazing, Inclusion, Patches, Pitted, Rolled &amp; Scratches.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgoHCG7_ypJ_8Im1HsfLkA.png" /><figcaption>Metal defects</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fi34Tk6_LLQo9dFBpubMEQ.png" /><figcaption>Metal defects</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pq3jAxil3mEuMwFBshplMA.png" /><figcaption>Metal defects</figcaption></figure><p>All code and images are available here: <a href="https://github.com/retkowsky/image-classification-azure-automl-for-images">retkowsky/image-classification-azure-automl-for-images: Azure AutoML for images — Image classification</a></p><h3>Step 1: Connect to Azure ML Workspace</h3><p>First, establish connection to your <strong>Azure ML workspace</strong> using Azure credentials:</p><pre>print(&quot;Connection to the Azure ML workspace…&quot;)<br>credential = DefaultAzureCredential()<br><br>ml_client = MLClient(<br>  credential,<br>  os.getenv(&quot;subscription_id&quot;),<br>  os.getenv(&quot;resource_group&quot;),<br>  os.getenv(&quot;workspace&quot;)<br>)<br><br>print(&quot;✅ Done&quot;)</pre><p>That’s it.</p><h3>Step 2: Upload Your Dataset</h3><p>Upload your <strong>image dataset to Azure ML.</strong> The code handles this elegantly:</p><pre>my_images = Data(<br>  path=TRAIN_DIR,<br>  type=AssetTypes.URI_FOLDER,<br>  description=&quot;Metal defects images for images classification&quot;,<br>  name=&quot;metaldefectimagesds&quot;,<br>)<br><br>uri_folder_data_asset = ml_client.data.create_or_update(my_images)<br><br>print(&quot;🖼️ Informations:&quot;)<br>print(uri_folder_data_asset)<br>print(&quot;\n🖼️ Path to folder in Blob Storage:&quot;)<br>print(uri_folder_data_asset.path)</pre><p>Your local images are now versioned data assets in Azure, ready for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*KIYV5HF1nH4i_RjsGfzKjA.png" /><figcaption>Local images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnMSs2BArJdFT_WYJIpiqg.png" /><figcaption>Azure ML Data Images</figcaption></figure><h3>Step 3: Create GPU Compute Cluster</h3><p><strong>AutoML needs compute power</strong>. Here’s how you create a GPU cluster that auto-scales:</p><pre>compute_name = &quot;gpucluster&quot;<br><br>try:<br>  _ = ml_client.compute.get(compute_name)<br>  print(&quot;✅ Found existing Azure ML compute target.&quot;)<br><br>except ResourceNotFoundError:<br>  print(f&quot;🛠️ Creating a new Azure ML compute cluster &#39;{compute_name}&#39;…&quot;)<br>  compute_config = AmlCompute(<br>   name=compute_name,<br>   type=&quot;amlcompute&quot;,<br>   size=&quot;Standard_NC16as_T4_v3&quot;, # GPU VM<br>   idle_time_before_scale_down=1200,<br>   min_instances=0, # Scale to zero when idle<br>   max_instances=4,<br>)<br> <br>ml_client.begin_create_or_update(compute_config).result()<br>print(&quot;✅ Done&quot;)</pre><p>The cluster scales from 0 to 4 instances based on workload, so you only pay for what you use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mOagkRmag4rHMe-E.jpg" /><figcaption>GPU cluster</figcaption></figure><h3>Step 4: Configure AutoML Training</h3><p>Now comes the magic. Here’s the entire configuration for an AutoML image classification job using a specific model (here a resnet34). It is possible as well to access all the available models from the image classification AutoML library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*G5P8baIRtfwnrY1k7S28eA.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models?view=azureml-api-2&amp;tabs=python#supported-model-architectures">https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models?view=azureml-api-2&amp;tabs=python#supported-model-architectures</a></figcaption></figure><pre><br>image_classification_job = automl.image_classification(<br>  compute=compute_name,<br>  experiment_name=exp_name,<br>  training_data=my_training_data_input,<br>  validation_data=my_validation_data_input,<br>  target_column_name=&quot;label&quot;,<br>)<br><br># Set training parameters<br>image_classification_job.set_limits(timeout_minutes=60)<br>image_classification_job.set_training_parameters(model_name=&quot;resnet34&quot;)</pre><p>That’s approximately 10 lines of code to configure what would traditionally require hundreds of lines and deep expertise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVxlTvVwIid8jNxtVU8U2A.png" /><figcaption>AutoML job</figcaption></figure><h3>Step 5: Hyperparameter Tuning (Optional)</h3><p>Want to explore multiple models and configurations?</p><pre>image_classification_job = automl.image_classification(<br>    compute=compute_name,  # Compute cluster<br>    experiment_name=exp_name,  # Azure ML job<br>    training_data=my_training_data_input,  # Training<br>    validation_data=my_validation_data_input,  # Validation<br>    target_column_name=&quot;label&quot;,  # Target<br>    primary_metric=ClassificationPrimaryMetrics.ACCURACY,  # Metric<br>    tags={&quot;usecase&quot;: &quot;metal defect&quot;, &quot;type&quot; : &quot;computer vision&quot;, <br>&quot;product&quot; : &quot;azure ML&quot;, &quot;ai&quot;: &quot;image classification&quot;, &quot;hyper&quot;: &quot;YES&quot;},<br>)<br><br>image_classification_job.set_limits(<br>    timeout_minutes=60,  # Timeout in min<br>    max_trials=5,  # Max model number<br>    max_concurrent_trials=2,  # Concurrent training<br>)<br><br>image_classification_job.extend_search_space([<br>    SearchSpace(<br>        model_name=Choice([&quot;vitb16r224&quot;, &quot;vits16r224&quot;]),<br>        learning_rate=Uniform(0.001, 0.01),  # LR<br>        number_of_epochs=Choice([15, 30]),  # Epoch<br>    ),<br>    SearchSpace(<br>        model_name=Choice([&quot;resnet50&quot;]),<br>        learning_rate=Uniform(0.001, 0.01),  # LR<br>        layers_to_freeze=Choice([0, 2]),  # Layers to freeze<br>    ),<br>])<br><br>image_classification_job.set_sweep(<br>    sampling_algorithm=&quot;Random&quot;,  # Random sampling to select combinations of hyperparameters. <br>    early_termination=BanditPolicy(evaluation_interval=2,  # The model is evaluated every 2 iterations.<br>                                   slack_factor=0.2,  # If a run’s performance is 20% worse than the best run so far, it may be terminated.<br>                                   delay_evaluation=6),  # The policy waits until 6 iterations have completed before starting to <br>                                                         # evaluate and potentially terminate runs.<br>)</pre><p>AutoML will now automatically try different model architectures, learning rates, and augmentation strategies to find the best configuration.</p><h3>Step 6: Launch Training</h3><p>Submit the job and monitor progress:</p><pre># Submit the job<br>returned_job = ml_client.jobs.create_or_update(image_classification_job)<br>print(f&quot;✅ Created job: {returned_job}&quot;)<br><br># Stream the logs in real-time<br>ml_client.jobs.stream(returned_job.name)</pre><p>While training runs, you can monitor metrics, view logs, and track progress through the <strong>Azure ML Studio UI</strong> or <strong>programmatically</strong>.</p><h3>Step 7: Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NPplUhduIcV43pnH.jpg" /><figcaption>Model results</figcaption></figure><h3>Step 8: Deploy to Production</h3><p>Once training completes, deploy the best model as a REST endpoint:</p><pre># Create endpoint configuration<br>online_endpoint_name = &quot;metal-defects-classification&quot;<br><br>endpoint = ManagedOnlineEndpoint(<br>  name=online_endpoint_name,<br>  description=&quot;Metal defects image classification&quot;,<br>  auth_mode=&quot;key&quot;,<br>  tags={<br>    &quot;usecase&quot;: &quot;metal defect&quot;, <br>    &quot;type&quot;: &quot;computer vision&quot;<br>   },<br>)<br><br># Deploy the endpoint<br>ml_client.online_endpoints.begin_create_or_update(endpoint).result()</pre><p><strong>Your model is now a production API endpoint, ready to classify images at scale.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gr0rDMO2tUtHqiFi.jpg" /><figcaption>Trained model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IQM4ysDHGlknclSw.jpg" /><figcaption>Deployed model</figcaption></figure><h3>Beyond the Cloud: Edge Deployment with ONNX</h3><p>One of the most powerful aspects of this approach is flexibility in deployment. The repository includes a third notebook demonstrating how to export your trained model to <strong>ONNX </strong>(<em>Open Neural Network Exchange</em>) format for edge deployment.</p><p>This means you can:</p><ul><li><strong>Deploy models on IoT devices</strong> for real-time inference without cloud connectivity</li><li><strong>Reduce latency </strong>by processing images locally on edge hardware</li><li><strong>Lower costs </strong>by eliminating constant cloud API calls</li><li><strong>Ensure privacy</strong> by keeping sensitive images on-premises</li></ul><p>The <strong>ONNX </strong>export process is straightforward and integrates seamlessly with the AutoML workflow. Your cloud-trained model can run anywhere ONNX Runtime is supported — from Raspberry Pi devices to industrial controllers.</p><pre>import onnxruntime<br><br># Load the ONNX model<br>session = onnxruntime.InferenceSession(&quot;model.onnx&quot;)<br><br># Run inference locally<br>results = session.run(None, {input_name: image_data})</pre><p>This cloud-to-edge workflow is particularly valuable for manufacturing, retail, and remote monitoring scenarios where edge processing is essential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*6ECkljUawFXAleGe5QjmdA.png" /><figcaption>Image classification using a local ONNX model</figcaption></figure><h3>Interactive webapp for image classification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TXPsnH8fheMYrQje.jpg" /><figcaption>Webapp example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FN2VavV9unfx-sbY.jpg" /><figcaption>Webapp example</figcaption></figure><h3>Interpreting model predictions</h3><p>Deployed endpoint returns base64 encoded image string if both model_explainability and visualizations are set to True.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*mmkV7VUgKgEcT_arKenAuQ.png" /><figcaption>Interpreting prediction</figcaption></figure><h3>Why This Matters</h3><p>In the AI era, the competitive advantage isn’t about who can build the most complex models — it’s about who can deploy effective solutions fastest. Azure AutoML for Images democratizes computer vision by making sophisticated ML accessible to a broader audience.</p><p>Small teams can now accomplish what previously required dedicated ML specialists. Prototypes that took months can be built in days. And the quality? Often on par with or better than manually crafted solutions, thanks to AutoML’s systematic approach and access to cutting-edge techniques.</p><h3>What the Code Reveals</h3><p>Looking at the actual implementation reveals several important insights:</p><ul><li><strong>Minimal Boilerplate:</strong> The entire training pipeline — from data upload to model deployment — requires less than 50 lines of meaningful code. Compare this to traditional PyTorch or TensorFlow implementations that often exceed several hundred lines.</li><li><strong>Built-in Best Practices: </strong>Notice how the code automatically manages concerns like data versioning, experiment tracking, and compute auto-scaling. These aren’t afterthoughts — they’re integral to the platform.</li><li><strong>Production-Ready from Day One: </strong>The deployed endpoint isn’t a prototype. It includes authentication, scaling, monitoring, and all the infrastructure needed for production workloads. You’re building production systems, not demos.</li><li><strong>Flexibility Without Complexity: </strong>The simple API hides complexity without sacrificing control. Need to specify a particular model architecture? One parameter. Want hyperparameter tuning? Add a few lines. The abstraction level is perfectly calibrated.</li><li><strong>Observable and Debuggable: </strong>The `.stream()` method and comprehensive logging mean you’re never in the dark about what’s happening. You can monitor training progress, inspect metrics, and debug issues — all critical for real projects.</li></ul><h3>The Cost of Complexity</h3><p>Traditional ML projects fail not because of technology limitations but because of complexity. The learning curve is steep, the iteration cycles are long, and the resource requirements are high. By abstracting away this complexity, AutoML for Images changes the economics of computer vision projects.</p><p>You can now:</p><ul><li><strong>Validate ideas quickly:</strong> Test whether image classification solves your problem before committing significant resources</li><li><strong>Iterate faster: </strong>Experiment with different approaches in hours rather than weeks</li><li><strong>Scale expertise: </strong>Enable more team members to work with computer vision, not just ML specialists</li></ul><h3>Conclusion</h3><p>Image classification is a fundamental building block for countless AI applications. <strong>Azure AutoML for Images </strong>makes it accessible, practical, and production-ready. Whether you’re a seasoned data scientist looking to accelerate your workflow or a developer taking your first steps into computer vision, this approach offers a compelling path forward.</p><p>The future of ML isn’t about writing more complex code — it’s about writing smarter code that leverages powerful platforms to deliver business value faster. This repository shows you exactly how to do that.</p><h3>Practical Tips from the Code</h3><p>After reviewing the notebooks, here are some key takeaways for your own projects:</p><ul><li><strong>Start with a Single Model: </strong>The basic configuration with `model_name=”resnet34&quot;` is perfect for initial experiments. Only move to hyperparameter sweeps once you’ve validated your data and use case.</li><li><strong>Use Tags Strategically: </strong>The code demonstrates adding tags to jobs and endpoints (e.g., `”usecase”: “metal defect”`). This becomes invaluable when managing multiple experiments and models in production.</li><li><strong>Leverage Auto-Scaling:</strong> The compute configuration with `min_instances=0` means you’re not paying for idle resources. The cluster scales up when needed and scales down to zero when idle.</li><li><strong>Monitor Training Live: </strong>The `ml_client.jobs.stream()` method is your best friend during development. You see exactly what’s happening and can catch issues early.</li><li><strong>Version Your Data: </strong>Creating named data assets (`name=”metaldefectimagesds”`) means your experiments are reproducible. You can always trace back which data version produced which model.</li><li><strong>Think Cloud-to-Edge:</strong> Even if you’re deploying to the cloud initially, the ONNX export capability gives you flexibility for future edge scenarios without retraining.</li></ul><h3>Resources</h3><ul><li>Azure ML: <a href="https://azure.microsoft.com/en-us/products/machine-learning">https://azure.microsoft.com/en-us/products/machine-learning</a></li><li>Demos notebooks: <a href="https://github.com/retkowsky/image-classification-azure-automl-for-images">https://github.com/retkowsky/image-classification-azure-automl-for-images</a></li><li>AutoML for Images documentation: <a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models">https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models</a></li><li>Available models: <a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-auto-train-image-models?view=azureml-api-2&amp;tabs=python#supported-model-architectures">Set up AutoML for computer vision — Azure Machine Learning | Microsoft Learn</a></li><li>Connect with the author: <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceb40393a8d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom Object Detection Models with Azure AI Custom Vision: A hands-on demo]]></title>
            <link>https://medium.com/@sergems18/building-custom-object-detection-models-with-azure-ai-custom-vision-a-hands-on-demo-195c70227985?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/195c70227985</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-ai-services]]></category>
            <category><![CDATA[azure-custom-vision]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 10:02:11 GMT</pubDate>
            <atom:updated>2025-10-10T11:21:20.904Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Detecting Swimming Pools from Aerial Images — A Practical Walkthrough</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGyIaB4SM8Jwf7vR64JSEg.jpeg" /><figcaption>Swimming pool detection</figcaption></figure><p>As a data scientist working with <strong>Azure AI services</strong>, I’ve found that one of the most powerful yet underutilized tools in the Azure ecosystem is <strong>Azure AI Custom Vision.</strong></p><p>In this article, I’ll walk you through a complete object detection project I built: <strong>detecting swimming pools from aerial imagery using Azure AI Custom Vision.</strong></p><p>This demo showcases how you can leverage pre-labeled datasets and build production-ready object detection models without writing extensive (not sure!) deep learning code.</p><blockquote><strong>All my notebooks and Python code</strong> are available on <a href="https://github.com/retkowsky/SwimmingPoolDetection"><strong>GitHub</strong></a><strong> </strong>for you to explore and adapt.</blockquote><h3><strong>I. Why Swimming Pool Detection?</strong></h3><p>The use case may seem niche, but it represents a class of real-world problems where organizations need to:</p><ul><li><strong>Identify specific objects in large-scale aerial or satellite imagery,</strong></li><li><strong>Automate manual inspection processes,</strong></li><li><strong>Ensure compliance (in this case, for water authority registrations or others),</strong></li><li><strong>Quality control,</strong></li><li><strong>Scale detection across thousands or millions of images</strong>.</li></ul><p>The principles I demonstrate here apply equally to detecting solar panels, construction sites, agricultural features, defects in quality control applications, or any distinct object visible from above.</p><h3><strong>II. The Images dataset</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*VsQNg5dQjbPI6i7644CaOg.png" /><figcaption>Training images</figcaption></figure><p>Rather than spending weeks collecting and labeling images, I used an existing dataset from <strong>Kaggle</strong>: the <a href="https://www.kaggle.com/alexj21/swimming-pool-512x512/metadata">Swimming Pool 512x512 dataset</a> shared by <strong>Alex</strong>. Thanks!</p><p>This dataset contains <strong>aerial images with labeled swimming pools</strong> — exactly what I needed. The only thing is to be able to import the images and the labels directly into Azure AI Custom Vision.</p><p><strong>Key lesson</strong>: Always check if quality labeled datasets already exist for your domain before investing in data collection. Platforms like Kaggle, Roboflow Universe, and Open Images can (sometimes) save months of work.</p><h4><strong>Notebook 1: Download Images Files</strong></h4><p><strong>Purpose</strong>: Import the Kaggle dataset and prepare it for Azure AI Custom Vision</p><p>In this notebook, I directly import the existing labeled dataset from Kaggle into an Azure AI Custom Vision project using <a href="https://github.com/pylabel-project/pylabel"><strong>pylabel</strong></a>. This is a huge time-saver — <strong>I don’t need to manually draw bounding boxes in the Azure Custom Vision interface because the dataset already includes annotations.</strong></p><h4><strong>What happens in this notebook:</strong></h4><ul><li>Download the swimming pool dataset from Kaggle,</li><li>Convert the annotations to a format compatible with Azure AI Custom Vision,</li><li>Validate image quality and annotation accuracy,</li><li>Prepare the data structure for upload.</li></ul><h4><strong>Key code pattern</strong></h4><pre># Using PyLabel to convert annotations<br>from pylabel import importer<br><br>dataset = importer.ImportVOC(path=LABELS_DIR,<br>  path_to_images=&quot;../png/&quot;,<br>  name=&quot;swimmingpool&quot;<br>)<br></pre><p>The beauty of <strong>PyLabel </strong>is that it handles the complexity of format conversion. Whether your data comes from <strong>COCO, YOLO, Pascal VOC, or other formats, PyLabel can convert it to what Azure AI Custom Vision expects. </strong>This is great.</p><h4><strong>Understanding the Data Structure</strong></h4><p>For object detection in Azure Custom Vision, each image needs <strong>region annotations</strong>. A region is defined by normalized coordinates (values between 0 and 1):</p><pre># Example region format for a swimming pool<br>region = {<br>  &quot;left&quot;: 0.2, # Left edge (20% from left)<br>  &quot;top&quot;: 0.3, # Top edge (30% from top)<br>  &quot;width&quot;: 0.4, # Width (40% of image width)<br>  &quot;height&quot;: 0.3 # Height (30% of image height)<br>}</pre><p>These normalized coordinates make the annotations resolution-independent, which is crucial when working with aerial imagery at different scales.</p><h3><strong>III. Model training</strong></h3><p><strong>Purpose</strong>: Train the object detection model using Azure Custom Vision. I can use the no-code interface or using the Python SDK. Here I will use the Python SDK.</p><p>This is where the magic happens — and it requires virtually no code. I use the Azure Custom Vision SDK (or you can use the user interface http://customvision.ai) to:</p><ol><li><strong>Create a new project</strong> and select “Object Detection” as the project type.</li><li><strong>Upload the prepared images</strong> with their annotations.</li><li><strong>Review the annotations</strong> to ensure quality.</li><li><strong>Click “Train”</strong> and wait a few minutes.</li></ol><p>That’s it.</p><p><strong>Azure AI Custom Vision</strong> handles:</p><ul><li>Selecting an appropriate deep learning architecture,</li><li>Splitting data into training and validation sets,</li><li>Training the model with transfer learning,</li><li>Computing performance metrics (precision, recall, mAP),</li><li>Model deployment.</li></ul><h4><strong>What I document in this notebook</strong></h4><ul><li>Screenshots of the Custom Vision interface workflow.</li><li>Performance metrics after training.</li><li>Quick threshold adjustments for precision/recall trade-offs.</li><li>Explanations of what each metric means in practice.</li><li>Batch predictions.</li><li>Gradio webapp to implement the deployed model into a custom graphical user interface.</li></ul><p>The model I trained achieved approximately 83% precision and 98% for recall. For a proof-of-concept, that’s excellent.</p><h4><strong>Understanding the metrics</strong></h4><ul><li><strong>Precision (83%)</strong> Of all the objects my model predicted as swimming pools, around 83% were actually swimming pools. Low false positive rate.</li><li><strong>Recall (98%)</strong>: Of all the actual swimming pools in the images, my model detected 98%.</li></ul><p>We can improve the results using more images.</p><p><strong>Once the model is trained and published in Azure AI Custom Vision using the UI or the Python SDK, I can call it programmatically.</strong></p><h4><strong>Core Azure Custom Vision SDK Functions</strong></h4><p>The Azure Custom Vision Python SDK provides two main client classes:</p><ol><li><strong>CustomVisionTrainingClient</strong>: For creating projects, uploading images, training models.</li><li><strong>CustomVisionPredictionClient</strong>: For making predictions with trained models.</li></ol><h4><strong>Setting up the clients</strong></h4><pre># Azure AI Custom Vision training client<br>training_credentials = ApiKeyCredentials(in_headers={&quot;Training-key&quot;: training_key})<br>trainer = CustomVisionTrainingClient(training_endpoint, training_credentials)<br><br># Azure AI Custom Vision prediction client<br>prediction_credentials = ApiKeyCredentials(in_headers={&quot;Prediction-key&quot;: prediction_key})<br>predictor = CustomVisionPredictionClient(prediction_endpoint, prediction_credentials)</pre><h4><strong>Key SDK Functions I Use</strong></h4><ol><li><strong>Getting Domain Information</strong></li></ol><pre>obj_detection_domain = next(<br>domain for domain in trainer.get_domains()<br>if domain.type == &quot;ObjectDetection&quot; and domain.name == &quot;General&quot;<br>)<br><br># Available domains: General, Logo, Products, Retail, General (compact)</pre><p><strong>2. Creating a Project (if done programmatically)</strong></p><pre># Create new object detection project<br>project = trainer.create_project(project_name,<br>  domain_id=obj_detection_domain.id,<br>  description=project_description<br>)</pre><p><strong>3. Creating Tags</strong></p><pre># Create tags for the objects you want to detect<br>for class_name in dataset.analyze.classes:<br>  tag = trainer.create_tag(project.id, class_name)<br>  tags[class_name] = tag</pre><p><strong>4. Uploading Images with Regions</strong></p><pre>success, fail = upload_images_to_azure_custom_vision(<br>  dataset=dataset,<br>  trainer=trainer,<br>  project=project,<br>  tags=tags,<br>  project_name=project_name,<br>  batch_size=64, # 64 images per batch is the max value for Azure AI Custom Vision.<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9rr9rRvmw3TMpn3DUJghA.png" /><figcaption>Azure AI Custom Vision project with the images and tags</figcaption></figure><p><strong>6. Training the Model</strong></p><pre>iteration = model_training(project_id, display_interval=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cCtoBNVNBmeCS25hFFnNA.png" /><figcaption>Metrics</figcaption></figure><p><strong>7. Publishing the Trained Iteration</strong></p><pre>trainer.publish_iteration(project_id, iteration_ids_list[0], publish_iteration_name, prediction_resource_id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1Z1XkGG3x3fLqNsZBh5gQ.png" /><figcaption>Prediction endpoint</figcaption></figure><p><strong>8. Getting Model Performance Metrics</strong></p><pre># Get all iterations<br>iterations = trainer.get_iterations(project_id)<br>iteration_ids_list = []<br><br>for iteration in iterations:<br>  print(f&quot;🆔 Iteration ID: {iteration.id}&quot;)<br>  print(f&quot;🏷️ Name: {iteration.name}&quot;)<br>  print(f&quot;📊 Status: {iteration.status}&quot;)<br>  iteration_ids_list.append(iteration.id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*7QskC58_43G_Kwc8FgROxQ.png" /><figcaption>Model metrics</figcaption></figure><p><strong>Making predictions on new images:</strong></p><pre>image_file = os.path.join(TEST_DIR, &quot;test_1.jpg&quot;)<br>img = Image.open(image_file)<br><br>display(img)<br><br>output_image_file, predictions_list = get_predictions(project_id, publish_iteration_name, image_file, RESULTS_DIR)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6a19QxJ6EpkZ-SdARLzBtQ.png" /><figcaption>Test 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*kbfT4qvOETzG8oFMdDs_rw.png" /><figcaption>Predictions on image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hPilGVUxl6INqJRLysndkA.png" /><figcaption>Test 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tqVSKGMKkulLuu1haNKzjA.png" /><figcaption>Predictions on image 2</figcaption></figure><p>Using the Azure AI Custom Vision Portal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfCj9Jqb3vulntbS4VUN7w.png" /><figcaption>Example 1 using Azure Custom Vision portal</figcaption></figure><h4><strong>9. Gradio Webapp</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*iPlpbognPz1WFghyF4S12g.png" /><figcaption>Example 1 using a gradio webapp</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPj3rQ1xQ8JY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPj3rQ1xQ8JY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPj3rQ1xQ8JY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a598998bb31194ce701bf06d2a49f4c7/href">https://medium.com/media/a598998bb31194ce701bf06d2a49f4c7/href</a></iframe><p><strong>IV. Key features I demonstrate</strong></p><ul><li><strong>Two prediction methods</strong>: detect_image() for files and detect_image_url() for URLs.</li><li><strong>Batch processing</strong> multiple images efficiently.</li><li><strong>Visualizing detections</strong> with bounding boxes and confidence scores.</li><li><strong>Adjusting confidence thresholds</strong> based on use case requirements.</li><li><strong>Batch predictions for non-interactive purposes.</strong></li><li><strong>Exporting results</strong> to JSON for further analysis.</li><li><strong>Gradio webapp</strong>.</li></ul><h3><strong>V. Azure Custom Vision SDK Architecture</strong></h3><p>Understanding the SDK architecture helped me build more robust applications:</p><h4><strong>Two Separate Client Libraries</strong></h4><p>Azure Custom Vision uses a clean separation between training and prediction:</p><pre>pip install azure-cognitiveservices-vision-customvision</pre><p>This single package includes both:</p><ul><li><strong>Training SDK</strong>: azure.cognitiveservices.vision.customvision.training</li><li><strong>Prediction SDK</strong>: azure.cognitiveservices.vision.customvision.prediction</li><li><strong>Authentication Pattern</strong></li></ul><p><strong>Azure Custom Vision requires two separate resources:</strong></p><ol><li><strong>Training Resource</strong>: For creating projects, uploading images, and training models.</li><li><strong>Prediction Resource</strong>: For making predictions with published models.</li></ol><p>This separation allows you to:</p><ul><li>Scale training and prediction independently.</li><li>Use different pricing tiers for each.</li><li>Share prediction endpoints across multiple projects.</li><li>Keep training costs separate from inference costs.</li></ul><h3><strong>VI. Best practices I follow</strong></h3><ul><li>Always use environment variables for keys and endpoints.</li><li>Implement retry logic for network failures.</li><li>Check upload results for each image in a batch.</li><li>Monitor training status with appropriate sleep intervals.</li><li>Validate predictions against confidence thresholds.</li><li>Log all API calls for debugging and monitoring.</li></ul><h3><strong>VII. What I Learned: Practical Insights from Using the SDK</strong></h3><h4>1. Images</h4><p>I achieved good results with just few images.</p><p>The key was variety:</p><ul><li>Different pool shapes (rectangular, kidney, circular),</li><li>Various lighting conditions and shadows,</li><li>Different backgrounds (urban, suburban, rural),</li><li>Multiple scales and viewing angles.</li></ul><h4><strong>2. The No-Code Interface Is Production-Ready</strong></h4><p>The no-code interface is available. But as you can see, I used most of the times the python SDK.</p><h4><strong>3. Transfer Learning Is Powerful</strong></h4><p>Azure Custom Vision uses transfer learning from models pre-trained on massive datasets. This means my images benefited from knowledge learned from millions of other images. That’s why we can train effective models with relatively small datasets.</p><h4><strong>4. Domain Selection Matters</strong></h4><p>Custom Vision offers specialized domains (General, Retail, Landmarks, etc.). For aerial imagery, the “General (compact)” domain worked well because it’s optimized for diverse object types and allows edge deployment if needed.</p><h4><strong>5. Iteration Is Key</strong></h4><p>My first model wasn’t perfect. I identified failure patterns:</p><ul><li>Above-ground pools were sometimes missed,</li><li>Blue tarps occasionally caused false positives,</li><li>Heavily shadowed pools had lower detection rates.</li></ul><p>I added targeted examples for these edge cases and retrained. The second iteration improved significantly.</p><h3><strong>VIII. Integration Possibilities</strong></h3><p>My notebooks demonstrate standalone prediction, but Azure Custom Vision integrates seamlessly with:</p><p><strong>Azure Functions</strong>: Create serverless image processing pipelines triggered by blob storage uploads.</p><p><strong>Azure Logic Apps</strong>: Build no-code workflows that process images and alert stakeholders.</p><p><strong>Power BI</strong>: Visualize detection results and analytics dashboards.</p><p><strong>Edge</strong>: Deploy models to drones for real-time aerial analysis.</p><h3><strong>IX. Limitations and When to Look Elsewhere</strong></h3><p>Azure Custom Vision is fantastic for many use cases, but I encountered scenarios where other tools are better:</p><p><strong>Small objects (&lt; 5% of image)</strong>: Consider Azure ML.</p><p><strong>Subtle defect detection</strong>: Custom Vision isn’t optimized for minor variations; consider Azure Machine Learning with custom models.</p><p><strong>Extreme class imbalance</strong>: If swimming pools appear in only 1% of images, you’ll need special data augmentation strategies.</p><p><strong>Research-grade accuracy requirements</strong>: For innovative performance, Azure ML AutoML for Images offers more control.</p><h3><strong>X. Migration Path: What’s Next?</strong></h3><p>Microsoft announced that Custom Vision will be retired on September 25, 2028. There are several alternative platforms and services you can consider depending on your specific use case, technical requirements, and integration needs. We recommend to use<strong> AutoML for Images.</strong></p><p><strong>Azure Machine Learning AutoML for Images</strong>: Offers similar functionality with more customization options.</p><p><a href="https://learn.microsoft.com/en-us/azure/ai-services/custom-vision-service/migration-options">Migrate from Custom Vision Service — Azure AI services | Microsoft Learn</a></p><h3><strong>XI. Try It Yourself</strong></h3><p>All my notebooks are available on my <a href="https://github.com/retkowsky/SwimmingPoolDetection">GitHub repository</a>. You can:</p><ol><li>Clone the repo,</li><li>Download the Kaggle dataset,</li><li>Follow along with my three notebooks,</li><li>Adapt the code for your own object detection projects.</li></ol><p>The same workflow applies to detecting:</p><ul><li>Solar panels for renewable energy mapping</li><li>Construction equipment for site monitoring</li><li>Agricultural features for crop analysis</li><li>Vehicles in parking lots for occupancy tracking</li><li>Retail products on shelves for inventory management</li></ul><h3>XII. Azure AI Custom Vision Pricing</h3><h4><strong>Free Tier</strong></h4><ul><li>2 transactions per second</li><li>Capabilities: Upload, train, and run predictions</li><li>Limits: Maximum 2 projects, 1 hour of training monthly</li><li>Cost: Free</li><li>Note: Unavailable in certain regions</li></ul><h4><strong>Standard Tier</strong></h4><ul><li>10 transactions per second</li><li>Capabilities: Prediction operations across up to 100 projects</li><li>Predictions: $2 per 1,000 transactions</li><li>Training: $10 per compute hour</li><li>Image storage: $0.70 per 1,000 images (up to 6 MB per image)</li></ul><h3><strong>XIII. Final Thoughts</strong></h3><p>Building this swimming pool detection demo reinforced my belief that <strong>Azure Custom Vision democratizes computer vision </strong>in the best possible way. It doesn’t replace deep learning expertise for cutting-edge research, but it makes 80% of real-world object detection problems accessible to anyone willing to invest a few hours.</p><p>The python code structure I developed — data preparation, training, and inference — provides a reusable template for similar projects. Whether you’re a data scientist, developer, or domain expert, you can adapt this workflow to solve your specific object detection challenges.</p><p>Give it a try, and feel free to reach out if you have questions or want to discuss your own computer vision projects!</p><h3><strong>XIV. Resources</strong></h3><ul><li><strong>My GitHub Demo</strong>: <a href="https://github.com/retkowsky/SwimmingPoolDetection">Swimming Pool Detection Repository</a></li><li><strong>Azure Custom Vision Portal</strong>: <a href="https://www.customvision.ai/">customvision.ai</a></li><li><strong>Microsoft Documentation</strong>: <a href="https://docs.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/">Custom Vision Service Docs</a></li><li><strong>Dataset Source</strong>: <a href="https://www.kaggle.com/alexj21/swimming-pool-512x512/metadata">Kaggle Swimming Pool Dataset</a></li><li><strong>Pricing: </strong><a href="https://azure.microsoft.com/en-us/pricing/details/cognitive-services/custom-vision-service/?msockid=26142c154a3263a22e423a774b4a62ee#pricing">AI Services Pricing — Custom Vision Service | Microsoft Azure</a></li></ul><h3><strong>About the Author</strong></h3><p>Serge Retkowsky | AI GBB | Microsoft France<br>LinkedIn | <a href="https://www.linkedin.com/in/serger/">https://www.linkedin.com/in/serger/</a><br>GitHub | <a href="https://github.com/retkowsky">retkowsky (Serge Retkowsky)</a></p><p><em>Have questions about Azure AI services? Drop a comment below or connect with me on LinkedIn! Have a good day.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195c70227985" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-KnowlEDGE: Revolutionizing Disconnected Azure AI Services]]></title>
            <link>https://medium.com/@sergems18/ai-knowledge-revolutionizing-disconnected-azure-ai-services-2b8d31b00a0d?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b8d31b00a0d</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[edge-ai]]></category>
            <category><![CDATA[azure-ai-services]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 07:22:34 GMT</pubDate>
            <atom:updated>2025-10-07T07:22:34.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIkkzNw0jD8PRCM6Gjl5Og.png" /><figcaption>Running Azure AI Services on containers</figcaption></figure><p><strong><em>Bridging the gap between cloud capabilities and on-premises requirements with containerized Microsoft AI excellence</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*ZHytzVT_hPwfjnOci2jfxA.jpeg" /><figcaption>Azure AI knowlEDGE <a href="https://github.com/Azure-Samples/AI-KnowlEDGE">Azure-Samples/AI-KnowlEDGE</a></figcaption></figure><h3>TL;DR</h3><p><strong>AI-KnowlEDGE </strong>is a revolutionary desktop application that enables organizations to deploy and manage Azure AI services in completely disconnected environments. <strong>By leveraging containerization and local Small Language Models (SLMs)</strong>, it brings the power of Azure’s AI capabilities to air-gapped systems while maintaining <strong>full control over data privacy and compliance requirements</strong>.</p><h3>The Challenge: AI in Disconnected Environments</h3><p>In today’s digital landscape, organizations face a critical dilemma: they need powerful AI capabilities but cannot always send their sensitive data to the cloud. Whether it’s due to regulatory compliance, security policies, or operational requirements, many enterprises operate in “air-gapped” or disconnected environments where cloud connectivity is limited or prohibited entirely.</p><p>Traditional solutions often force organizations to choose between security and innovation. <strong>AI-KnowlEDGE eliminates this compromise.</strong></p><h3>What is AI-KnowlEDGE?</h3><p>AI-KnowlEDGE is an open-source accelerator developed by Microsoft’s Azure team that enables users to:</p><ul><li><strong>Deploy Azure AI services locally</strong> using Docker containers</li><li><strong>Maintain complete data sovereignty</strong> with on-premises processing</li><li><strong>Access familiar Azure APIs</strong> without internet connectivity</li><li><strong>Leverage Small Language Models</strong> through Ollama integration</li><li><strong>Build RAG (Retrieval-Augmented Generation) solutions</strong> with ChromaDB</li></ul><p>The goal of this repository is to provide an accelerator that enables users to quickly and efficiently set up and run Azure AI services in a disconnected environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LtuZXDF9hL6GYWS3X1t-Q.jpeg" /><figcaption>AI KnowlEDGE — Document analysis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5nh_-7RPrhXqQoORRqqjg.jpeg" /><figcaption>AI KnowlEDGE — Summary generation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dmd6HFkQz44MithpZPsDcQ.jpeg" /><figcaption>AI KnowlEDGE — Suggested questions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OictNrOOqQRsgf3K2FgsEA.jpeg" /><figcaption>AI KnowlEDGE — Answers with context</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hhKqAwnzvEKBi2x9hbV2w.jpeg" /><figcaption>AI KnowlEDGE — Answers with context</figcaption></figure><h3>Core Architecture &amp; Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*kXiJUxPiPYraHMwKWZ3lcw.png" /><figcaption>Architecture</figcaption></figure><h3>Container-First Approach</h3><p><strong>AI-KnowlEDGE </strong>leverages Docker containerization to package Azure AI services with their dependencies, creating portable and consistent deployments across different environments.</p><h3>Supported Azure AI Services</h3><p>Currently, the platform supports:</p><ul><li><strong>Azure Document Intelligence</strong> — OCR and document analysis capabilities</li><li><strong>Azure AI Language Services</strong> — Text summarization and language processing</li><li><strong>Future roadmap includes</strong> Speech Services and Translation Services</li></ul><h3>Local AI Integration</h3><ul><li><strong>Ollama Integration</strong>: Runs Small Language Models locally (Phi-3 and others)</li><li><strong>ChromaDB</strong>: Provides vector database capabilities for RAG implementations</li><li><strong>Embedding Models</strong>: Supports nomic-embed-text for document vectorization</li></ul><h3>User Interface</h3><ul><li><strong>Streamlit Frontend</strong>: Intuitive web-based interface for end users</li><li><strong>FastAPI Backend</strong>: Robust API layer handling service orchestration</li><li><strong>Docker Compose</strong>: Simplified service deployment and management</li></ul><h3>Key Benefits: Why AI-KnowlEDGE Matters</h3><h4>🔒 Complete Data Control</h4><p>You can determine where your data is processed by Azure AI services, which is crucial if you cannot send data to the cloud but still need access to Azure AI services APIs. This ensures compliance with the strictest data governance requirements.</p><h4>⚡ High Performance</h4><p>Containers allow Azure AI services to run close to your application logic and data, meeting high throughput and low latency requirements. They do not limit transactions per second (TPS) and can scale both vertically and horizontally to meet demand.</p><h4>🏗️ Immutable Infrastructure</h4><p>DevOps teams can utilize a consistent and reliable set of known system parameters while remaining adaptable to changes. Containers offer the flexibility to pivot within a stable ecosystem and prevent configuration drift.</p><h4>📈 Enterprise Scalability</h4><p>The platform supports deployment across multiple environments:</p><ul><li>Azure Kubernetes Service</li><li>Azure Container Instances</li><li>On-premises Kubernetes clusters</li><li>Edge computing scenarios</li></ul><h4>🔄 Version Control &amp; Updates</h4><p>You have the flexibility to version and update models deployed in your solutions as needed.</p><h3>Real-World Use Cases</h3><h4>Financial Services</h4><p>Banks and financial institutions can process loan documents, perform fraud detection, and analyze customer communications without data leaving their secured networks.</p><h4>Healthcare</h4><p>Medical organizations can analyze patient records, extract insights from medical literature, and support clinical decision-making while maintaining HIPAA compliance.</p><h4>Government &amp; Defense</h4><p>Agencies can process classified documents, perform intelligence analysis, and support decision-making in completely air-gapped environments.</p><h4>Manufacturing</h4><p>Industrial companies can analyze technical documentation, support quality control processes, and extract insights from operational data without exposing proprietary information.</p><h3>Getting Started: Your First AI-KnowlEDGE Deployment</h3><h4>Prerequisites</h4><ul><li>Python 3.12+</li><li>Docker Desktop</li><li>Azure AI Services subscription (for initial setup)</li><li>Visual Studio Code (recommended)</li></ul><h4>Quick Start Guide</h4><p><strong>Step 1: Clone and Setup</strong></p><p>bash</p><pre>git clone https://github.com/Azure-Samples/AI-knowlEDGE.git<br>cd AI-knowlEDGE<br>python -m venv venv<br>source venv/bin/activate  # Windows: venv\Scripts\activate<br>pip install -r requirements.txt</pre><p><strong>Step 2: Container Deployment</strong></p><p>bash</p><pre>docker pull mcr.microsoft.com/azure-cognitive-services/textanalytics/summarization:cpu<br>docker-compose up</pre><p><strong>Step 3: Local AI Models</strong></p><p>bash</p><pre>ollama pull phi3<br>ollama pull nomic-embed-text</pre><p><strong>Step 4: Start Services</strong></p><p>bash</p><pre># Backend<br>uvicorn backend.main:app --host 0.0.0.0 --port 8000</pre><pre># Frontend<br>streamlit run frontend/app.py --server.port=8501</pre><h3>Technical Deep Dive: Understanding the Magic</h3><h4>Container Architecture</h4><p>AI-KnowlEDGE uses a microservices architecture where each Azure AI service runs in its own container:</p><p>yaml</p><pre>services:<br>  azure-form-recognizer-read:<br>    image: mcr.microsoft.com/azure-cognitive-services/form-recognizer/read-3.1<br>    ports: [&quot;5000:5000&quot;]<br>  <br>  textanalytics:<br>    image: mcr.microsoft.com/azure-cognitive-services/textanalytics/summarization:cpu<br>    ports: [&quot;5001:5000&quot;]</pre><h3>API Compatibility</h3><p>The containerized services maintain full compatibility with Azure’s cloud APIs, ensuring seamless migration and development consistency.</p><h3>RAG Implementation</h3><p>The platform implements Retrieval-Augmented Generation by:</p><ol><li><strong>Document Processing</strong>: Using Azure Document Intelligence for OCR</li><li><strong>Text Vectorization</strong>: Converting content to embeddings via Ollama</li><li><strong>Vector Storage</strong>: Storing embeddings in ChromaDB</li><li><strong>Query Processing</strong>: Matching user queries with relevant content</li><li><strong>Response Generation</strong>: Using local SLMs to generate contextual responses</li></ol><h3>Best Practices &amp; Production Considerations</h3><h4>Security Hardening</h4><ul><li>Implement network segmentation</li><li>Use secrets management for API keys</li><li>Regular security scanning of container images</li><li>Access control and authentication</li></ul><h4>Performance Optimization</h4><ul><li>Resource allocation based on workload</li><li>Container orchestration with Kubernetes</li><li>Load balancing for high availability</li><li>Monitoring and alerting setup</li></ul><h4>Operational Excellence</h4><ul><li>Automated backup strategies</li><li>Disaster recovery planning</li><li>Version control for model updates</li><li>Comprehensive logging and monitoring</li></ul><h3>Community &amp; Contribution</h3><p>AI-KnowlEDGE is an active open-source project with contributions from Microsoft engineers and the global developer community. The project welcomes:</p><ul><li><strong>Feature Requests</strong>: New AI service integrations</li><li><strong>Bug Reports</strong>: Issue identification and resolution</li><li><strong>Code Contributions</strong>: Performance improvements and new capabilities</li><li><strong>Documentation</strong>: User guides and best practices</li></ul><h3>Core Contributors</h3><ul><li><a href="https://www.linkedin.com/in/farid-el-attaoui/"><strong>Farid El Attaoui</strong></a><strong> — Microsoft France</strong></li><li><a href="https://www.linkedin.com/in/alibek-jakupov-30305b61/"><strong>Alibek Jakupov</strong></a><strong> — Microsoft France</strong></li><li><a href="https://www.linkedin.com/in/raoui-lassoued/"><strong>Raoui Lassoued</strong></a> <strong>— Microsoft France</strong></li><li><a href="https://www.linkedin.com/in/serger"><strong>Serge Retkowsky</strong></a><strong> — Microsoft France</strong></li></ul><h3>Getting Help &amp; Resources</h3><h4>Official Resources</h4><ul><li><strong>GitHub Repository</strong>: <a href="https://github.com/Azure-Samples/AI-KnowlEDGE">Azure-Samples/AI-KnowlEDGE</a></li><li><strong>Demo Video</strong>: <a href="https://www.youtube.com/watch?v=m9Q2RUp-3Vo">Watch the Demo</a></li><li><strong>Documentation</strong>: <a href="https://learn.microsoft.com/en-us/azure/ai-services/containers/disconnected-container-faq">Microsoft Learn</a></li><li><strong>Azure AI Containers sample</strong>s: <a href="https://github.com/retkowsky/azure-ai-containers-samples">retkowsky/azure-ai-containers-samples: Azure AI Containers samples</a></li><li><a href="https://www.youtube.com/watch?v=hdfbn4Q8jbo">Bringing AI to the edge: Azure Cognitive Services in Containers</a></li></ul><h3>Conclusion: The Future of Hybrid AI</h3><p><strong>AI-KnowlEDGE</strong> represents a change in thinking in how organizations can approach AI adoption. By removing the traditional barriers between security and innovation, it enables enterprises to harness the full power of Azure AI services while maintaining complete control over their data and infrastructure.</p><p>As the digital landscape continues to evolve, tools like <strong>AI-KnowlEDGE</strong> will become increasingly critical for organizations that need to balance the competing demands of innovation, security, and compliance. The future of AI is not just in the cloud — it’s wherever your data needs to stay secure.</p><p><strong>Ready to get started?</strong> Clone the repository today and discover how AI-KnowlEDGE can transform your organization’s AI capabilities while keeping your data exactly where it belongs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b8d31b00a0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide: Image Classification with Azure Custom Vision (metal defect classification use…]]></title>
            <link>https://medium.com/@sergems18/complete-guide-image-classification-with-azure-custom-vision-metal-defect-classification-use-e49af6e7e100?source=rss-d92e84d8be4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49af6e7e100</guid>
            <category><![CDATA[azure-custom-vision-api]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[azure-custom-vision]]></category>
            <dc:creator><![CDATA[Serge Retkowsky]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 15:46:27 GMT</pubDate>
            <atom:updated>2025-09-17T07:44:19.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete Guide: Image Classification with Azure Custom Vision (metal defect classification use case)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*Jk4chnZXAxTMuP0u" /><figcaption>Custom Webapp for image classification</figcaption></figure><h3>1. Introduction</h3><p><strong>Azure Custom Vision </strong>is a powerful cloud-based service that democratizes machine learning by allowing developers and data scientists to build <strong>custom image classification models </strong>without requiring deep expertise in computer vision algorithms.</p><p>This comprehensive guide will walk you through the entire process of creating, training, and deploying image classification models using <strong>Azure Custom Vision</strong>, from basic concepts to advanced implementation strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QCJGuxNfeVuZ2QKSRfo7Q.jpeg" /><figcaption>Azure Custom Vision (source: Foteini Savvidou)</figcaption></figure><h3>2. What is Azure Custom Vision?</h3><p><strong>Azure AI Custom Vision</strong> is an image recognition service that lets you build, deploy, and improve your own image identifier models.</p><p>An image identifier applies labels to images according to their visual characteristics. Each label represents a classification or object.</p><p>The service is particularly powerful because it can achieve high accuracy with small datasets, making it accessible for businesses and developers who don’t have access to massive image collections.</p><h3>3. How to Build a Custom Vision Model with Azure Custom Vision (6 Steps)?</h3><p><strong>Step 1</strong>: Every ML project starts with data — Find data that would help you train your model</p><p><strong>Step 2</strong>: Use the <strong>Custom Vision web portal </strong>or the <strong>Custom Vision Rest API</strong> to upload and tag your images</p><p><strong>Step 3</strong>: Use your trained model to classify or detect objects using Azure Custom Vision Rest API</p><p><strong>Step 4</strong>: Custom Vision Model analyzes &amp; evaluates how well you performed the model. These metrics tell you only how big model performed so far, how to make it better provided</p><p><strong>Step 5</strong>: Test your model and see how it performs on unseen (new) data</p><p><strong>Step 6</strong>: If your model is performing at a satisfactory level, you can start using it. You can deploy it as an endpoint for your applications, or export the model for offline use</p><h3>4. Key Benefits of Azure Custom Vision</h3><ul><li><strong>No-Code and Low-Code Options</strong>: Build models through an intuitive web interface or programmatically via APIs</li><li><strong>Few-Shot Learning</strong>: The Custom Vision service is optimized to quickly recognize major differences between images, so you can start prototyping your model with a small amount of data</li><li><strong>Export Capabilities</strong>: Deploy models locally or integrate them into applications</li><li><strong>Multi-Platform Support</strong>: Available through REST APIs, SDKs for multiple programming languages, and direct web portal access</li></ul><h3>5. Core Concepts</h3><h4>Classification Types</h4><p>Azure Custom Vision supports two main classification approaches:</p><p><strong>Multiclass Classification</strong>: Each image receives exactly one label from a set of mutually exclusive categories. For example, classifying animals as “dog,” “cat,” or “bird.”</p><p><strong>Multilabel Classification</strong>: Images can have multiple labels applied simultaneously. For instance, a food image might be tagged as both “healthy” and “vegetarian.”</p><h4>Domains</h4><p>Custom Vision offers specialized domains optimized for different use cases:</p><ul><li><strong>General</strong>: Broad range of image classification tasks</li><li><strong>Food</strong>: Optimized for photographs of dishes and individual ingredients</li><li><strong>Landmarks</strong>: Natural and artificial landmarks recognition</li><li><strong>Retail</strong>: Shopping catalogs and e-commerce applications</li><li><strong>Compact</strong>: Optimized for real-time classification on mobile devices with export capabilities</li></ul><h3>6. Step-by-Step Implementation</h3><h4>1. Setting Up Azure Resources</h4><p>To use the Custom Vision service, you need to create Custom Vision training and prediction resources in Azure:</p><ol><li>Navigate to the <a href="https://portal.azure.com/">Azure Portal</a></li><li>Click “Create a resource” and search for “Custom Vision”</li><li>Configure your resource:</li></ol><ul><li><strong>Resource Group</strong>: Create new or select existing</li><li><strong>Region</strong>: Choose based on your location and compliance requirements</li><li><strong>Training Pricing Tier</strong>: F0 (free) for testing, S0 for production</li><li><strong>Prediction Pricing Tier</strong>: F0 (free) for testing, S0 for production</li><li><strong>Training Resource</strong>: Handles model training and management</li><li><strong>Prediction Resource</strong>: Manages inference requests</li><li><strong>Separate Resources</strong>: Recommended for production to isolate training and prediction costs</li></ul><h4>2. Creating Your First Project</h4><h4>Using the Web Portal</h4><ol><li>Navigate to <a href="https://customvision.ai/">Custom Vision Portal</a></li><li>Sign in with your Azure credentials</li><li>Click “New Project” and configure:</li></ol><ul><li><strong>Name</strong>: Descriptive project name</li><li><strong>Description</strong>: Clear project purpose</li><li><strong>Resource</strong>: Select your training resource</li><li><strong>Project Types</strong>: Classification</li><li><strong>Classification Types</strong>: Multiclass or Multilabel</li><li><strong>Domains</strong>: Select appropriate domain</li></ul><h4>Project Planning Considerations</h4><p><strong>Data Strategy</strong>:</p><ul><li>Minimum 15–20 images per class for basic models</li><li>50–100 images per class for production-ready models</li><li>Balanced datasets across all classes</li><li>Representative samples of edge cases and variations</li></ul><p><strong>Tagging Strategy</strong>:</p><ul><li>Clear, consistent naming conventions</li><li>Hierarchical tags when appropriate</li><li>Consider negative examples to improve precision</li></ul><h4>3. Data Preparation and Upload</h4><h4>Image Requirements</h4><ul><li><strong>Format</strong>: JPEG, PNG, BMP, GIF</li><li><strong>Size</strong>: 4MB maximum per image</li><li><strong>Dimensions</strong>: Minimum 256x256 pixels</li><li><strong>Quantity</strong>: 5,000 images maximum per project (free tier: 500)</li></ul><h4>Upload Process</h4><p>Click on Add Images to select images you wish to train your model on, and then select appropriate tags or ‘labels’ for your images:</p><ol><li>Select “Add images” in your project</li><li>Choose multiple images (up to 64 per batch)</li><li>Apply tags during upload or after</li><li>Review and confirm uploads</li></ol><h4>Data Quality Tips</h4><ul><li><strong>Variety</strong>: Include different angles, lighting conditions, and backgrounds</li><li><strong>Quality</strong>: Ensure clear, well-lit images</li><li><strong>Relevance</strong>: Remove ambiguous or incorrectly labeled images</li><li><strong>Balance</strong>: Maintain roughly equal numbers of images per class</li></ul><h4>4. Training Your Model</h4><h4>Training Process</h4><p>To train the classifier, select the Train button. The classifier uses all of the current images to create a model that identifies the visual qualities of each tag:</p><ol><li>Click the <strong>“Train</strong>” button in your project</li><li>Select training type (<strong>Quick Training</strong>: Faster, suitable for initial experiments or <strong>Advanced Training</strong>: More thorough, better for production models)</li><li>Monitor training progress</li><li>Review performance metrics upon completion</li></ol><h4>Understanding Performance Metrics</h4><p><strong>Precision</strong>: Precision indicates the fraction of identified classifications that were correct. For example, if the model identified 100 images as dogs, and 99 of them were actually of dogs, then the precision would be 99%</p><p><strong>Recall</strong>: Recall indicates the fraction of actual classifications that were correctly identified</p><p><strong>Average Precision (AP)</strong>: Overall model performance metric combining precision and recall</p><h4>5. Testing and Evaluation</h4><h4>Quick Test Feature</h4><ol><li>Use the<strong> “Quick Test”</strong> tab to upload new images</li><li>Review predictions and confidence scores</li><li>Identify misclassifications and edge cases</li></ol><h4>Performance Analysis</h4><ul><li><strong>Confusion Matrix</strong>: Understand classification patterns</li><li><strong>Per-Class Metrics</strong>: Identify underperforming categories</li><li><strong>Threshold Tuning</strong>: Adjust confidence thresholds for optimal results</li></ul><h4>6. Model Improvement Strategies</h4><h4>Iterative Refinement</h4><ol><li><strong>Add More Data</strong>: Focus on misclassified categories</li><li><strong>Improve Tagging</strong>: Correct mislabeled training images</li><li><strong>Balance Dataset</strong>: Address class imbalance issues</li><li><strong>Negative Examples</strong>: Add images of what the model shouldn’t classify</li></ol><h4>Advanced Techniques</h4><ul><li><strong>Data Augmentation</strong>: Use varied angles, lighting, and crops</li><li><strong>Transfer Learning</strong>: Leverage pre-trained domain models</li><li><strong>Ensemble Methods</strong>: Combine multiple model predictions</li></ul><h3>7. Programmatic Approach using the Python SDK</h3><p><em>The following examples are based on the implementation patterns: </em><a href="https://github.com/retkowsky/image-classification-azure-custom-vision"><strong>retkowsky/image-classification-azure-custom-vision: Azure Custom Vision for image classification</strong></a></p><h4>Installation and Setup</h4><pre># Install required packages<br>pip install azure-cognitiveservices-vision-customvision<br>pip install pillow<br>pip install matplotlib<br>pip install python-dotenv</pre><h4>Environment Configuration</h4><pre>import os<br>from dotenv import load_dotenv<br>from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient<br>from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient<br>from msrest.authentication import ApiKeyCredentials<br>import time<br>from PIL import Image<br>import matplotlib.pyplot as plt</pre><pre># Load environment variables<br>load_dotenv()</pre><pre># Azure Custom Vision credentials<br>TRAINING_KEY = os.getenv(&#39;CUSTOM_VISION_TRAINING_KEY&#39;)<br>TRAINING_ENDPOINT = os.getenv(&#39;CUSTOM_VISION_TRAINING_ENDPOINT&#39;)<br>PREDICTION_KEY = os.getenv(&#39;CUSTOM_VISION_PREDICTION_KEY&#39;)<br>PREDICTION_ENDPOINT = os.getenv(&#39;CUSTOM_VISION_PREDICTION_ENDPOINT&#39;)<br>PREDICTION_RESOURCE_ID = os.getenv(&#39;CUSTOM_VISION_PREDICTION_RESOURCE_ID&#39;)</pre><pre>print(f&quot;Training Endpoint: {TRAINING_ENDPOINT}&quot;)<br>print(f&quot;Prediction Endpoint: {PREDICTION_ENDPOINT}&quot;)</pre><h4>Complete Training Workflow</h4><pre>def create_custom_vision_project(project_name, domain_type=&quot;General&quot;):<br>    &quot;&quot;&quot;<br>    Create a new Custom Vision project<br>    &quot;&quot;&quot;<br>    # Initialize training client<br>    training_credentials = ApiKeyCredentials(in_headers={&quot;Training-key&quot;: TRAINING_KEY})<br>    trainer = CustomVisionTrainingClient(TRAINING_ENDPOINT, training_credentials)<br>    <br>    # Get available domains<br>    domains = trainer.get_domains()<br>    domain = next(domain for domain in domains if domain.name == domain_type)<br>    <br>    # Create project<br>    project = trainer.create_project(<br>        name=project_name, <br>        domain_id=domain.id, <br>        classification_type=&quot;Multiclass&quot;<br>    )<br>    <br>    print(f&quot;Created project &#39;{project_name}&#39; with ID: {project.id}&quot;)<br>    return trainer, project</pre><pre>def upload_training_images(trainer, project, images_folder):<br>    &quot;&quot;&quot;<br>    Upload and tag training images<br>    Organized in subfolders by class name<br>    &quot;&quot;&quot;<br>    tags = {}<br>    <br>    # Create tags based on subfolder names<br>    for class_name in os.listdir(images_folder):<br>        class_path = os.path.join(images_folder, class_name)<br>        if os.path.isdir(class_path):<br>            tag = trainer.create_tag(project.id, class_name)<br>            tags[class_name] = tag<br>            print(f&quot;Created tag: {class_name}&quot;)<br>    <br>    # Upload images for each class<br>    for class_name, tag in tags.items():<br>        class_path = os.path.join(images_folder, class_name)<br>        image_files = [f for f in os.listdir(class_path) <br>                      if f.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;))]<br>        <br>        print(f&quot;Uploading {len(image_files)} images for class: {class_name}&quot;)<br>        <br>        # Upload in batches<br>        batch_size = 10<br>        for i in range(0, len(image_files), batch_size):<br>            batch_files = image_files[i:i + batch_size]<br>            images_batch = []<br>            <br>            for image_file in batch_files:<br>                image_path = os.path.join(class_path, image_file)<br>                with open(image_path, &quot;rb&quot;) as img:<br>                    images_batch.append(<br>                        trainer.create_images_from_data(<br>                            project.id, <br>                            img.read(), <br>                            tag_ids=[tag.id]<br>                        )<br>                    )<br>            <br>            print(f&quot;Uploaded batch {i//batch_size + 1} for {class_name}&quot;)<br>    <br>    return tags</pre><pre>def train_and_evaluate_model(trainer, project):<br>    &quot;&quot;&quot;<br>    Train the Custom Vision model and display performance metrics<br>    &quot;&quot;&quot;<br>    print(&quot;Starting training...&quot;)<br>    iteration = trainer.train_project(project.id)<br>    <br>    # Wait for training to complete<br>    while iteration.status != &quot;Completed&quot;:<br>        iteration = trainer.get_iteration(project.id, iteration.id)<br>        print(f&quot;Training status: {iteration.status}&quot;)<br>        time.sleep(10)<br>    <br>    print(&quot;Training completed!&quot;)<br>    <br>    # Get performance metrics<br>    performance = trainer.get_iteration_performance(project.id, iteration.id)<br>    <br>    print(f&quot;\nModel Performance:&quot;)<br>    print(f&quot;Precision: {performance.precision:.4f}&quot;)<br>    print(f&quot;Recall: {performance.recall:.4f}&quot;)<br>    print(f&quot;Average Precision: {performance.average_precision:.4f}&quot;)<br>    <br>    # Per-tag performance<br>    print(&quot;\nPer-class Performance:&quot;)<br>    for tag_performance in performance.per_tag_performance:<br>        print(f&quot;{tag_performance.name}:&quot;)<br>        print(f&quot;  Precision: {tag_performance.precision:.4f}&quot;)<br>        print(f&quot;  Recall: {tag_performance.recall:.4f}&quot;)<br>        print(f&quot;  Average Precision: {tag_performance.average_precision:.4f}&quot;)<br>    <br>    return iteration</pre><pre># Complete training pipeline<br>def main_training_pipeline():<br>    &quot;&quot;&quot;<br>    Complete training pipeline for Azure Custom Vision<br>    &quot;&quot;&quot;<br>    # Configuration<br>    project_name = &quot;Image Classification Demo&quot;<br>    images_folder = &quot;training_images&quot;  # Folder with subfolders for each class<br>    <br>    # Create project<br>    trainer, project = create_custom_vision_project(project_name)<br>    <br>    # Upload training images<br>    tags = upload_training_images(trainer, project, images_folder)<br>    <br>    # Train model<br>    iteration = train_and_evaluate_model(trainer, project)<br>    <br>    # Publish model<br>    publish_name = &quot;production_v1&quot;<br>    trainer.publish_iteration(project.id, iteration.id, publish_name, PREDICTION_RESOURCE_ID)<br>    print(f&quot;Model published as: {publish_name}&quot;)<br>    <br>    return project.id, iteration.id, publish_name</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RizBLNI09Ry8f-rE" /><figcaption>Azure Custom Vision: Tags and images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*30Z0AlojVMUgnVz1" /><figcaption>Azure Custom Vision: performance metrics</figcaption></figure><h4>Prediction and Testing</h4><pre>def predict_single_image(project_id, publish_name, image_path, show_image=True):<br>    &quot;&quot;&quot;<br>    Predict single image using Custom Vision model<br>    &quot;&quot;&quot;<br>    # Initialize prediction client<br>    prediction_credentials = ApiKeyCredentials(in_headers={&quot;Prediction-key&quot;: PREDICTION_KEY})<br>    predictor = CustomVisionPredictionClient(PREDICTION_ENDPOINT, prediction_credentials)<br>    <br>    # Make prediction<br>    with open(image_path, &quot;rb&quot;) as image_data:<br>        results = predictor.classify_image(project_id, publish_name, image_data.read())<br>    <br>    # Display results<br>    if show_image:<br>        # Load and display image<br>        img = Image.open(image_path)<br>        plt.figure(figsize=(10, 6))<br>        <br>        plt.subplot(1, 2, 1)<br>        plt.imshow(img)<br>        plt.title(f&quot;Test Image: {os.path.basename(image_path)}&quot;)<br>        plt.axis(&#39;off&#39;)<br>        <br>        # Plot predictions<br>        plt.subplot(1, 2, 2)<br>        labels = [pred.tag_name for pred in results.predictions]<br>        scores = [pred.probability for pred in results.predictions]<br>        <br>        bars = plt.barh(labels, scores)<br>        plt.xlabel(&#39;Confidence Score&#39;)<br>        plt.title(&#39;Prediction Results&#39;)<br>        plt.xlim(0, 1)<br>        <br>        # Color bars based on confidence<br>        for i, bar in enumerate(bars):<br>            if scores[i] &gt; 0.7:<br>                bar.set_color(&#39;green&#39;)<br>            elif scores[i] &gt; 0.5:<br>                bar.set_color(&#39;orange&#39;)<br>            else:<br>                bar.set_color(&#39;red&#39;)<br>        <br>        plt.tight_layout()<br>        plt.show()<br>    <br>    # Print detailed results<br>    print(f&quot;\nPrediction results for: {os.path.basename(image_path)}&quot;)<br>    print(&quot;-&quot; * 50)<br>    for prediction in results.predictions:<br>        print(f&quot;{prediction.tag_name}: {prediction.probability:.4f} ({prediction.probability*100:.2f}%)&quot;)<br>    <br>    return results</pre><pre>def batch_predict_and_analyze(project_id, publish_name, test_folder):<br>    &quot;&quot;&quot;<br>    Batch prediction with performance analysis<br>    &quot;&quot;&quot;<br>    prediction_credentials = ApiKeyCredentials(in_headers={&quot;Prediction-key&quot;: PREDICTION_KEY})<br>    predictor = CustomVisionPredictionClient(PREDICTION_ENDPOINT, prediction_credentials)<br>    <br>    results = []<br>    <br>    # Process each test image<br>    for filename in os.listdir(test_folder):<br>        if filename.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;)):<br>            image_path = os.path.join(test_folder, filename)<br>            <br>            with open(image_path, &quot;rb&quot;) as image_data:<br>                prediction = predictor.classify_image(project_id, publish_name, image_data.read())<br>            <br>            # Store results<br>            top_prediction = prediction.predictions[0] if prediction.predictions else None<br>            results.append({<br>                &#39;filename&#39;: filename,<br>                &#39;predicted_class&#39;: top_prediction.tag_name if top_prediction else &#39;Unknown&#39;,<br>                &#39;confidence&#39;: top_prediction.probability if top_prediction else 0.0,<br>                &#39;all_predictions&#39;: [(p.tag_name, p.probability) for p in prediction.predictions]<br>            })<br>    <br>    # Analysis and visualization<br>    print(f&quot;Processed {len(results)} test images&quot;)<br>    <br>    # Confidence distribution<br>    confidences = [r[&#39;confidence&#39;] for r in results]<br>    plt.figure(figsize=(12, 4))<br>    <br>    plt.subplot(1, 2, 1)<br>    plt.hist(confidences, bins=20, alpha=0.7, color=&#39;blue&#39;)<br>    plt.xlabel(&#39;Confidence Score&#39;)<br>    plt.ylabel(&#39;Frequency&#39;)<br>    plt.title(&#39;Confidence Score Distribution&#39;)<br>    <br>    # Top predictions summary<br>    from collections import Counter<br>    predicted_classes = [r[&#39;predicted_class&#39;] for r in results]<br>    class_counts = Counter(predicted_classes)<br>    <br>    plt.subplot(1, 2, 2)<br>    plt.bar(class_counts.keys(), class_counts.values())<br>    plt.xlabel(&#39;Predicted Classes&#39;)<br>    plt.ylabel(&#39;Count&#39;)<br>    plt.title(&#39;Predicted Class Distribution&#39;)<br>    plt.xticks(rotation=45)<br>    <br>    plt.tight_layout()<br>    plt.show()<br>    <br>    return results</pre><pre># Usage examples<br>if __name__ == &quot;__main__&quot;:<br>    # Train model<br>    project_id, iteration_id, publish_name = main_training_pipeline()<br>    <br>    # Test single image<br>    test_image = &quot;test_images/sample_image.jpg&quot;<br>    predict_single_image(project_id, publish_name, test_image)<br>    <br>    # Batch testing<br>    test_results = batch_predict_and_analyze(project_id, publish_name, &quot;test_images&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*CURNTogpsU3SExTfHSJrRw.png" /><figcaption>Confusion matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*Lw4Mi3hE5jW0RuuVMGtHVw.png" /><figcaption>Misclassification results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*j_aKocDq2lYvk3A5xdW2Jw.png" /><figcaption>Image classification result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*l4Zt5ViTkoSkvrQTGavzJA.png" /><figcaption>Image classification result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Jk4chnZXAxTMuP0u" /><figcaption>Custom webapp for image classification</figcaption></figure><h3>8. Deployment Options</h3><h4>Cloud Deployment</h4><ol><li><strong>Azure Container Instances</strong>: Quick deployment for testing</li><li><strong>Azure Kubernetes Service</strong>: Scalable production deployment</li><li><strong>Azure Functions</strong>: Serverless inference for event-driven scenarios</li><li><strong>Azure App Service</strong>: Web application integration</li></ol><h4>Edge Deployment</h4><p>Custom Vision lets you export models as Docker containers for deployment to edge devices:</p><ol><li><strong>Export Model</strong>: Download as Docker container, ONNX, or platform-specific formats</li><li><strong>IoT Edge Integration</strong>: Deploy to Azure IoT Edge devices</li><li><strong>Mobile Integration</strong>: iOS and Android SDKs for on-device inference</li></ol><h3>9. Export Formats</h3><ul><li><strong>Docker Container</strong>: Linux or Windows containers</li><li><strong>ONNX</strong>: Cross-platform model format</li><li><strong>TensorFlow</strong>: For TensorFlow applications</li><li><strong>CoreML</strong>: iOS applications</li><li><strong>TensorFlow Lite</strong>: Android and edge devices</li></ul><h3>10. Production Best Practices</h3><h4>Security Considerations</h4><ol><li><strong>Key Management</strong>: Use Azure Key Vault for API keys</li><li><strong>Network Security</strong>: Implement VNet integration for enterprise deployments</li><li><strong>Access Control</strong>: Configure Azure RBAC for resource management</li><li><strong>Compliance</strong>: Ensure data residency and regulatory compliance</li></ol><h4>Performance Optimization</h4><ol><li><strong>Batch Processing</strong>: Use batch APIs for multiple image processing</li><li><strong>Load Balancing</strong>: Distribute requests across multiple prediction endpoints</li><li><strong>Monitoring</strong>: Set up Azure Monitor for performance tracking</li></ol><h4>Cost Management</h4><ol><li><strong>Resource Planning</strong>: Choose appropriate pricing tiers</li><li><strong>Usage Monitoring</strong>: Track prediction requests and training iterations</li><li><strong>Optimization</strong>: Use compact models for edge deployment to reduce cloud costs</li><li><strong>Scaling</strong>: Implement auto-scaling based on demand</li></ol><h3>11. Troubleshooting Common Issues</h3><h4>Low Model Performance</h4><p><strong>Symptoms</strong>: Poor accuracy, high misclassification rates</p><p><strong>Solutions</strong>:</p><ul><li>Increase training data volume</li><li>Improve data quality and labeling consistency</li><li>Balance dataset across classes</li><li>Use appropriate domain selection</li><li>Add negative examples</li></ul><h4>Training Failures</h4><p><strong>Symptoms</strong>: Training doesn’t complete, error messages</p><p><strong>Solutions</strong>:</p><ul><li>Verify image formats and sizes</li><li>Check tag consistency</li><li>Ensure minimum images per tag</li><li>Review quota limitations</li></ul><h4>Prediction Latency</h4><p><strong>Symptoms</strong>: Slow response times, timeouts</p><p><strong>Solutions</strong>:</p><ul><li>Use compact models for faster inference</li><li>Implement caching strategies</li><li>Deploy closer to users geographically</li><li>Optimize image preprocessing</li></ul><h3>12. Performance Monitoring</h3><ol><li><strong>Azure Monitor</strong>: Track API calls, latency, and errors</li><li><strong>Custom Telemetry</strong>: Log prediction confidence scores</li><li><strong>A/B Testing</strong>: Compare model versions</li><li><strong>Feedback Loops</strong>: Collect user feedback for model improvement</li></ol><h3>13. Model Lifecycle Management</h3><ol><li><strong>Version Control</strong>: Maintain multiple model iterations</li><li><strong>Automated Retraining</strong>: Schedule regular model updates</li><li><strong>Deployment Pipelines</strong>: CI/CD for model deployment</li><li><strong>Rollback Strategies</strong>: Quick reversion to previous versions</li></ol><h3>14. Real-World Applications</h3><h4>Retail and E-commerce</h4><ul><li><strong>Product Categorization</strong>: Automatically classify product images</li><li><strong>Quality Control</strong>: Identify defective products</li><li><strong>Visual Search</strong>: Enable image-based product discovery</li><li><strong>Inventory Management</strong>: Track product availability through images</li></ul><h4>Healthcare</h4><ul><li><strong>Medical Imaging</strong>: Assist in diagnostic imaging analysis</li><li><strong>Drug Identification</strong>: Classify pharmaceutical products</li><li><strong>Safety Compliance</strong>: Monitor PPE usage</li><li><strong>Research Applications</strong>: Classify research specimens</li></ul><h4>Manufacturing</h4><ul><li><strong>Quality Assurance</strong>: Detect manufacturing defects</li><li><strong>Predictive Maintenance</strong>: Classify equipment conditions</li><li><strong>Safety Monitoring</strong>: Identify safety violations</li><li><strong>Process Optimization</strong>: Analyze production line efficiency</li></ul><h4>Agriculture</h4><ul><li><strong>Crop Monitoring</strong>: Classify plant health and diseases</li><li><strong>Yield Estimation</strong>: Analyze crop maturity</li><li><strong>Pest Detection</strong>: Identify agricultural pests</li><li><strong>Equipment Monitoring</strong>: Track machinery conditions</li></ul><h3>15. Future Considerations</h3><h4>Emerging Technologies</h4><ol><li><strong>AI/ML Advances</strong>: Stay updated with latest computer vision techniques</li><li><strong>Edge Computing</strong>: Increased focus on on-device processing</li><li><strong>AutoML Evolution</strong>: More automated model optimization</li><li><strong>Multimodal Learning</strong>: Integration with text and audio data</li></ol><h4>Scalability Planning</h4><ol><li><strong>Global Distribution</strong>: Multi-region deployment strategies</li><li><strong>Performance Requirements</strong>: Plan for growing user bases</li><li><strong>Data Growth</strong>: Handle increasing dataset sizes</li><li><strong>Integration Complexity</strong>: Manage multiple AI services</li></ol><h3>16. Conclusion</h3><p><strong>Azure Custom Vision</strong> provides a comprehensive platform for building, deploying, and managing image classification models at scale.</p><p>By following the practices outlined in this guide, you can create robust, production-ready solutions that leverage the power of machine learning without requiring deep expertise in computer vision algorithms.</p><p>The key to success with Custom Vision lies in:</p><ul><li><strong>Quality Data</strong>: Investing time in proper data preparation and labeling</li><li><strong>Iterative Improvement</strong>: Continuously refining models based on performance feedback</li><li><strong>Appropriate Architecture</strong>: Choosing the right deployment and integration patterns</li><li><strong>Monitoring and Maintenance</strong>: Implementing proper lifecycle management</li></ul><p>Whether you’re building a simple prototype or a complex enterprise solution, Azure Custom Vision offers the flexibility and power to bring your computer vision ideas to life.</p><p>Start with the web portal for rapid prototyping, then scale to programmatic approaches as your requirements grow.</p><h3>All python code and images are available here</h3><p><a href="https://github.com/retkowsky/image-classification-azure-custom-vision/tree/main">retkowsky/image-classification-azure-custom-vision: Azure Custom Vision for image classification</a></p><h3>Additional Resources</h3><ul><li><a href="https://www.customvision.ai/?azure-portal=true">Custom Vision — Home</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-services/custom-vision-service/">Custom Vision documentation — Quickstarts, Tutorials, API Reference — Azure AI services | Microsoft Learn</a></li><li><a href="https://learn.microsoft.com/en-us/azure/ai-services/custom-vision-service/quickstarts/image-classification">https://learn.microsoft.com/en-us/azure/ai-services/custom-vision-service/quickstarts/image-classification</a></li><li><a href="https://azure.microsoft.com/en-us/pricing/details/cognitive-services/custom-vision-service/">Pricing Information</a></li><li><a href="https://www.youtube.com/@serge1840/playlists">Serge Analytics — YouTube</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49af6e7e100" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>