<?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 Mohamed Stifi on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Stifi on Medium]]></description>
        <link>https://medium.com/@mohamed-stifi?source=rss-ebf899c0a71d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*y7eLnEe_BCYkJXlC</url>
            <title>Stories by Mohamed Stifi on Medium</title>
            <link>https://medium.com/@mohamed-stifi?source=rss-ebf899c0a71d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:46:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamed-stifi/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[Production Agentic System Patterns — The Complete Series Map]]></title>
            <link>https://mohamed-stifi.medium.com/production-agentic-system-patterns-the-complete-series-map-4aee5063ae6a?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aee5063ae6a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Sat, 23 May 2026 00:00:24 GMT</pubDate>
            <atom:updated>2026-05-23T00:00:51.798Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to feel like I knew agents.</p><p>I’d read the papers. I followed the right people on Twitter. I watched the talks. I could explain ReAct, chain-of-thought, RAG, tool calling — any of it, on demand. When a new concept dropped, I’d add it to my mental inventory and move on.</p><p>Thanks for reading Mohamed’s Substack! Subscribe for free to receive new posts and support my work.</p><p>Then I sat down to engineer a real system — a production agent that had to be <em>reliable</em>, <em>observable</em>, <em>safe</em>, and <em>maintainable</em> — and I had nothing. Not because I lacked concepts. I had too many, with no map connecting them. No structure to tell me which pattern to reach for, when to stop, or why things were breaking the way they were.</p><p>That moment is what this series is about.</p><h3>What this series is not</h3><p>This is not a beginner’s guide to large language models.</p><p>It assumes you have already built something with agents. You know what a prompt is, what RAG does, what tool calling looks like. You may have shipped a prototype that worked beautifully on your laptop and then quietly fell apart in production.</p><p>If that sounds familiar, this is for you.</p><h3>The one thesis that runs through everything</h3><blockquote><em>An LLM is a brilliant, fallible, manipulable </em>proposer<em>. Production engineering is the discipline of wrapping it in structure, feedback, memory, and deterministic guarantees — so the system is reliable, safe, and improvable even though the model at its core is none of those things on its own.</em></blockquote><p>That single sentence is the architecture of this entire series. Every module is one more layer of the wrapper. Every pattern solves one specific failure that appears when that wrapper is missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*trZNatZaIwX4apWd.png" /></figure><h3>How every module is built</h3><p>Each article in this series follows the same spine — deliberately:</p><p><strong>Problem first → why it bites in production → the pattern → code → real use case → when NOT to use it.</strong></p><p>You learn the failure before the fix. That’s intentional. The skill that transfers to real engineering isn’t knowing pattern names — it’s being able to <em>name a failure you’ve never seen before</em> and reach for the minimum pattern that resolves it.</p><p>All code follows two rules: every function is five lines or fewer, and code is written high-level to low-level, threading a single state object down from orchestration to processing. The top function reads like the algorithm. You only descend into the <em>how</em> as far as you need.</p><h3>The full trajectory — read in order, or jump to your gap</h3><h3>Part I — Foundations (M0)</h3><p><strong>M0 — Foundations</strong></p><p>The failure modes are architectural, not model-quality. An LLM is a CPU; an agent is a process; a framework is an OS. The problem-first method. And the trap that kills more systems than any bug: over-architecting.</p><p><em>Read this before anything else.</em></p><h3>Part II — Core Reasoning Patterns (M1–M5)</h3><p>These are the five atomic patterns. Everything in orchestration, memory, and production ops is composed from them.</p><p><strong>M1 — ReAct</strong> The base reason→act→observe loop. How to close the open loop. Why you must always bound it.</p><p><strong>M2 — Tool Use</strong> Grounding: <em>if correctness matters, the LLM must not compute it.</em> Tools are the hard guarantee.</p><p><strong>M3 — Reflection</strong> Generate→critique→revise. This is risk reduction, not intelligence amplification. Know the difference.</p><p><strong>M4 — Planning</strong> The explicit plan object. How to reduce entropy before a long task begins. The rule: <em>no long task without a plan.</em></p><p><strong>M5 — Evaluator-Optimizer</strong> Separate the maker from the checker. This is the seed of your eval infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKlX0YgfBVbAKaE2.png" /></figure><h3>Part III — Orchestration (M6–M7)</h3><p><strong>M6 — Orchestrator</strong> Four coordination patterns: sequential, orchestrator-worker, fan-out, and handoff. Important note: <em>a single agent wins approximately 64% of the time.</em> The module teaches you to recognize that 64% before you reach for multi-agent complexity.</p><p><strong>M7 — Routing &amp; Supervisor</strong> Classify then dispatch. How to match cost to complexity. The hidden failure: misrouting is invisible — your system silently sends every request to the wrong handler.</p><h3>Part IV — Context &amp; Memory (M8–M9)</h3><p><strong>M8 — Context Engineering</strong> The context window is RAM, not storage. The four corruptions that destroy agent behavior: poisoning, distraction, confusion, and clash. How to engineer the window deliberately.</p><p><strong>M9 — Tiered Memory</strong> Working memory, session memory, long-term memory. The key question for every write: <em>is this relevant in 30 days?</em> How to scope writes and — critically — how to build the invalidation path before you need it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VeaxIVdEOsPTaEjA.png" /></figure><h3>Part V — Production Stack &amp; Ops (M10–M13)</h3><p><strong>M10 — Reliability Patterns</strong> Stop conditions, checkpointing, retry with backoff, fallback chains, and human-in-the-loop. How to build an agent that fails gracefully instead of silently.</p><p><strong>M11 — Guardrails &amp; Security</strong> Defense-in-depth at every boundary. Indirect prompt injection. The Layer-3 code boundary that must be a hard wall, not a suggestion.</p><p><strong>M12 — Observability &amp; Eval</strong> Trace every run. Eval is a first-class, continuous component — not a test suite you run once before shipping. The compounding feedback loop that makes every iteration better than the last.</p><p><strong>M13 — The Reference Stack</strong> Wire it all together. Clean layering beats framework choice. How real engineers grow an architecture from observed failures — not from whitepapers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0focZ3ruYSEJ2nB-.png" /></figure><h3>Part Two — Advanced &amp; Deep Patterns</h3><p>Once Part One is solid, three new pressures appear at scale. Part Two is about those pressures.</p><p><strong>The Part Two thesis:</strong> Advanced agent engineering is mostly distributed-systems engineering with an LLM in the loop.</p><h3>Frontier A — Multi-Agent Communication</h3><p>How agents communicate without a conductor. Message passing, blackboard patterns, pub-sub. Why ordering is the silent killer.</p><h3>Frontier B — Determinism, Economics &amp; Performance</h3><p>Semantic caching. Deterministic replay. Cost as a first-class architectural property — not an afterthought.</p><h3>Frontier C — Skills, Permissions &amp; Environment</h3><p>Capability manifests. Minimal, just-in-time permissions. MicroVM isolation. The principle of <em>concentric containment</em>: every layer assumes the one inside it is compromised.</p><h3>Frontier D — Self-Improvement &amp; Advanced Memory</h3><p>Reflexion. Episodic, semantic, and procedural memory taxonomy. The one rule that doesn’t change as models improve: <em>the agent never edits its own safety controls.</em></p><h3>The five threads that run through everything</h3><p>These are the patterns within the patterns. Spotting them is the difference between reading a glossary and developing an engineering instinct.</p><p><strong>1. Code guarantees; the model proposes.</strong> This appears as a reasoning rule in M2, a reliability rule in M10, and a security rule in M11. Same principle, three faces.</p><p><strong>2. Make the important thing an explicit object and re-inject it.</strong> The plan in M4, the pinned intent in M8, the scoped memory in M9. The fix for “the model loses the thread” is never a bigger context window.</p><p><strong>3. The state object is the trace.</strong> The scratch you thread through every loop is your observability layer. You build it for free as you build the agent.</p><p><strong>4. Proportionality — don’t over-architect.</strong> Stated in M0, enforced in M6, M9, M10, M11, and M12. The minimum structure that correctly serves the actual risk.</p><p><strong>5. Patterns compose.</strong> Planning calls ReAct (M4 ← M1). Reflection is ReAct turned inward (M3). Evaluator-optimizer grows into continuous eval (M5 → M12). The reference stack is all of them layered (M13).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2mXYiXLAY_GjfZfh.png" /></figure><h3>How to use this series</h3><p><strong>Reading the full course:</strong> Go M0 → M13 in order. Do not skip the “when NOT to use it” sections. They carry half the lesson. After Part One, take the exam closed-book, run the solution, and grade yourself. If you reached for a heavier pattern than the question needed, re-read M0 and M6.</p><p><strong>Jumping to your gap:</strong> Use the module descriptions above to locate your specific failure. If your agent loses context on long tasks, go to M8. If it’s not observable, go to M12. If it sometimes loops forever, go to M1 and M10. Each module is self-contained enough to read on its own.</p><p><strong>On the job:</strong> Start with one agent, good tools, and a trace. Add the <em>one</em> pattern that fixes your <em>observed</em> failure. Prove it with eval. Harden with stakes. That loop is the whole course applied.</p><h3>What comes next</h3><p>Each article in this series follows the map above — one module, one pattern, one real production failure, and the exact code that resolves it.</p><p>The next article covers <strong>M0 — Foundations</strong>: why production agent failures are architectural by nature, and why the most dangerous thing you can do when starting a new agent system is to reach for a framework before you understand the failure modes.</p><p><em>If this series is solving a problem you’ve felt before, follow me here — I’ll be publishing each module in order. Drop a comment below: which module are you most curious about? Your answer helps me know which failures resonate most with engineers right now.</em></p><p><em>And if you want to know the moment a new article drops — hit the email follow button. No noise, just the next module when it’s ready.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aee5063ae6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Pyramid: Which Level Are You — And Which One Should You Target?]]></title>
            <link>https://mohamed-stifi.medium.com/the-ai-pyramid-which-level-are-you-and-which-one-should-you-target-8217d8c691a9?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8217d8c691a9</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Sat, 16 May 2026 21:25:29 GMT</pubDate>
            <atom:updated>2026-05-16T21:25:29.081Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A guide for everyone — from curious beginners to domain experts — on how to find your place in the age of artificial intelligence.</em></p><p>Every day, millions of people open a browser, type something into an AI tool, and walk away either amazed or confused. Some get a recipe. Some generate an image. Some build an entire product. And some are the ones who built the AI itself.</p><p>The difference between these people is not intelligence. It is not even effort. It is <strong>clarity</strong> — knowing exactly which level of AI is relevant to <em>you</em>, and what you actually need to learn to unlock real value from it.</p><p>This article is about that clarity.</p><p>When most people search “how to use AI” on YouTube or Google, they are immediately flooded with content about deep learning, neural networks, PyTorch, LangChain, and model fine-tuning. And they close the tab feeling like AI is not for them — that it belongs to some elite circle of engineers with PhDs and years of mathematics behind them.</p><p>That is a lie. And this article is here to correct it.</p><p>AI is not one thing. It is a landscape with multiple levels — and each level has its own tools, its own learning curve, and its own rewards. The goal is not to climb to the top. The goal is to find <strong>your level</strong> and master it.</p><h3>The AI Pyramid</h3><p>Think of AI adoption as a pyramid. Three distinct levels, each representing a different relationship with artificial intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpbJIj9LG0vcWtStWDFe_w.png" /></figure><p>Let’s walk through each one.</p><h3>🔵 Level One: AI Consumers</h3><p><em>“Use It”</em></p><p>This is where most people are today — and there is absolutely nothing wrong with that.</p><p>AI Consumers are people who interact with AI through finished products. They use ChatGPT to draft emails, Midjourney to generate images, Sora or Runway to create short videos, and Claude to answer complex questions. They may not know what happens behind the interface. They do not need to.</p><p>The value for AI Consumers is immediate and personal:</p><ul><li>Writing faster</li><li>Learning something new in minutes instead of hours</li><li>Getting creative ideas on demand</li><li>Translating, summarizing, and organizing information effortlessly</li></ul><p>If you are an AI Consumer, you are already ahead of the majority of the world. The skill you need to develop at this level is not technical — it is <strong>conversational</strong>. Learning how to ask better questions, how to give context, how to guide the AI toward what you actually need. This is called prompt literacy, and it is more powerful than most people realize.</p><p><strong>Your target tools:</strong> ChatGPT, Claude, Gemini, Midjourney, Runway, ElevenLabs, Notion AI, and any AI-powered feature inside the apps you already use.</p><p><strong>What you do NOT need:</strong> Python, APIs, machine learning theory, or any form of coding.</p><h3>🟡 Level Two: AI Craftsmen</h3><p><em>“Master It”</em></p><p>This is the most exciting level — and the most misunderstood.</p><p>AI Craftsmen are professionals who already have deep domain expertise. They are software developers, marketers, video editors, project managers, founders, designers, writers, and researchers. What makes them Craftsmen is not just that they <em>use</em> AI — it is that they have fundamentally transformed how they work by making AI their <strong>daily partner</strong>.</p><p>Think about a software developer. Before AI, their day looked like this: architecture planning, writing code, reviewing output, debugging, improving, repeating. That same developer, as an AI Craftsman, now does all of that — but with AI sitting beside them at every step. They use Claude Code to generate production-level code. They use AI to review their architecture decisions. They use agents to automate testing pipelines. They are no longer a single developer. They operate like a small team.</p><p>Or think about a marketer. They use AI agents to research audiences, generate content variations, build automated campaign workflows, and analyze results — all within their existing marketing knowledge. They do not need to understand how a language model was trained. They need to understand their audience, their strategy, and which AI tools serve that strategy best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvgsai0Gem3-TF6mFuwy4w.png" /></figure><p>What separates an AI Craftsman from an AI Consumer is this: <strong>they produce</strong>. They do not just get answers — they build things, deliver work, generate income, and create value using the combination of their human knowledge and AI capability. They learn faster, ship faster, think faster, and produce at a quality and speed that would have required an entire team just a few years ago.</p><p>The knowledge required at this level is two-layered:</p><ol><li><strong>Deep domain expertise</strong> — you must know your field well</li><li><strong>AI tool fluency</strong> — you must know which AI tools serve your domain and how to use them with precision</li></ol><p>This is not about learning to code (unless you are a developer). It is about learning the right tools for your profession.</p><p><strong>If you are a software developer or founder:</strong> In 2026, the top developers are not just writing code — they are orchestrating AI agents across their entire codebase. Claude Code has become the #1 AI coding tool, rated by developers for its ability to reason across entire projects with up to 1 million tokens of context. Cursor brings AI deeply into the IDE for real-time multi-file editing. GitHub Copilot automates pull requests, opens branches, writes tests, and reviews code autonomously. For building AI-powered products, tools like LangGraph and n8n let you design agent workflows without deep ML knowledge. The shift is clear: 95% of developers now use AI tools weekly, and over 51% of all code committed to GitHub is AI-assisted.</p><p><strong>If you are a marketer or content creator:</strong> Your toolkit has never been more powerful. Claude and ChatGPT serve as your strategic thinking partners — for campaign strategy, SEO content, audience research, and brand voice. Jasper brings brand consistency at scale across large marketing teams. Surfer SEO scores your content against top-ranking pages in real time. For social and short-form content, Copy.ai generates ad variations and captions in seconds. For research, Perplexity gives you cited, synthesized answers instantly. The shift in 2026: marketers are becoming product builders — tools like Lovable, Bolt, and v0 let marketers build internal tools and landing pages simply by describing them in natural language.</p><p><strong>If you are a video editor or creative:</strong> The video production landscape has transformed entirely. Runway generates cinematic sequences from text prompts. Sora 2 acts like an AI director — turning narrative ideas into coherent visual sequences with audio included. For AI avatars and multilingual content, HeyGen creates photorealistic spokespersons in 65+ languages without a camera or studio. Descript makes editing as simple as editing a document — cut the transcript, the video edits itself. Adobe Premiere Pro now has Generative Extend and text-based editing built in. For short-form repurposing, OpusClip and CapCut turn long videos into platform-ready clips automatically. According to recent data, AI has improved video editing efficiency by over 60% for professional editors compared to manual workflows two years ago.</p><p><strong>If you are a project manager or operations professional:</strong> Your power is in orchestration. AI-powered workflow tools like n8n, Make.com, and Zapier AI let you automate entire operational pipelines without writing code. Notion AI brings intelligence into your planning and documentation. Claude serves as your thinking partner for strategy, meeting summaries, and stakeholder communication. The Craftsman mindset here is about identifying which repetitive processes in your workflow can be handed to an AI agent — and designing systems that run themselves.</p><p><strong>What you do NOT need:</strong> to train models, write neural networks, or understand the mathematics of transformers.</p><h3>🔴 Level Three: AI Engineers</h3><p><em>“Build It”</em></p><p>At the top of the pyramid are the people who build what everyone else uses.</p><p>But here is something that most articles get wrong: the image of an AI Engineer as someone who spends their days writing neural networks from scratch with a mathematics textbook open beside them — that image is outdated.</p><p>The modern AI Engineer is first and foremost a <strong>software engineer who thinks in AI systems</strong>. They do not reinvent the wheel. They architect, integrate, and deploy AI at scale. Their superpower is knowing <em>when</em> to use an existing model, <em>when</em> to fine-tune it, and <em>when</em> to build on top of it — and how to connect all of that into a system that actually works in production.</p><p>Think about what it means to build a computer vision product today. You do not start by training a model from scratch. You start by understanding the problem — what data you have, what accuracy you need, what latency you can afford. Then you evaluate existing APIs and pre-trained models. You design the database and data pipeline. You manage the infrastructure for serving the model at scale. You fine-tune when necessary. You ship. That is modern AI engineering.</p><p>Or think about building an intelligent agent system. You need to understand context engineering — how to structure information so the model reasons correctly. You need to design the agent’s memory, its tools, its decision logic. You need to manage failures gracefully. This requires software engineering depth, system design thinking, and AI knowledge — not a PhD in mathematics.</p><p><strong>What a modern AI Engineer actually needs:</strong></p><ul><li>Strong <strong>software engineering fundamentals</strong> — system design, databases, APIs, infrastructure, and scalable architecture</li><li><strong>AI and ML foundations</strong> — understanding how models work, their strengths and limitations, how training and fine-tuning operate conceptually</li><li><strong>Context engineering and agent design</strong> — knowing how to build systems where AI reasons, acts, and improves reliably</li><li><strong>Integration skills</strong> — selecting and connecting the right models, APIs, and tools (computer vision APIs, embedding models, LLMs) for each use case</li><li><strong>MLOps awareness</strong> — deploying, monitoring, and improving AI systems in production</li></ul><p>Some AI Engineers go deeper — into research, model architecture, and training at scale. That path exists and is valuable. But the majority of AI Engineers being hired and building products today are software engineers who have mastered how to think with AI, build with AI, and deploy AI systems that create real value.</p><p><strong>AI Engineers are also built on top of the levels below them.</strong> The best ones have been AI Craftsmen first. They understand real-world problems because they have lived inside them.</p><h3>AI Is Not Here to Replace You. It Is Here to Complete You.</h3><p>This is perhaps the most important thing this article can leave you with.</p><p>Every conversation about AI eventually arrives at the same fear: <em>“Will AI take my job?”</em></p><p>The answer — at least for now, and for the foreseeable future — is this: <strong>AI will not replace people who know how to use it.</strong> It will replace people who refuse to.</p><p>The developer who uses Claude Code does not get replaced by AI — they become five developers in one. The marketer who builds AI-powered workflows does not get automated away — they become a marketing department of one. The video editor who integrates AI tools does not lose their craft — they gain a creative superpower.</p><p>AI does not erase your expertise. It <strong>amplifies</strong> it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxzcAxOJA7PH1vgUJT8DIQ.png" /></figure><h3>So — Which Level Are You?</h3><p>Here is a simple way to find out:</p><p><strong>You are an AI Consumer if:</strong> You use AI products daily for personal productivity, creativity, or curiosity — and you want to get better at asking the right questions.</p><p><strong>You are (or should become) an AI Craftsman if:</strong> You have a profession, a domain, a skill set — and you want AI to become your partner in that work, not just a tool you occasionally open.</p><p><strong>You are (or should become) an AI Engineer if:</strong> You want to build the future of AI itself — to design systems, train models, and create the tools that others will use.</p><p>There is no wrong level. There is only the wrong level <em>for you</em>.</p><h3>Your Next Step</h3><p>Do not search for “AI tutorials” and drown in content about deep learning if you are a marketer. Do not stay at the Consumer level if you are a professional who could be operating like a full team.</p><p>Find your pyramid level. Target the tools and knowledge that belong to it. And start building — whatever that means for you.</p><p>The AI era is not a threat to your career or your creativity. It is the greatest amplifier your generation has ever been handed.</p><p>The only question is: <strong>are you going to pick it up?</strong></p><p><em>If this article helped you find your place in the AI pyramid, share it with someone who is still searching. The more people who understand their level, the faster we all move forward — together.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8217d8c691a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering MLflow: The Complete MLOps Workflow from Experiment to Production]]></title>
            <link>https://mohamed-stifi.medium.com/mastering-mlflow-the-complete-mlops-workflow-from-experiment-to-production-3b78b8c8abe1?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b78b8c8abe1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 03:39:37 GMT</pubDate>
            <atom:updated>2025-12-02T03:39:37.741Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering MLflow: From Experiment Tracking to Production-Ready MLOps</strong></h3><h3><em>A hands-on guide to building reproducible, scalable, and automated ML workflows with MLflow.</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vvS_GIziqZ7GfU7z.jpg" /></figure><p>If you’ve ever trained a machine learning model only to realize you can’t reproduce it, struggled to track dozens of hyperparameter experiments, or found yourself manually copying model files to servers, you’re not alone. In the messy lifecycle of an ML project — experimentation, tracking, packaging, deployment, and monitoring — it’s easy to lose control.</p><p>That’s where MLflow comes in. Created by Databricks, MLflow is an open-source platform designed to bring order to the chaos of machine learning operations. It’s not just another experiment tracker — it’s a comprehensive framework that covers the entire ML lifecycle.</p><p>In this guide, I’ll walk you through MLflow from first principles to production-grade workflows. Whether you’re a data scientist tired of spreadsheet tracking or an ML engineer building reproducible pipelines, you’ll learn how MLflow can transform how you develop, deploy, and manage models.</p><h3>Getting Started: Installation and Setup</h3><p>Let’s begin with the basics. Installation is straightforward:s</p><pre>!pip install mlflow --quiet</pre><p>No complex dependencies, no heavy configurations. MLflow runs locally out of the box, creating a simple file-based tracking system. But as we’ll see later, this is just the beginning — MLflow scales from local development to enterprise deployments.</p><h3>MLflow Tracking: Your Experimentation Foundation</h3><p>At its core, MLflow Tracking is a logging API that records everything about your experiments: parameters, metrics, artifacts, and models. Think of it as version control for machine learning.</p><p>Here’s how you start a basic run:</p><pre>import mlflow<br>import random<br><br>with mlflow.start_run(run_name=&#39;run_0_test&#39;):<br>    # Log parameters (hyperparameters, configuration)<br>    lr = 0.01<br>    epochs = 5<br>    mlflow.log_param(&quot;learning_rate&quot;, lr)<br>    mlflow.log_param(&quot;epochs&quot;, epochs)<br>    <br>    # Simulate training loop<br>    for epoch in range(epochs):<br>        loss = 1.0 - (epoch * 0.2) + random.uniform(-0.1, 0.1)<br>        # Log metrics (can be called multiple times)<br>        mlflow.log_metric(&quot;loss&quot;, loss, step=epoch)</pre><p>Notice the pattern: start_run() creates a context, log_param() records static values, and log_metric() tracks evolving metrics. This simple structure is powerful — it creates a complete audit trail of what you tried and how it performed.</p><h3>Where Does This Data Go?</h3><p>By default, MLflow creates a local mlruns/ directory with a nested structure:</p><pre>mlruns/<br>├── 0/<br>│   └── meta.yaml<br>├── 1/<br>│   ├── meta.yaml<br>│   └── c982ec76ed22425d81b420990cb6165e/<br>│       ├── meta.yaml<br>│       ├── metrics/<br>│       ├── params/<br>│       └── artifacts/</pre><p>Each run gets its own folder with everything neatly organized. But here’s the catch: file-based storage doesn’t scale for teams. We’ll address this when we discuss production architecture.</p><h3>Visualizing Experiments: The MLflow UI</h3><p>While the file structure gives you raw access to your data, the true power of MLflow’s tracking becomes apparent when you launch the MLflow UI. This web interface turns your scattered experiments into a searchable, sortable dashboard where you can compare runs, visualize metrics, and drill down into details.</p><p>To launch the UI, simply run:</p><pre>mlflow ui</pre><p>This starts a local server (typically on http://localhost:5000) where you can:</p><ul><li>Compare multiple runs side-by-side with metrics, parameters, and tags</li><li>Filter and search experiments by any criteria (e.g., “accuracy &gt; 0.9”)</li><li>Visualize metric histories with interactive charts</li><li>View and download artifacts (models, plots, configuration files)</li><li>Register models directly from the UI</li></ul><p>For teams using a centralized tracking server, the UI becomes even more powerful — everyone can view the same experiments, collaborate on model selection, and maintain a shared understanding of what’s been tried and what works best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1YHerETtFf46hobF.png" /><figcaption><em>MLflow UI with experiment runs, and metric charts</em></figcaption></figure><p>The UI isn’t just a nice-to-have visualization tool; it’s a critical component of the data science workflow. It transforms ML experimentation from a “black box” process into a transparent, auditable, and collaborative practice. Whether you’re a solo researcher trying to remember which hyperparameters worked best or a team lead reviewing work before production deployment, the MLflow UI provides the visibility you need.</p><h3>Autologging: Let MLflow Do the Heavy Lifting</h3><p>Manually logging every parameter and metric gets tedious fast. That’s where autologging shines:</p><pre>mlflow.sklearn.autolog()<br><br>with mlflow.start_run(run_name=&quot;RandomForest_Autolog_Demo&quot;):<br>    rf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)<br>    rf.fit(X_train, y_train)  # MLflow captures everything automatically!</pre><p>Enable autologging before your training code, and MLflow will automatically detect and log:</p><ul><li>All model parameters</li><li>Training metrics</li><li>Model artifacts</li><li>Library versions</li><li>Even feature importance for some models</li></ul><p>Supported frameworks include Scikit-learn, TensorFlow, PyTorch, XGBoost, LightGBM, and more. It’s like having an assistant who documents every experiment for you.</p><h3>The MLmodel Format: More Than Just a Pickle File</h3><p>When MLflow saves a model, it doesn’t just pickle it. It creates a structured directory with an MLmodel file that describes how to load and use the model:</p><pre>model/<br>├── MLmodel<br>├── conda.yaml<br>├── python_env.yaml<br>└── model.pkl</pre><p>The MLmodel file contains metadata about the model flavor (sklearn, pytorch, etc.), signature (input/output schema), and environment requirements. This standardized format enables two loading approaches:</p><pre># Option A: Native flavor (framework-specific)<br>sklearn_model = mlflow.sklearn.load_model(f&quot;runs:/{run_id}/model&quot;)<br><br># Option B: PyFunc flavor (generic Python function)<br>pyfunc_model = mlflow.pyfunc.load_model(f&quot;runs:/{run_id}/model&quot;)</pre><p>The PyFunc interface is particularly powerful — it abstracts away framework differences, making deployment consistent whether you’re serving Scikit-learn, PyTorch, or custom models.</p><h3>The Model Registry: From Experiment to Production</h3><p>Experimentation is just the beginning. The real challenge is managing model versions as they move through development, testing, and production. Enter the Model Registry.</p><p>Think of the Model Registry as a centralized catalog for your models. It introduces three key concepts:</p><ol><li>Registered Model: A named container (e.g., “FraudDetector”)</li><li>Model Version: Immutable snapshot (Version 1, 2, 3…)</li><li>Model Stage: Lifecycle label (None → Staging → Production → Archived)</li></ol><p>Here’s how you register and promote a model:</p><pre># Register a model from an experiment run<br>model_uri = f&quot;runs:/{run_id}/model&quot;<br>model_version = mlflow.register_model(model_uri, &quot;Iris_Production_Model&quot;)<br><br># Transition through stages<br>from mlflow.tracking import MlflowClient<br>client = MlflowClient()<br>client.transition_model_version_stage(<br>    name=&quot;Iris_Production_Model&quot;,<br>    version=model_version.version,<br>    stage=&quot;Staging&quot;<br>)</pre><p>The stage-based workflow mirrors real-world deployment pipelines:</p><ul><li>None: Newly registered model</li><li>Staging: Ready for testing/validation</li><li>Production: Live in serving</li><li>Archived: Retired but kept for reference</li></ul><h3>Serving Models: From Code to API</h3><p>A model in the registry is useless if you can’t serve predictions. MLflow makes deployment remarkably simple:</p><pre># Start a REST API server<br>mlflow models serve -m &quot;models:/Iris_Production_Model/Staging&quot; -p 1234 --no-conda</pre><p>This single command spins up a production-ready web server with:</p><ul><li>Automatic input validation (using the model signature)</li><li>Batch prediction support</li><li>Health endpoints</li><li>Standardized request/response format</li></ul><p>Clients can then send requests:</p><pre>import requests<br>import json<br><br>url = &quot;http://127.0.0.1:1234/invocations&quot;<br>data = {<br>    &quot;dataframe_split&quot;: {<br>        &quot;columns&quot;: [&quot;sepal length&quot;, &quot;sepal width&quot;, &quot;petal length&quot;, &quot;petal width&quot;],<br>        &quot;data&quot;: [[5.1, 3.5, 1.4, 0.2]]<br>    }<br>}<br><br>response = requests.post(url, json=data, headers={&quot;Content-Type&quot;: &quot;application/json&quot;})<br>print(f&quot;Prediction: {response.json()}&quot;)</pre><p>The beauty of using stage-based URIs (models:/ModelName/Staging) is that you can promote new versions without changing client code. When you move Version 2 to Production, all clients automatically get the new model.</p><h3>MLflow Projects: Packaging for Reproducibility</h3><p>How do you ensure your training code runs the same way on your laptop, your colleague’s machine, and in production? MLflow Projects solves this with a standardized packaging format.</p><p>A project is defined by two files:</p><p>1. MLproject (YAML configuration):</p><pre>name: Iris_Project<br><br>entry_points:<br>  main:<br>    parameters:<br>      n_estimators: {type: int, default: 100}<br>      max_depth: {type: int, default: 5}<br>    command: &quot;python train.py --n_estimators {n_estimators} --max_depth {max_depth}&quot;</pre><p>2. conda.yaml (environment specification):</p><pre>name: ml-env<br>dependencies:<br>  - python=3.9<br>  - scikit-learn<br>  - mlflow<br>  - pip</pre><p>Run the project with:</p><pre>mlflow run . -P n_estimators=200 -P max_depth=10</pre><p>MLflow automatically:</p><ol><li>Creates a Conda environment with the specified dependencies</li><li>Runs your training code with the provided parameters</li><li>Logs everything to the tracking server</li></ol><p>This ensures complete reproducibility — anyone with the project files can recreate your exact experiment</p><h3>Dockerizing for Production Consistency</h3><p>While Conda handles Python dependencies, it doesn’t guarantee system-level consistency. For true production reproducibility, you need Docker.</p><p>MLflow Projects seamlessly integrates with Docker:</p><pre># MLproject with Docker<br>name: Iris_Docker_Project<br>docker_env:<br>  image: .  # Build from local Dockerfile<br>entry_points: ...</pre><p>With a simple Dockerfile:</p><pre>FROM python:3.9-slim<br>RUN pip install mlflow scikit-learn pandas</pre><p>Now when you run mlflow run ., MLflow:</p><ol><li>Builds the Docker image</li><li>Mounts your code into the container</li><li>Executes the training inside the containerized environment</li></ol><p>This guarantees identical behavior regardless of the host system — the gold standard for production ML.</p><h3>Production Architecture: Beyond Local Development</h3><p>Local file-based tracking is fine for experimentation, but real teams need scalable infrastructure. Here’s the production architecture pattern:</p><pre>mlflow server \<br>    --backend-store-uri postgresql://user:password@rds-endpoint:5432/mlflowdb \<br>    --default-artifact-root s3://my-company-mlflow-artifacts/ \<br>    --host 0.0.0.0 \<br>    --port 5000</pre><p>This single command sets up:</p><ul><li>PostgreSQL/RDS: For metadata (runs, parameters, metrics)</li><li>S3/Blob Storage: For large artifacts (models, plots, datasets)</li><li>EC2/Container: For the MLflow server process</li></ul><p>The architecture separates concerns:</p><ul><li>Lightweight metadata goes to the database (fast queries)</li><li>Heavy artifacts go to object storage (cost-effective)</li><li>The server orchestrates everything</li></ul><h3>Remote Tracking: Managed Services</h3><p>If managing infrastructure isn’t your priority, consider managed MLflow:</p><p>Databricks (Managed MLflow):</p><pre>mlflow.set_tracking_uri(&quot;databricks&quot;)<br>mlflow.set_experiment(&quot;/Users/your_email@company.com/MyExperiment&quot;)</pre><p>MLflow on Cloud Providers:</p><ul><li>AWS: SageMaker Experiments + MLflow</li><li>Azure: Azure Machine Learning + MLflow</li><li>GCP: Vertex AI + MLflow</li></ul><p>These services handle scaling, security, and maintenance, letting you focus on ML rather than infrastructure.</p><h3>CI/CD Integration: Automating the Pipeline</h3><p>The final piece of the MLOps puzzle is automation. Here’s a GitHub Actions workflow that trains and registers models on every push:</p><pre>name: MLflow Training Pipeline<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  train-model:<br>    runs-on: ubuntu-latest<br>    <br>    steps:<br>    - uses: actions/checkout@v3<br>    <br>    - name: Set up Python 3.9<br>      uses: actions/setup-python@v4<br>      with:<br>        python-version: &#39;3.9&#39;<br>        <br>    - name: Install dependencies<br>      run: pip install mlflow scikit-learn<br>    <br>    - name: Train Model<br>      env:<br>        MLFLOW_TRACKING_URI: ${{ secrets.MLFLOW_TRACKING_URI }}<br>        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>      run: |<br>        mlflow run . --env-manager=local -P n_estimators=150<br>        # Register best model<br>        python register_best_model.py</pre><p>This automation ensures that:</p><ol><li>Every code change triggers retraining</li><li>Models are automatically registered</li><li>Quality gates can be added (e.g., minimum accuracy thresholds)</li><li>The entire pipeline is reproducible and auditable</li></ol><p><em>[In a future article, I’ll dive deeper into implementing CI/CD, and Continuous Training (CT) pipelines with GitHub Actions ]</em></p><h3>The Complete MLOps Workflow</h3><p>Putting it all together, here’s how MLflow enables end-to-end MLOps:</p><ol><li>Experimentation: Data scientists run experiments with mlflow run, comparing results in the UI</li><li>Selection: Best models are identified based on validation metrics</li><li>Registration: Selected models are registered in the Model Registry</li><li>Validation: Automated tests run on Staging models</li><li>Deployment: Approved models are promoted to Production</li><li>Serving: Applications load models:/ModelName/Production via REST API</li><li>Monitoring: Model performance is tracked in production</li><li>Retraining: New data triggers automated retraining pipelines</li></ol><h3>Key Takeaways and Best Practices</h3><p>After working with MLflow, here are my hard-earned lessons:</p><p>Do:</p><ul><li>Start with local tracking but plan for centralized infrastructure early</li><li>Use autologging but supplement with custom metrics for business logic</li><li>Register models immediately after promising experiments</li><li>Use stage-based model URIs in production code</li><li>Package projects with Docker for true reproducibility</li><li>Implement CI/CD from day one [ you can CT for more production level]</li></ul><p>Don’t:</p><ul><li>Rely on local file storage for team projects</li><li>Hardcode run IDs in production code</li><li>Skip model validation before promotion</li><li>Forget to set resource limits on automatic experiment runs</li><li>Neglect to monitor model performance post-deployment</li></ul><h3>Looking Ahead: The Future of MLflow</h3><p>MLflow continues to evolve with exciting developments:</p><ul><li>MLflow 2.0: Improved UI, faster queries, enhanced model evaluation</li><li>LLM Tracking: Specialized support for large language models</li><li>Feature Store Integration: Tighter integration with Feast, Tecton</li><li>Enhanced Monitoring: Built-in drift detection and performance tracking</li></ul><p>The platform is becoming increasingly essential in the MLOps ecosystem, positioned as the glue between data science experimentation and engineering production.</p><h3>Your Next Steps</h3><p>Ready to implement MLflow in your projects? Here’s a practical roadmap:</p><ol><li>Install MLflow, convert one existing script to use tracking</li><li>Set up a centralized tracking server (even if just SQLite + local folder)</li><li>Containerize one project with Docker</li><li>Implement CI/CD for automatic retraining</li><li>Design your production architecture (cloud provider choice)</li><li>Establish team workflows and review processes</li></ol><p>Remember, MLOps maturity is a journey, not a destination. Start small, iterate, and continuously improve your processes.</p><p>Explore the complete code examples from this article in the <a href="https://github.com/mohamed-stifi/MLflow/blob/main/MLflow_tutorial_doc.ipynb">GitHub repository</a>. Clone it, run the examples, and adapt them to your use cases.</p><p>The power of MLflow isn’t just in the features — it’s in the workflow it enables. By bringing discipline to machine learning development, it transforms ML from a research activity into a reliable engineering practice. Your future self (and your team) will thank you.</p><p><em>Have you implemented MLflow in your organization? What challenges did you face? Share your experiences in the comments below — let’s learn from each other’s journeys toward better MLOps.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b78b8c8abe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shrink Your PyTorch Models: The Ultimate Guide to Pruning AI]]></title>
            <link>https://mohamed-stifi.medium.com/shrink-your-pytorch-models-the-ultimate-guide-to-pruning-ai-30149badf95d?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30149badf95d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 14:50:27 GMT</pubDate>
            <atom:updated>2025-10-09T14:50:27.769Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Deep Theory to Practical Code: A Step-by-Step Tutorial for Making Your Models Smaller, Faster, and More Efficient</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w2R7d-X8_SMGzG55.png" /><figcaption><em>Image by </em><a href="https://blog.tensorflow.org/2019/05/tf-model-optimization-toolkit-pruning-API.html">tensorflow blog</a><em>. A dense network (left) becomes a sparse, efficient subnetwork (right) after pruning.</em></figcaption></figure><p>You’ve done it. You’ve trained a massive deep learning model that achieves state-of-the-art accuracy. But there’s an elephant in the room: your model is a behemoth. It’s too big to deploy on a smartphone, too slow for real-time inference, and costs a fortune to run in the cloud.</p><p>What if you could surgically remove the &quot;unimportant&quot; parts of your model, making it drastically smaller and faster without sacrificing performance?</p><p>This isn&#39;t a fantasy. It&#39;s a powerful technique called <strong>pruning</strong>. Inspired by how the human brain eliminates unused synaptic connections, model pruning systematically removes redundant weights from a neural network, revealing a lean, efficient subnetwork hidden within.</p><p>In this guide, we&#39;ll take a deep dive into the world of model pruning. We will cover:</p><ul><li><strong>The What &amp; Why:</strong> The core concepts, from the theory of over-parameterization to the critical difference between unstructured and structured pruning.</li><li><strong>The How with PyTorch:</strong> A look at PyTorch&#39;s elegant <em>torch.nn.utils.prune</em> module that makes pruning a breeze.</li><li><strong>A Full Walkthrough:</strong> A complete, hands-on example where we train a CNN on CIFAR-10, prune it, and witness the dramatic reduction in size and computation.</li></ul><p>Let&#39;s begin.</p><h3>Part 1: The Theory — What’s Really Happening When We Prune?</h3><p>The magic of deep learning lies in over-parameterization. We intentionally create models with millions (or billions!) of parameters, giving them the capacity to learn complex patterns. However, research has shown that not all of these parameters are created equal. Many are redundant or contribute very little to the final prediction.</p><p>The central idea of pruning is to identify and eliminate these less important parameters.</p><h3>The Most Important Distinction: Unstructured vs. Structured Pruning</h3><p>This is the single most critical concept to understand because it determines whether you get real-world speedups.</p><h4>Unstructured Pruning (Weight Pruning)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*E8cqz8l9bbvlhzT1dPdCHw.png" /></figure><ul><li><strong>What it is:</strong> Removing individual weights anywhere in the network, based on some importance score (like their magnitude).</li><li><strong>Analogy:</strong> Plucking random leaves off a bonsai tree.</li><li><strong>Result:</strong> This creates sparse matrices with zeros sprinkled all over the place. While it can achieve very high compression ratios (e.g., 90% of weights removed) with minimal accuracy loss, it runs into a major problem.</li><li><strong>The Hardware Gap:</strong> Standard CPUs and GPUs are terrible at handling sparse matrices. They are optimized for dense, regular computations. So, even if you have 90% sparsity, you often won’t see a 90% speedup. You need specialized hardware (like NVIDIA’s Sparse Tensor Cores) or libraries to see a benefit.</li></ul><blockquote><em>Unstructured pruning creates irregular sparsity, while structured pruning removes entire groups, maintaining a dense structure that hardware loves.</em></blockquote><h4>Structured Pruning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*TtwnukIZTAYO2rfL4S7vMg.png" /></figure><ul><li><strong>What it is:</strong> Removing entire groups of parameters together. This could mean entire filters in a convolutional layer or entire neurons (columns) in a fully connected layer.</li><li><strong>Analogy:</strong> Cutting off whole branches from the bonsai tree.</li><li><strong>Result:</strong> The weight matrices shrink in size but remain dense and regular.</li><li><strong>The Payoff:</strong> This is what gives you <strong>real, measurable speedups on standard hardware</strong>. By removing an entire filter, you reduce the number of convolutions the GPU has to perform.</li></ul><blockquote><strong>Key Takeaway:</strong> If your goal is just to reduce model storage size, unstructured pruning is fine. If you want a <strong>faster model</strong>, you <strong>must</strong> use structured pruning.</blockquote><h3>Part 2: The “How” with PyTorch’s Pruning API</h3><p>PyTorch provides a wonderfully simple and powerful API in <em>torch.nn.utils.prune</em>. Its core philosophy is <strong>non-destructive pruning</strong>. Instead of immediately deleting weights, it applies a <em>mask</em> to them.</p><p>Here’s how it works under the hood:</p><ul><li>When you prune a layer’s weight tensor, PyTorch renames it to weight_orig.</li><li>It creates a new binary tensor called weight_mask (0 for pruned, 1 for kept).</li><li>The weight attribute is then dynamically computed on every forward pass as weight = weight_orig * weight_mask.</li></ul><p>This is brilliant because you can continue training (fine-tuning) your model, and the gradients will only flow through the unpruned weights. Once you’re satisfied, you can make the pruning permanent.</p><h3>Part 3: A Full Walkthrough on CIFAR-10</h3><p>Theory is great, but let’s see this in action. We’ll follow the complete workflow:</p><ul><li>Train a dense baseline model.</li><li>Apply structured pruning.</li><li>Fine-tune the pruned model.</li><li>Make the pruning permanent and compare the results.</li></ul><p>Here is the complete code from our notebook.</p><h3>Step 1: Setup and Baseline Model Training</h3><p>First, let’s set up our environment, data, model, and helper functions.</p><pre># install torchinfo<br>!pip install torchinfo</pre><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torchvision<br>import torchvision.transforms as transforms<br>from torch.nn.utils import prune<br>from torchinfo import summary<br><br># --- 1. SETUP: Data, Model, Helpers ---<br><br># Device configuration<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br># Data<br>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))<br>])<br>trainset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=True, download=True, transform=transform)<br>trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True)<br>testset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=False, download=True, transform=transform)<br>testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False)<br><br># A slightly larger model for CIFAR10<br>class SimpleCNN(nn.Module):<br>    def __init__(self):<br>        super(SimpleCNN, self).__init__()<br>        self.features = nn.Sequential(<br>            nn.Conv2d(3, 64, kernel_size=3, padding=1),<br>            nn.ReLU(inplace=True),<br>            nn.MaxPool2d(kernel_size=2, stride=2),<br>            nn.Conv2d(64, 128, kernel_size=3, padding=1),<br>            nn.ReLU(inplace=True),<br>            nn.MaxPool2d(kernel_size=2, stride=2),<br>        )<br>        self.classifier = nn.Sequential(<br>            nn.Linear(128 * 8 * 8, 256),<br>            nn.ReLU(inplace=True),<br>            nn.Linear(256, 10),<br>        )<br>    def forward(self, x):<br>        x = self.features(x)<br>        x = x.view(x.size(0), -1)<br>        x = self.classifier(x)<br>        return x<br><br># Helper functions for training and testing<br>def train(model, dataloader, epochs=5):<br>    criterion = nn.CrossEntropyLoss()<br>    optimizer = optim.Adam(model.parameters(), lr=0.001)<br>    for epoch in range(epochs):<br>        for i, (images, labels) in enumerate(dataloader):<br>            images, labels = images.to(device), labels.to(device)<br>            optimizer.zero_grad()<br>            outputs = model(images)<br>            loss = criterion(outputs, labels)<br>            loss.backward()<br>            optimizer.step()<br>        print(f&quot;Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}&quot;)<br><br>def test(model, dataloader):<br>    model.eval()<br>    correct = 0<br>    total = 0<br>    with torch.no_grad():<br>        for images, labels in dataloader:<br>            images, labels = images.to(device), labels.to(device)<br>            outputs = model(images)<br>            _, predicted = torch.max(outputs.data, 1)<br>            total += labels.size(0)<br>            correct += (predicted == labels).sum().item()<br>    accuracy = 100 * correct / total<br>    model.train()<br>    return accuracy</pre><p>Now, let’s train our dense baseline model for a few epochs.</p><pre>print(&quot;--- Training Dense Model ---&quot;)<br>dense_model = SimpleCNN().to(device)<br>train(dense_model, trainloader, epochs=3) # Use more epochs for better results<br>dense_accuracy = test(dense_model, testloader)<br>print(f&quot;Dense model accuracy: {dense_accuracy:.2f}%&quot;)</pre><pre>- - Training Dense Model - -<br>Epoch [1/3], Loss: 0.9805<br>Epoch [2/3], Loss: 0.7542<br>Epoch [3/3], Loss: 0.6401<br>Dense model accuracy: 71.93%</pre><p>Let’s inspect our dense model. Note the total parameters and computational cost (Mult-Adds).</p><pre>summary(dense_model, input_size=(1, 3, 32, 32))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*XYXztGFhmc9_p_fGVBa4lA.png" /></figure><p>Our baseline model has <strong>~2.17M parameters</strong> and requires <strong>0.08 Giga-MACs</strong> (Multiply-Accumulate operations) per forward pass.</p><h3>Step 2: Apply Structured Pruning</h3><p>Now for the exciting part. We’ll create a copy of our trained model and apply <strong>structured pruning</strong>. We will prune 40% of the filters in the convolutional layers and 40% of the neurons in the linear layer, based on their L2 norm.</p><p>The key here is dim=0, which tells PyTorch to prune along the output channel/neuron dimension.</p><pre>pruned_model = SimpleCNN().to(device)<br>pruned_model.load_state_dict(dense_model.state_dict()) # Start with trained weights<br><br># We&#39;ll do structured pruning for real benefits<br>prune.ln_structured(pruned_model.features[0], name=&#39;weight&#39;, amount=0.4, n=2, dim=0)<br>prune.ln_structured(pruned_model.features[3], name=&#39;weight&#39;, amount=0.4, n=2, dim=0)<br>prune.ln_structured(pruned_model.classifier[0], name=&#39;weight&#39;, amount=0.4, n=2, dim=0)</pre><p>Let’s check the model’s state_dict. Notice the weight_orig and weight_mask parameters that have appeared.</p><pre>print(pruned_model.state_dict().keys())</pre><pre>odict_keys([<br>            &#39;features.0.bias&#39;, &#39;features.0.weight_orig&#39;, <br>            &#39;features.0.weight_mask&#39;, &#39;features.3.bias&#39;, <br>            &#39;features.3.weight_orig&#39;, &#39;features.3.weight_mask&#39;, <br>            &#39;classifier.0.bias&#39;, &#39;classifier.0.weight_orig&#39;, <br>            &#39;classifier.0.weight_mask&#39;, &#39;classifier.2.weight&#39;, <br>            &#39;classifier.2.bias&#39;<br>])</pre><h3>Step 3: Fine-Tune the Pruned Model</h3><p>Pruning damages the network, so we need to “heal” it by fine-tuning for a few epochs, typically with a lower learning rate.</p><pre>print(&quot;\n--- Fine-tuning Pruned Model ---&quot;)<br># Use a lower learning rate for fine-tuning<br>train(pruned_model, trainloader, epochs=2)<br>pruned_accuracy = test(pruned_model, testloader)<br><br>print(f&quot;Pruned model accuracy (after fine-tuning): {pruned_accuracy:.2f}%&quot;)</pre><pre>--- Fine-tuning Pruned Model ---<br>Epoch [1/2], Loss: 0.7725<br>Epoch [2/2], Loss: 0.6744<br>Pruned model accuracy (after fine-tuning): 74.15%</pre><p>Fantastic! The accuracy has almost fully recovered.</p><p>Now, let’s look at the final summary. This is the moment of truth.</p><pre>summary(pruned_model, input_size=(1, 3, 32, 32))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*YhDR3O7JhRvDjdqQRmEZUQ.png" /></figure><h3>Part 4: The Payoff — Before vs. After</h3><p>Let’s summarize our incredible results in a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*nvBt8la-p-xeTO0Hg0pOBg.png" /></figure><p>This is a phenomenal outcome. We have:</p><ul><li><strong>Reduced the model size by over 63%.</strong></li><li><strong>Cut the computational cost by 37.5%.</strong></li><li><strong>Actually <em>improved</em> the accuracy!</strong> This can happen because pruning acts as a powerful regularizer, helping the model generalize better.</li></ul><h3>Part 5: Pro-Tips and The Road Ahead</h3><p>You’re now equipped to start pruning your own models. Here are some final best practices:</p><ul><li><strong>Go Iterative:</strong> Instead of pruning 40% at once, try pruning 10% four times, with a short fine-tuning session after each step. This often yields better results.</li><li><strong>Combine with Quantization:</strong> Pruning is just one tool. For maximum efficiency, combine it with quantization (reducing the precision of the weights, e.g., from FP32 to INT8). A pruned and quantized model is the gold standard for edge deployment.</li><li><strong>Don’t Prune Blindly:</strong> Some layers are more sensitive than others. The first convolutional layer, which learns basic features like edges and colors, is often left unpruned.</li></ul><h3>Conclusion</h3><p>Model pruning is no longer an obscure academic technique; it’s an essential, practical tool for any machine learning engineer. It bridges the gap between massive, state-of-the-art models and the resource constraints of the real world.</p><p>We’ve journeyed from the core theory to a live PyTorch implementation, demonstrating that you can significantly shrink your models, make them faster, and even improve their performance. The next time you find yourself with a model that’s too big or too slow, remember the art of the bonsai: prune away the unnecessary, and reveal the efficient, powerful core within.</p><p>Now, go try it on your own models</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30149badf95d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph Convolutional Networks (GCNs), Demystified: from Theory to Pure-PyTorch]]></title>
            <link>https://mohamed-stifi.medium.com/graph-convolutional-networks-gcns-demystified-from-theory-to-pure-pytorch-3a323e79c937?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a323e79c937</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 22:01:29 GMT</pubDate>
            <atom:updated>2025-10-08T22:01:29.444Z</atom:updated>
            <content:encoded><![CDATA[<p>GCNs are the workhorse of modern graph learning. In this article you’ll get a sharp, <strong>implementation-first</strong> walkthrough: what a GCN really computes, how the “magic” normalization works, how to write it <strong>without PyTorch Geometric</strong>, plus training tips, pitfalls, and extensions you can mention like a pro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*dNyzndGCTCiEtt94" /></figure><h3>Why a convolution on graphs?</h3><p>In images, convolution aggregates a pixel’s neighbors with shared weights. On graphs, nodes have <strong>irregular neighborhoods</strong> — different sizes and shapes — so we need a way to “share weights” while respecting structure.</p><p>The elegant answer: use the graph Laplacian and build a convolution that <strong>smooths</strong> features across edges. Practically, that becomes a simple recipe you can implement in a few lines.</p><h3>From spectral intuition to the GCN update</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*TWP4DInbq7he62jDOgnj5w.png" /></figure><h3>1) Reproducibility seeds</h3><pre>import numpy as np<br>import random<br><br>seed_value = 42<br>np.random.seed(seed_value)<br>random.seed(seed_value)</pre><p><strong>What this does:</strong> Sets seeds to make your synthetic data and k-NN graph repeatable.</p><h3>2) Build a toy graph from data (no PyG required)</h3><p>We’ll turn the classic make_moons dataset into a graph using k-nearest neighbors (k-NN).</p><pre>from sklearn.datasets import make_moons<br>import networkx as nx<br>from sklearn.neighbors import kneighbors_graph<br><br># Generate nodes\<br>X, y = make_moons(n_samples=100, noise=0.1, random_state=42)<br><br># Build edges using k-nearest neighbors<br>A = kneighbors_graph(X, n_neighbors=5, mode=&#39;connectivity&#39;, include_self=False)<br><br># Convert adjacency matrix to graph<br>G = nx.from_scipy_sparse_array(A)<br><br>print(f&quot;Nodes: {G.number_of_nodes()}, Edges: {G.number_of_edges()}&quot;)</pre><p><strong>Output</strong></p><pre>Nodes: 100, Edges: 294</pre><p><strong>What this does:</strong></p><ul><li>X (shape 100×2) are 2-D points; y are binary labels (two half-moons).</li><li>kneighbors_graph connects each point to its 5 nearest neighbors; converting to a NetworkX Graph gives us G.</li></ul><h3>3) Take a quick look</h3><pre>import matplotlib.pyplot as plt<br><br># Visualize the graph<br>pos = nx.spring_layout(G)  # You can choose different layouts<br>nx.draw(G, pos, with_labels=True, node_color=&#39;skyblue&#39;, node_size=700, edge_color=&#39;k&#39;, linewidths=1, font_size=15)<br>plt.title(&quot;Graph Visualization&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*w-kAwg92rQVH0VwC1YUAmQ.png" /></figure><p>This layout shows clusters roughly aligned with the two moons (similar to the image you captured). Visual checks like this are a great sanity test: <strong>is the graph topology meaningful for our task?</strong></p><h3>4) Inspect the structure (adjacency &amp; degree)</h3><pre># Get the adjacency matrix<br>adj_matrix = nx.adjacency_matrix(G)<br># Convert adjacency matrix to numpy array<br>adj_numpy = adj_matrix.toarray()<br>print(&quot;Adjacency Matrix (NumPy):&quot;)<br>print(f&quot;The shape of the adjacency matrix is {adj_numpy.shape}&quot;)<br>print(f&quot;First 5 x 5 on the adjacency matrix is: \n {adj_numpy[:5, :5]}&quot;)</pre><p><strong>Output (truncated)</strong></p><pre>Adjacency Matrix (NumPy):<br>The shape of the adjacency matrix is (100, 100)<br>First 5 x 5 on the adjacency matrix is:<br> [[0. 0. 0. 0. 0.]<br>  ...<br>  [0. 0. 0. 1. 0.]]</pre><p>And degrees:</p><pre># Get the degree of each node<br>degree = G.degree()<br># Convert degree to numpy array<br>degree_numpy = np.array(list(dict(degree).values()))<br>print(&quot;Node Degrees (NumPy):&quot;)<br>display(degree_numpy)</pre><p><strong>Why this matters:</strong> GCN normalization uses degrees to scale contributions from hubs vs. leaves.</p><h3>5) GCN layer</h3><p>This is the heart of the model. You add self-loops, compute D~^(0.5) *A~ * D~^(0.5), transform features by a learned Linear, propagate with the normalized adjacency, and add bias.</p><p>The GCNLayer is a custom PyTorch module that implements a single layer of a Graph Convolutional Network (GCN).</p><p><strong>What it does:</strong> It performs graph convolution on input node features. The core operation is based on the formula:</p><p><em>H</em>(<em>l</em>+1)=<em>σ</em>(<em>D</em>~−1/2 <em>* A</em>~ <em>* D</em>~−1/2 <em>* H</em>(<em>l</em>) <em>* W</em>(<em>l</em>) + <em>b</em>(<em>l</em>) )</p><p>where:</p><ul><li><em>H</em>(<em>l</em>) is the input feature matrix for layer <em>l</em>.</li><li><em>A</em>~=<em>A</em>+<em>I</em> is the adjacency matrix with added self-loops.</li><li><em>D</em>~ is the diagonal degree matrix of <em>A</em>~.</li><li><em>W</em>(<em>l</em>) is the weight matrix for layer <em>l</em>.</li><li><em>b</em>(<em>l</em>) is the bias term for layer <em>l</em>.</li><li><em>σ</em> is an activation function (usually ReLU, applied outside the layer in the GCN model).</li></ul><p><strong>How it is used:</strong> The GCNLayer is typically used as a building block within a larger GCN model. You instantiate it by providing the input and output feature dimensions. In the forward pass, you pass the node features and the adjacency matrix to the layer.</p><p><strong>General Goal:</strong> The general goal of a GCN layer is to learn representations of nodes in a graph by aggregating information from their neighbors. By stacking multiple GCN layers, the model can capture information from wider neighborhoods, enabling it to learn complex patterns and relationships within the graph structure.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class GCNLayer(nn.Module):<br>    def __init__(self, in_features, out_features):<br>        super(GCNLayer, self).__init__()<br>        self.linear = nn.Linear(in_features, out_features, bias=False) # Weight matrix W<br>        self.bias = nn.Parameter(torch.Tensor(out_features)) # Bias term<br>        nn.init.xavier_uniform_(self.linear.weight)<br>        nn.init.zeros_(self.bias)<br><br>    def forward(self, x, adj_matrix):<br>        # x: Node features (N x D_in)<br>        # adj_matrix: Adjacency matrix (N x N)<br><br>        # 1. Add self-loops to the adjacency matrix and compute degree matrix<br>        adj_matrix_hat = adj_matrix + torch.eye(adj_matrix.size(0), device=adj_matrix.device)<br>        degree_matrix_hat = torch.diag_embed(torch.sum(adj_matrix_hat, dim=1)**(-0.5))<br><br>        # 2. Compute normalized adjacency matrix (D_hat^-0.5 * A_hat * D_hat^-0.5)<br>        normalized_adj = torch.matmul(torch.matmul(degree_matrix_hat, adj_matrix_hat), degree_matrix_hat)<br><br>        # 3. Linear transformation of node features<br>        transformed_features = self.linear(x)<br><br>        # 4. Graph convolution: (D_hat^-0.5 * A_hat * D_hat^-0.5) * X * W<br>        output = torch.matmul(normalized_adj, transformed_features)<br><br>        # 5. Add bias<br>        output = output + self.bias<br><br>        return output</pre><p><strong>What to notice</strong></p><ul><li>Self-loops ensure each node keeps a piece of itself.</li><li>diag_embed materializes the degree matrix; simple and clear for moderate graphs.</li><li>Xavier init is a good default for the linear weights.</li></ul><h3>6) A multi-layer GCN model (stack layers)</h3><p>The GCN is a custom PyTorch module that implements a full Graph Convolutional Network.</p><p><strong>What it does:</strong> It stacks multiple GCNLayer instances to perform multi-layer graph convolution on input node features. It takes an adjacency matrix and node features as input and outputs learned node representations.</p><p><strong>How it is used:</strong> You instantiate the GCN model by providing the input feature dimensions, hidden layer dimensions, output feature dimensions, and the number of layers. In the forward pass, you pass the adjacency matrix and the initial node features to the model.</p><p><strong>General Goal:</strong> The general goal of a GCN model is to learn powerful, expressive node representations by aggregating information from increasingly larger neighborhoods in the graph. These learned representations can then be used for various downstream graph tasks.</p><p><strong>Possible Use Cases in Graph Tasks:</strong></p><ul><li><strong>Node Classification:</strong> Predicting the category or label of each node in a graph (e.g., classifying users in a social network).</li><li><strong>Link Prediction:</strong> Predicting whether a link exists or is likely to exist between two nodes (e.g., recommending friends in a social network).</li><li><strong>Graph Classification:</strong> Classifying entire graphs based on their structure and node features (e.g., classifying molecules).</li><li><strong>Node Clustering:</strong> Grouping similar nodes together based on their learned representations.</li></ul><pre>class GCN(nn.Module):<br>    def __init__(self, in_features, hidden_features, out_features, num_layers):<br>        super(GCN, self).__init__()<br>        self.num_layers = num_layers<br>        self.layers = nn.ModuleList()<br><br>        # Input layer<br>        self.layers.append(GCNLayer(in_features, hidden_features))<br><br>        # Hidden layers<br>        for _ in range(num_layers - 2):<br>            self.layers.append(GCNLayer(hidden_features, hidden_features))<br><br>        # Output layer<br>        self.layers.append(GCNLayer(hidden_features, out_features))<br><br>    def forward(self, adj_matrix, features):<br>        x = features<br>        for i, layer in enumerate(self.layers):<br>            x = layer(x, adj_matrix)<br>            if i &lt; self.num_layers - 1:<br>                x = F.relu(x) # Apply ReLU activation after each layer except the last<br><br>        return x</pre><h3>7) Prepare tensors and a simple dataset wrapper</h3><pre>import torch<br>from torch.utils.data import Dataset<br><br># # Convert node features (X) and labels (y) to PyTorch tensors<br>features = torch.tensor(X, dtype=torch.float32)<br>labels = torch.tensor(y, dtype=torch.long)<br><br># Convert the adjacency matrix to a PyTorch tensor<br>adj_matrix_tensor = torch.tensor(nx.adjacency_matrix(G).todense(), dtype=torch.float32)<br><br>print(&quot;Features tensor shape:&quot;, features.shape)<br>print(&quot;Labels tensor shape:&quot;, labels.shape)<br>print(&quot;Adjacency matrix tensor shape:&quot;, adj_matrix_tensor.shape)</pre><p><strong>Output</strong></p><pre>Features tensor shape: torch.Size([100, 2])<br>Labels tensor shape: torch.Size([100])<br>Adjacency matrix tensor shape: torch.Size([100, 100])</pre><pre>class GraphDataset(Dataset):<br>    def __init__(self, features, labels, adj_matrix):<br>        self.features = features<br>        self.labels = labels<br>        self.adj_matrix = adj_matrix<br><br>    def __len__(self):<br>        return self.features.size(0)<br><br>    def __getitem__(self, idx):<br>        # In this simple graph dataset, we return the entire graph data<br>        # for each &quot;item&quot;, as GCN operates on the whole graph.<br>        # For more complex datasets (e.g., mini-batching nodes or subgraphs),<br>        # this method would be different.<br>        return self.features, self.labels, self.adj_matrix<br><br># Instantiate the custom dataset<br>graph_dataset = GraphDataset(features, labels, adj_matrix_tensor)<br><br>print(&quot;Graph Dataset created:&quot;, graph_dataset)<br>print(&quot;Number of nodes in dataset:&quot;, len(graph_dataset))</pre><h3>8) Model hyperparams and architecture printout</h3><pre># Set parameters for the GCN model<br>in_features = X.shape[1]  # Number of input features (dimensions of the data points)<br>hidden_features = 32     # Number of features in the hidden layers<br>out_features = 2         # Number of output features (e.g., for classification)<br>num_layers = 3           # Number of GCN layers<br><br># Instantiate the GCN model<br>model = GCN(in_features, hidden_features, out_features, num_layers)<br><br>print(&quot;GCN Model Architecture:&quot;)<br>print(model)</pre><p><strong>Output (truncated)</strong></p><pre>GCN Model Architecture:<br>GCN(<br>  (layers): ModuleList(<br>    (0): GCNLayer(<br>      (linear): Linear(in_features=2, out_features=32, bias=False)<br>    )<br>    (1): GCNLayer(<br>      (linear): Linear(in_features=32, out_features=32, bias=False)<br>    )<br>    (2): GCNLayer(<br>      (linear): Linear(in_features=32, out_features=2, bias=False)<br>    )<br>  )<br>)</pre><h3>9) Training &amp; evaluation loops</h3><pre>import torch.optim as optim<br><br>def train(model, dataset, criterion, optimizer, epochs=100):<br>    model.train()  # Set the model to training mode<br>    features, labels, adj_matrix = dataset[0] # Get the entire graph data<br><br>    for epoch in range(epochs):<br>        optimizer.zero_grad()  # Zero the gradients<br>        outputs = model(adj_matrix, features) # Forward pass<br><br>        if epoch == 0:<br>            print(&quot;Features shape:&quot;, features.shape)<br>            print(&quot;Inputs shape:&quot;, features.shape)<br>            print(&quot;Outputs shape:&quot;, outputs.shape)<br>            print(&quot;Labels shape:&quot;, labels.shape)<br>            print(f&quot;Output values: {outputs[0]}&quot;)<br>            print(f&quot;Label values: {labels}&quot;)<br>        # Calculate loss. For simplicity in this example, we calculate loss on all nodes.<br>        # In a real-world scenario, you might use a mask for training nodes.<br>        <br>        loss = criterion(outputs, labels)<br><br>        loss.backward()  # Backward pass<br>        optimizer.step()  # Update weights<br><br>        if (epoch + 1) % 10 == 0:<br>            print(f&#39;Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}&#39;)<br><br>def evaluate(model, dataset):<br>    model.eval()  # Set the model to evaluation mode<br>    with torch.no_grad(): # Disable gradient calculation<br>        features, labels, adj_matrix = dataset[0] # Get the entire graph data<br>        outputs = model(adj_matrix, features) # Forward pass<br><br>        # Get predictions<br>        _, predicted = torch.max(outputs.data, 1)<br><br>        # Calculate accuracy<br>        # For simplicity, calculating accuracy on all nodes<br>        total = labels.size(0)<br>        correct = (predicted == labels).sum().item()<br>        accuracy = 100 * correct / total<br><br>        print(f&#39;Accuracy: {accuracy:.2f}%&#39;)<br>        return accuracy</pre><pre># Initialize optimizer and loss function (already done in the previous cell, but showing here for clarity)<br>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.Adam(model.parameters(), lr=0.01)</pre><pre># Train the model<br>print(&quot;Starting training...&quot;)<br>train(model, graph_dataset, criterion, optimizer, epochs=100)</pre><pre>Starting training...<br>Features shape: torch.Size([100, 2])<br>Inputs shape: torch.Size([100, 2])<br>Outputs shape: torch.Size([100, 2])<br>Labels shape: torch.Size([100])<br>Output values: tensor([-5.5762,  4.4726], grad_fn=&lt;SelectBackward0&gt;)<br>Label values: tensor([...])<br>Epoch [10/100], Loss: 0.0015<br>...<br>Epoch [100/100], Loss: 0.0000</pre><pre># Evaluate the model<br>print(&quot;\nEvaluating the model...&quot;)<br>evaluate(model, graph_dataset)</pre><pre>Evaluating the model...<br>Accuracy: 100.00%</pre><h3>Closing</h3><p>GCNs aren’t mysterious: normalize AAA, aggregate, linear map, repeat. With the pure-PyTorch layer above, a small training loop, and the tips here, you can ship a strong baseline, explain <em>why</em> it works, and know what to try when it doesn’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a323e79c937" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Friendly Guide to Knowledge Distillation (with PyTorch code you can paste today)]]></title>
            <link>https://mohamed-stifi.medium.com/a-friendly-guide-to-knowledge-distillation-with-pytorch-code-you-can-paste-today-5a764762e7c7?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a764762e7c7</guid>
            <category><![CDATA[knowledge-distillation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[model-compression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 11:47:09 GMT</pubDate>
            <atom:updated>2025-10-07T11:47:09.135Z</atom:updated>
            <content:encoded><![CDATA[<p>How to turn a big, smart “teacher” model into a smaller “student” that runs fast — without losing much accuracy.</p><h3>TL;DR</h3><p>Knowledge distillation trains a compact <strong>student</strong> model to mimic a powerful <strong>teacher</strong> model. You combine two losses: a normal cross-entropy against the hard labels and a “soft” loss that nudges the student toward the teacher’s probability distribution (its <em>logits</em>). A temperature parameter T controls how soft those targets are, and a mixing weight α \alphaα balances the two losses. Do this right and you’ll ship lighter models that still perform impressively — perfect for edge devices and low-latency services.</p><h3>The intuition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ydIEelbhp-oDX-isgJR_A.png" /></figure><p>Traditional training (left side of your diagram) optimizes a model purely against the ground-truth labels using cross-entropy. That teaches the model <em>what</em> the right class is, but not <em>how</em> the teacher thinks about the alternatives.</p><p>Distillation (right side) feeds the same inputs to a <strong>frozen, pretrained teacher</strong> and to the <strong>student</strong>. Besides the hard loss on labels, we add a <strong>soft loss</strong> between the teacher’s and the student’s output distributions. Those “soft targets” carry rich information — e.g., that a “husky” is closer to “wolf” than “car” — which helps the student generalize with fewer parameters.</p><h3>The math (short &amp; sweet)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*Vr6PHJnYisJiS8Gs3w9kRw.png" /></figure><p>The T² factor compensates for gradients when softening the distributions. Don’t forget it — this is the #1 mistake in KD implementations.</p><h3>A clean PyTorch implementation</h3><p>Paste this into your training code. It works with any teacher/student architectures as long as they output logits of the same size.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class DistillationLoss(nn.Module):<br>    def __init__(self, temperature=4.0, alpha=0.5, hard_criterion=None):<br>        super().__init__()<br>        self.T = temperature<br>        self.alpha = alpha<br>        self.hard_criterion = hard_criterion or nn.CrossEntropyLoss()<br>        self.kl_div = nn.KLDivLoss(reduction=&#39;batchmean&#39;)<br><br>    def forward(self, student_logits, labels, teacher_logits):<br>        T = self.T<br>        # Student log-probs and teacher probs at temperature T<br>        log_p_s = F.log_softmax(student_logits / T, dim=1)<br>        p_t = F.softmax(teacher_logits / T, dim=1)<br><br>        loss_soft = self.kl_div(log_p_s, p_t) * (T * T)<br>        loss_hard = self.hard_criterion(student_logits, labels)<br>        loss = self.alpha * loss_hard + (1 - self.alpha) * loss_soft<br>        return loss, {&quot;hard&quot;: loss_hard.item(), &quot;soft&quot;: loss_soft.item()}<br><br>def train_kd(teacher, student, dataloader, optimizer, device=&quot;cuda&quot;,<br>             temperature=4.0, alpha=0.5, epochs=10, amp=True):<br>    teacher.eval()              # Freeze teacher<br>    for p in teacher.parameters():<br>        p.requires_grad_(False)<br><br>    kd_loss = DistillationLoss(temperature=temperature, alpha=alpha)<br>    scaler = torch.cuda.amp.GradScaler(enabled=amp)<br><br>    student.to(device)<br>    teacher.to(device)<br><br>    for epoch in range(epochs):<br>        student.train()<br>        running = {&quot;loss&quot;: 0.0, &quot;hard&quot;: 0.0, &quot;soft&quot;: 0.0, &quot;n&quot;: 0}<br><br>        for x, y in dataloader:<br>            x, y = x.to(device), y.to(device)<br><br>            with torch.no_grad():<br>                teacher_logits = teacher(x)<br><br>            optimizer.zero_grad(set_to_none=True)<br><br>            with torch.cuda.amp.autocast(enabled=amp):<br>                student_logits = student(x)<br>                loss, parts = kd_loss(student_logits, y, teacher_logits)<br><br>            scaler.scale(loss).backward()<br>            scaler.step(optimizer)<br>            scaler.update()<br><br>            b = x.size(0)<br>            running[&quot;loss&quot;] += loss.item() * b<br>            running[&quot;hard&quot;] += parts[&quot;hard&quot;] * b<br>            running[&quot;soft&quot;] += parts[&quot;soft&quot;] * b<br>            running[&quot;n&quot;] += b<br><br>        n = running[&quot;n&quot;]<br>        print(f&quot;Epoch {epoch+1:02d} | &quot;<br>              f&quot;loss {running[&#39;loss&#39;]/n:.4f} &quot;<br>              f&quot;(hard {running[&#39;hard&#39;]/n:.4f}, soft {running[&#39;soft&#39;]/n:.4f})&quot;)</pre><p>How to use it</p><pre># teacher = torchvision.models.resnet50(weights=&quot;IMAGENET1K_V2&quot;)<br># student = torchvision.models.mobilenet_v3_small(num_classes=1000)<br># dataloader = ...<br># optimizer = torch.optim.AdamW(student.parameters(), lr=3e-4, weight_decay=0.05)<br><br>train_kd(teacher, student, dataloader, optimizer,<br>         temperature=4.0, alpha=0.7, epochs=30)</pre><p>That’s it: you’re now doing response-based distillation.</p><h3>Picking T and α:</h3><ul><li><strong>Temperature T</strong>: 2–8 is a practical range.</li><li>Lower T: sharper distributions, behaves closer to hard labels.</li><li>Higher T: smoother, more relative-class information; too high can wash out signal.</li><li><strong>Mixing α</strong>: 0.5–0.9 commonly works.</li><li>Larger α = trust labels more (useful if teacher occasionally errs).</li><li>Smaller α = mimic teacher more (useful when teacher is very strong or labels are noisy).</li></ul><p>A simple schedule works well: start with a modest T (e.g., 4) and α=0.7, then grid-search a few combos on a held-out set.</p><h3>When distillation shines</h3><ul><li><strong>Latency/throughput constraints:</strong> mobile, browsers, serverless, or high-QPS APIs.</li><li><strong>Edge deployment:</strong> limited memory/compute but still need accuracy.</li><li><strong>Noisy labels or weak supervision:</strong> teacher’s soft targets provide richer signal than one-hot labels.</li><li><strong>Domain adaptation:</strong> teacher trained on lots of data; student adapts faster on smaller, on-device data.</li></ul><h3>Variants worth knowing</h3><ul><li><strong>Offline KD (above):</strong> teacher is fixed; student learns from it.</li><li><strong>Online/self-distillation:</strong> teacher and student are the same model at different EMA snapshots; strong for training stability.</li><li><strong>Feature-based KD:</strong> match intermediate feature maps (e.g., FitNets, attention transfer). Great when architectures differ a lot.</li><li><strong>Data-free KD:</strong> synthesize inputs to probe the teacher when original data can’t be shared (privacy/IP scenarios).</li></ul><h3>Practical tips &amp; common pitfalls</h3><ol><li><strong>Freeze the teacher</strong> (no grads, eval() mode). Keep dropout/BN in inference behavior.</li><li><strong>Use the right KL direction:</strong> KL(log p_s || p_t) with student in <strong>log-prob</strong> form, teacher in <strong>prob</strong> form.</li><li><strong>Remember the T²</strong> multiplier in the soft loss.</li><li><strong>Match class dimensions</strong> (student and teacher logits must have the same num_classes).</li><li><strong>Monitor both losses.</strong> If the soft loss is near zero early, your T may be too low; if hard loss doesn’t drop, increase α.</li><li><strong>Evaluate against baselines:</strong> compare student-from-scratch vs student-via-KD; report latency/size gains, not just accuracy.</li><li><strong>Mind domain shift:</strong> if teacher data ≠ student data, prioritize the hard loss a bit more (α↑).</li></ol><h3>A minimal evaluation checklist</h3><ul><li>Metrics: accuracy/F1 for classification, plus <strong>calibration</strong> (ECE) if probabilities matter.</li><li>Efficiency: <strong>params</strong>, <strong>FLOPs</strong>, <strong>latency</strong> (p50/p95) on target hardware, <strong>peak memory</strong>.</li><li>Ablations: (1) student from scratch, (2) KD with several T, (3) KD with several α, (4) with/without soft-only phase.</li></ul><h3>FAQs</h3><p><strong>Do I need the original training data?</strong><br> Yes for offline KD; teacher and student see the same inputs. If you can’t access the data, look into <em>data-free distillation</em>.</p><p><strong>Can architectures differ?</strong><br> Completely. The teacher might be a transformer; the student could be a tiny CNN or MobileNet — as long as output classes align.</p><p><strong>Why not just fine-tune the student on labels?</strong><br> Try it! KD often adds a few extra points of accuracy while keeping models small and fast.</p><p>Knowledge distillation is one of the highest-leverage tricks in modern ML: you keep most of the teacher’s brains while shipping a model your users’ devices can actually run. Start with the simple recipe above — <strong>hard CE + soft KL at temperature</strong> — then iterate on T, α, and (if needed) feature-matching for extra gains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a764762e7c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NumPy MLP From Scratch with OOP: Theory & Application (Regression, Binary Classification…]]></title>
            <link>https://mohamed-stifi.medium.com/numpy-mlp-from-scratch-with-oop-theory-application-regression-binary-classification-b852ffcadf32?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b852ffcadf32</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 21:48:56 GMT</pubDate>
            <atom:updated>2025-02-10T22:30:40.293Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>NumPy MLP From Scratch with OOP: Theory &amp; Application (Regression, Binary Classification, Multi-Classification)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*8EFBJ02Ov4fDbm4DEv_kMQ.png" /></figure><p>In the ever-evolving world of artificial intelligence and machine learning, <strong>Multi-Layer Perceptrons (MLPs)</strong> stand as one of the most fundamental and versatile architectures. As the building blocks of modern deep learning, MLPs have paved the way for groundbreaking advancements in fields ranging from computer vision to natural language processing. Whether you’re predicting house prices, classifying medical data, or recognizing handwritten digits, MLPs provide a robust framework for solving a wide array of problems.</p><p>This article is designed to take you on a comprehensive journey through the theory and application of MLPs. By combining <strong>mathematical foundations</strong> with <strong>hands-on implementation</strong>, we will demystify the inner workings of MLPs and empower you to build your own neural network from scratch using <strong>NumPy</strong> in an <strong>object-oriented programming (OOP)</strong> style. No black boxes here — just clear, step-by-step explanations and practical code that you can adapt and extend for your own projects.</p><h4>What You Will Learn:</h4><ul><li><strong>The Mathematical Foundations of MLPs</strong>: Understand the linear algebra and calculus behind neural networks, including forward propagation, backpropagation, and gradient-based optimization.</li><li><strong>Building an MLP from Scratch</strong>: Implement an MLP using NumPy, complete with customizable activation functions, loss functions, and optimization algorithms.</li><li><strong>Deep Learning Essentials</strong>: Gain a solid understanding of activation functions (ReLU, sigmoid, softmax), loss functions (MSE, BCE, CE), and optimization techniques (Adam, Momentum, AdaGrad).</li><li><strong>Real-World Applications</strong>: Apply your MLP to three distinct tasks:</li></ul><p><strong>Regression</strong>: Predict house prices using the California Housing Dataset.</p><ul><li><strong>Dataset:</strong> California Housing Dataset</li><li><strong>Objective:</strong> Predict house prices</li><li><strong>Results:</strong> Achieved an R² score of <strong>0.80</strong></li></ul><p><strong>Binary Classification</strong>: Classify tumors as malignant or benign using the Breast Cancer Dataset.</p><ul><li><strong>Dataset:</strong> Breast Cancer Dataset</li><li><strong>Objective:</strong> Classify tumors as malignant or benign</li><li><strong>Results:</strong> Achieved an accuracy of <strong>99%</strong></li></ul><p><strong>Multi-Class Classification</strong>: Recognize handwritten digits (0–9) using the Digits Dataset.</p><ul><li><strong>Dataset:</strong> Digits Dataset</li><li><strong>Objective:</strong> Classify handwritten digits (0–9)</li><li><strong>Results:</strong> Achieved an accuracy of <strong>97%</strong></li></ul><p>🚀 Let’s dive in!</p><h3>Table of Contents</h3><p><strong>1. What is an MLP?</strong></p><ul><li>Definition and Structure</li><li>Mathematical Formulation</li></ul><p><strong>2. Activation Functions</strong></p><ul><li>Role of Activation Functions</li><li>Common Activation Functions and Their Derivatives</li><li>Implementation of Function Class</li></ul><p><strong>3. Loss Functions</strong></p><ul><li>Mean Squared Error (MSE)</li><li>Binary Cross-Entropy (BCE)</li><li>Categorical Cross-Entropy (CE)</li><li>Implementation of Loss Class</li></ul><p><strong>4. Optimization Algorithms</strong></p><ul><li>Gradient Descent and Its Variants</li><li>Momentum, AdaGrad, and Adam</li><li>Implementation of Optimizer Class</li></ul><p><strong>5. Building the MLP from Scratch: </strong><strong>BaseModule Class</strong></p><ul><li>Class Initialization (__init__)</li><li>Initialization of Weights and Biases</li><li>Forward Propagation (forward)</li><li>Backpropagation (backward)</li><li>Parameter Updates (step)</li></ul><p><strong>6. Applications of MLPs</strong></p><p><strong><em>Regression Example</em></strong></p><ul><li>Load the dataset</li><li>Exploratory Data Analysis (EDA)</li><li>Data Preprocessing</li><li>Build and Train MLP Regressor Model</li><li>a. Build Model</li><li>b. Train Model</li><li>Model Evaluation</li></ul><p><strong><em>Binary Classification Example</em></strong></p><ul><li>Load the dataset</li><li>Exploratory Data Analysis (EDA)</li><li>Data Preprocessing</li><li>Build and Train MLP Binary Classification Model</li><li>a. Build Model</li><li>b. Train Model</li><li>Model Evaluation</li></ul><p><strong><em>Multi-Class Classification Example</em></strong></p><ul><li>Load the dataset</li><li>Exploratory Data Analysis (EDA)</li><li>Data Preprocessing</li><li>Build and Train MLP Multi-Class Classification Model</li><li>a. Build Model</li><li>b. Train Model</li><li>Model Evaluation</li></ul><p><strong>7. Conclusion</strong></p><h3>1. What is an MLP?</h3><h4>Definition and Structure</h4><p>A <strong>Multi-Layer Perceptron (MLP)</strong> is a class of feedforward artificial neural networks. It consists of:</p><ul><li>An <strong>input layer</strong> that receives the input data.</li><li>One or more <strong>hidden layers</strong> that transform the input data using weights, biases, and activation functions.</li><li>An <strong>output layer</strong> that produces the final prediction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*QcxDVM9vOsAjLv5J.png" /></figure><p>Each layer is fully connected to the next, meaning every neuron in one layer is connected to every neuron in the following layer. The connections between neurons are represented by <strong>weights</strong>, and each neuron has an associated <strong>bias</strong>.</p><h4>Mathematical Formulation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-ipi7J_SvUnnemq0uNh8Vw.png" /></figure><p>The output of each neuron in a layer is computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*syBHwZlKl9sHATmiVKzzfQ.png" /></figure><p>where:</p><ul><li><em>W</em> is the weight matrix.</li><li><em>x</em> is the input vector.</li><li><em>b</em> is the bias vector.</li></ul><p>The output of the neuron is then passed through an <strong>activation function</strong> <em>f</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*LDhFqauf1-JTIO1FB9s3sA.png" /></figure><p>For an MLP with <em>L</em> layers, the forward propagation can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*384Bkf5v36rl_b2dDmb68g.png" /></figure><p>where <em>l</em> denotes the layer index.</p><p>The upcoming section will clearly explain the forward propagation process.</p><h3>2. Activation Functions</h3><h4>Role of Activation Functions</h4><p>Activation functions introduce <strong>non-linearity</strong> into the network, enabling it to learn complex patterns. Without activation functions, an MLP would simply be a linear model, no matter how many layers it has.</p><h4>Common Activation Functions</h4><p><strong>ReLU (Rectified Linear Unit)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*jAOe2-Q_yReFYTy5-mr1BA.png" /></figure><ul><li><strong>Advantages</strong>: Computationally efficient, avoids vanishing gradients.</li></ul><p><strong>Sigmoid</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*ga4lauTMFS122b1wOvVxIg.png" /></figure><ul><li><strong>Advantages</strong>: Smooth gradient, outputs in the range [0, 1].</li></ul><p><strong>Tanh (Hyperbolic Tangent)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*8YnxXFIA9LYiSmfz9_7cbA.png" /></figure><ul><li><strong>Advantages</strong>: Outputs in the range [-1, 1], stronger gradient than sigmoid.</li></ul><p><strong>Softmax</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*oJua6OZRlKCHTwJg2otOvg.png" /></figure><ul><li><strong>Advantages</strong>: Used in the output layer for multi-class classification.</li></ul><h4>Implementation of Function Class</h4><pre>class Functions:<br>    # Activation functions and their derivatives<br>    @staticmethod<br>    def _relu(x):<br>        return np.maximum(0, x)<br><br>    @staticmethod<br>    def _relu_derivative(x):<br>        return (x &gt; 0).astype(float)<br><br>    @staticmethod<br>    def _sigmoid(x):<br>        return 1 / (1 + np.exp(-x))<br><br>    @staticmethod<br>    def _sigmoid_derivative(x):<br>        sx = Functions._sigmoid(x)<br>        return sx * (1 - sx)<br><br>    @staticmethod<br>    def _tanh(x):<br>        return np.tanh(x)<br><br>    @staticmethod<br>    def _tanh_derivative(x):<br>        return 1 - np.tanh(x)**2<br><br>    @staticmethod<br>    def _softmax(x):<br>        &quot;&quot;&quot;Softmax function for a vector of inputs.&quot;&quot;&quot;<br>        exp_x = np.exp(x - np.max(x))  # Subtract max to avoid overflow<br>        return exp_x / np.sum(exp_x, axis=-1, keepdims=True)<br><br>    @staticmethod<br>    def _softmax_derivative_one(x):<br>        &quot;&quot;&quot;Derivative of the softmax function.&quot;&quot;&quot;<br>        s = Functions._softmax(x)<br>        return np.diagflat(s) - np.outer(s, s)  # Jacobian of softmax<br><br>    def _softmax_derivative(x):<br>        return np.array([Functions._softmax_derivative_one(i) for i in x])<br><br>    # Dictionary that maps activation function names to their corresponding functions and derivatives<br>    name_to_function = {<br>        &#39;relu&#39;: (_relu, _relu_derivative),<br>        &#39;sigmoid&#39;: (_sigmoid, _sigmoid_derivative),<br>        &#39;tanh&#39;: (_tanh, _tanh_derivative),<br>        &#39;linear&#39;: (lambda x: x, lambda x: 1),<br>        &#39;softmax&#39;: (_softmax, _softmax_derivative)<br>    }</pre><ul><li>The name_to_function dictionary maps activation function names to their corresponding functions and derivatives, making it easy to switch between them.</li></ul><h3>3. Loss Functions</h3><p>Loss functions measure how well the model’s predictions match the true labels.</p><h4>Mean Squared Error (MSE)</h4><p>Used for <strong>regression</strong> tasks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*_g_7lfralJ3OPVgjDojZsg.png" /></figure><h4>Binary Cross-Entropy (BCE)</h4><p>Used for <strong>binary classification</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*5MN7wTjW5YUho5mR6tir6A.png" /></figure><h4>Categorical Cross-Entropy (CE)</h4><p>Used for <strong>multi-class classification</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*EMh55jQZyZ9U3kBO7Sx08Q.png" /></figure><h4>Implementation of Loss Class</h4><pre>class Loss:<br>    # Loss functions and their derivatives<br><br>    @staticmethod<br>    def MSELoss(true_y, pred_y):<br>        # Mean Squared Error (Regression)<br>        &#39;&#39;&#39;<br>            true_y = true label (y)<br>            pred_y = self.a[-1]<br>        &#39;&#39;&#39;<br>        m = true_y.shape[0]<br>        loss = np.mean((true_y - pred_y) ** 2)<br>        dA = -2 * (true_y - pred_y) / m<br>        return loss, dA<br>    @staticmethod<br>    def BCELoss(true_y, pred_y):<br>        # Binary Cross-Entropy Loss (binary classification)<br>        &#39;&#39;&#39;<br>            true_y = treu label (y)<br>            pred_y = self.a[-1]<br>        &#39;&#39;&#39;<br>        m = true_y.shape[0]<br>        a2 = pred_y<br>        y = true_y<br>        epsilon = 1e-15<br>        loss = -np.mean(y * np.log(a2 + epsilon) + (1 - y) * np.log(1 - a2 + epsilon))<br>        dA = -(y / (a2 + epsilon)) + ((1 - y) / (1 - a2 + epsilon))<br>        return loss, dA<br><br>    @staticmethod<br>    def CELoss(true_y, pred_y):<br>        # Categorical Cross-Entropy Loss (multiclass classification)<br>        &#39;&#39;&#39;<br>            true_y = treu label (y)<br>            pred_y = self.a[-1]<br>        &#39;&#39;&#39;<br>        y = true_y<br>        m = y.shape[0]<br>        a2 = pred_y<br><br>        # print(&quot;a2 shape: &quot;, a2.shape)<br>        # print(&quot;y shape: &quot;, y.shape)<br>        epsilon = 1e-15<br>        loss = -np.mean(np.sum(y * np.log(a2 + epsilon), axis=1))<br>        dA = -y / (a2 + epsilon)<br>        # print(&quot;loss shape: &quot;, loss.shape)<br>        # print(&quot;dA shape: &quot;, dA.shape)<br>        return loss, dA<br><br>    name_to_loss = {<br>        &#39;MSE&#39;: MSELoss,<br>        &#39;BCE&#39;: BCELoss,<br>        &#39;CE&#39;: CELoss<br>    }</pre><ul><li>The name_to_loss dictionary maps loss function names to their corresponding implementations.</li></ul><h3>4. Optimization Algorithms</h3><p>Optimizers update the weights and biases of the network to minimize the loss. We implement:</p><h4>Gradient Descent</h4><p>The simplest optimization algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Kd3a2-b6QtrQ-OA5zMqutQ.png" /></figure><p>where <em>η</em> is the learning rate.</p><h4>Momentum</h4><p>Accumulates past gradients to speed up convergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*A7TWWEOq1j2Wy9sXB8Lqyg.png" /></figure><h4>AdaGrad</h4><p>Adapts the learning rate based on past gradients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*ccXTQdLEvVdye0oluy9IQg.png" /></figure><h4>Adam</h4><p>Combines Momentum and AdaGrad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*tGvAmZ7BBSG542MhdvVzyg.png" /></figure><h4>Implementation of Optimizer Class</h4><pre>class Optimizer:<br>    @staticmethod<br>    def Momentum(w, dW, b, db, velocity_W, velocity_b, lr=0.001, momentum=0.9):<br>        for i in range(len(w)):<br>            velocity_W[i] = momentum * velocity_W[i] + lr * dW[i]<br>            w[i] = w[i] - velocity_W[i]<br><br>            velocity_b[i] = momentum * velocity_b[i] + lr * db[i]<br>            b[i] = b[i] - velocity_b[i]<br>        args = {&#39;velocity_W&#39;: velocity_W, &#39;velocity_b&#39;: velocity_b}<br>        return w, b, args<br><br>    @staticmethod<br>    def AdaGrad(w, dW, b, db, squared_dW, squared_db, lr=0.01, epsilon=1e-8):<br>        for i in range(len(w)):<br><br>            squared_dW[i] += dW[i] ** 2<br>            w[i] -= lr * dW[i] / (np.sqrt(squared_dW[i]) + epsilon)<br><br>            squared_db[i] += db[i] ** 2<br>            b[i] -= lr * db[i] / (np.sqrt(squared_db[i]) + epsilon)<br>        args = {&#39;squared_dW&#39;: squared_dW, &#39;squared_db&#39;: squared_db}<br>        return w, b, args<br><br>    @staticmethod<br>    def Adam(w, dW, b, db, m_W, m_b, v_W, v_b, t, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):<br>        t += 1<br>        for i in range(len(w)):<br>            m_W[i] = beta1 * m_W[i] + (1 - beta1) * dW[i]<br>            m_b[i] = beta1 * m_b[i] + (1 - beta1) * db[i]<br><br>            v_W[i] = beta2 * v_W[i] + (1 - beta2) * dW[i] ** 2<br>            v_b[i] = beta2 * v_b[i] + (1 - beta2) * db[i] ** 2<br><br>            m_W_hat = m_W[i] / (1 - beta1 ** (t))<br>            m_b_hat = m_b[i] / (1 - beta1 ** (t))<br><br>            v_W_hat = v_W[i] / (1 - beta2 ** (t))<br>            v_b_hat = v_b[i] / (1 - beta2 ** (t))<br><br>            w[i] -= lr * m_W_hat / (np.sqrt(v_W_hat) + epsilon)<br>            b[i] -= lr * m_b_hat / (np.sqrt(v_b_hat) + epsilon)<br><br>        args = {&#39;m_W&#39;: m_W, &#39;m_b&#39;: m_b, &#39;v_W&#39;: v_W, &#39;v_b&#39;: v_b, &#39;t&#39;: t}<br>        return w, b, args<br><br>    name_to_optimizer = {<br>        &#39;Momentum&#39;: Momentum,<br>        &#39;AdaGrad&#39;: AdaGrad,<br>        &#39;Adam&#39;: Adam<br>    }</pre><p>The name_to_optimizer dictionary maps optimizer names to their implementations.</p><h3>5. Building the MLP from Scratch: BaseModule Class</h3><p>The BaseModul class is the core of our Multi-Layer Perceptron (MLP) implementation. It encapsulates the architecture, initialization, forward pass, backward pass, and optimization of the neural network. Let’s break it down step by step.</p><pre>class BaseModul:<br>    def __init__(self, input_size, hidden_layers, output_size, activation_fn, loss, optimizer):<br>        pass<br><br>    def _initialize_parameters(self):<br>        pass<br><br>    def forward(self, X):<br>        pass<br><br>    def backward(self, X, y):<br>        pass<br><br>    def step(self):<br>        pass</pre><h4>Class Initialization (__init__)</h4><p>The __init__ method sets up the MLP architecture and initializes the necessary parameters.</p><pre>class BaseModul:<br>    def __init__(self, input_size, hidden_layers, output_size, activation_fn, loss, optimizer):<br>        self.input_size = input_size<br>        self.hidden_layers = hidden_layers<br>        self.output_size = output_size<br>        self.activation_fn = []<br>        for activation in activation_fn:<br>            self.activation_fn.append(Functions.name_to_function[activation])<br><br>        self.loss = Loss.name_to_loss[loss]<br>        self.optimizer = Optimizer.name_to_optimizer[optimizer]<br><br><br>        # Initialize weights and biases<br>        self.weights = []<br>        self.biases = []<br><br>        self.num_layers = len(hidden_layers) + 2<br>        self.layer_sizes = [input_size] + hidden_layers + [output_size]<br>        self._initialize_parameters()<br><br>        self.optimizer_args = {}<br>        if optimizer == &#39;Momentum&#39;:<br>            self.optimizer_args = {<br>                &#39;lr&#39;: 0.001,<br>                &#39;momentum&#39;: 0.9,<br>                &#39;velocity_W&#39;: [np.zeros_like(w) for w in self.weights],<br>                &#39;velocity_b&#39;: [np.zeros_like(b) for b in self.biases]<br>            }<br><br>        elif optimizer == &#39;AdaGrad&#39;:<br>            self.optimizer_args = {<br>                &#39;lr&#39;: 0.01,<br>                &#39;epsilon&#39;: 1e-8,<br>                &#39;squared_dW&#39;: [np.zeros_like(w) for w in self.weights],<br>                &#39;squared_db&#39;: [np.zeros_like(b) for b in self.biases]<br>            }<br>        elif optimizer == &#39;Adam&#39;:<br>            self.optimizer_args = {<br>                &#39;lr&#39;: 0.001,<br>                &#39;beta1&#39;: 0.9,<br>                &#39;beta2&#39;: 0.999,<br>                &#39;epsilon&#39;: 1e-8,<br>                &#39;m_W&#39;: [np.zeros_like(w) for w in self.weights],<br>                &#39;m_b&#39;: [np.zeros_like(b) for b in self.biases],<br>                &#39;v_W&#39;: [np.zeros_like(w) for w in self.weights],<br>                &#39;v_b&#39;: [np.zeros_like(b) for b in self.biases],<br>                &#39;t&#39;: 0<br>                }</pre><p><strong>Parameters:</strong></p><ul><li>input_size: Number of input features.</li><li>hidden_layers: List of integers specifying the number of neurons in each hidden layer.</li><li>output_size: Number of output neurons (e.g., 1 for regression/binary classification, C for multi-class classification).</li><li>activation_fn: List of activation functions for each layer.</li><li>loss: Loss function to use (e.g., MSE, BCE, CE).</li><li>optimizer: Optimization algorithm to use (e.g., Adam, Momentum, AdaGrad).</li></ul><p><strong>Key Steps:</strong></p><ul><li>Store the architecture details (input size, hidden layers, output size).</li><li>Map activation functions and their derivatives using the Functions.name_to_function dictionary.</li><li>Map the loss function and optimizer using the Loss.name_to_loss and Optimizer.name_to_optimizer dictionaries.</li><li>initial optimizer parameter self.optimizer_args.</li></ul><h4>Initialization of Weights and Biases</h4><p>The _initialize_parameters method initializes the weights and biases for all layers using <strong>He initialization</strong>.</p><pre>class BaseModul:<br>    &quot;&quot;&quot;...&quot;&quot;&quot;<br>    def _initialize_parameters(self):<br>        &quot;&quot;&quot;Initialize network weights and biases using He initialization&quot;&quot;&quot;<br>        self.weights = []<br>        self.biases = []<br>        for i in range(1, self.num_layers):<br>            # He initialization<br>            weight = np.random.randn(self.layer_sizes[i-1], self.layer_sizes[i]) * np.sqrt(2 / self.layer_sizes[i-1])<br>            bias = np.zeros((1, self.layer_sizes[i]))<br><br>            self.weights.append(weight)<br>            self.biases.append(bias)</pre><p><strong>He Initialization:</strong></p><ul><li>Weights are initialized with a normal distribution scaled by sqrt(2 / input_size). This helps avoid vanishing/exploding gradients in deep networks.</li><li>Biases are initialized to zeros.</li></ul><p><strong>Layer Sizes:</strong></p><ul><li>self.layer_sizes is a list containing the number of neurons in each layer, including the input and output layers.</li></ul><h4>Forward Propagation (forward)</h4><p><strong>Forward Propagation</strong> in a Multi-Layer Perceptron (MLP), Is the process where an input <strong>X</strong> passes through multiple layers of the network, producing an output <strong>ŷ</strong> (predicted value, a3 ). The output is then compared to the true label <strong>Y</strong> using a <strong>loss function</strong> to measure performance.</p><p>Forward propagation is performed <strong>layer by layer</strong>, applying weights, biases, and activation functions to the input, as showing on this illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gt8aX8R5YB2qtci-mwR-VQ.png" /></figure><p><strong>1. Input Layer</strong></p><p>The input <strong>X</strong> is assigned to <strong>a0</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*MSErDs6ff8dxx_8jcCR7_A.png" /></figure><p>This input will be passed through the network.</p><p><strong>2. Hidden Layer 1</strong></p><p>The first transformation happens using <strong>weights (w0)</strong> and <strong>biases (b0)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*ZEzwTVWMipFm6fSuRWyUTw.png" /></figure><p>Then, the activation function <strong>f0</strong> is applied to get <strong>a1</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*O4mfxpysbgvesm3SA7Vddw.png" /></figure><p>Here, <strong>f0</strong> is typically a non-linear function like <strong>ReLU, Sigmoid, or Tanh</strong>.</p><p><strong>3. Hidden Layer 2</strong></p><p>The process repeats for the second hidden layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*fd2NDBXQlmRRL2J5MRkeUA.png" /></figure><p><strong>4. Output Layer</strong></p><p>The final layer computes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*fRairXgUpsbBtsXv_jb8DA.png" /></figure><p>Here, <strong>f2</strong> could be:</p><ul><li><strong>Sigmoid</strong> for binary classification.</li><li><strong>Softmax</strong> for multi-class classification.</li><li><strong>Linear (Identity function)</strong> for regression.</li></ul><p><strong>5. Compute the Loss Function</strong></p><p>The final activation <strong>a3</strong> is the model’s output <strong>ŷ</strong>. This is compared to the true target <strong>Y</strong> using a loss function <strong>L</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*Yn9ZZAtTHj5Mbo2rJUIdlg.png" /></figure><p>Common loss functions:</p><ul><li><strong>Mean Squared Error (MSE)</strong> for regression.</li><li><strong>Binary Cross-Entropy (BCE)</strong> for binary classification.</li><li><strong>Categorical Cross-Entropy (CE)</strong> for multi-class classification.</li></ul><p>The forward method computes the output of the network given an input X.</p><pre>class BaseModul:<br>    def forward(self, X):<br>        self.a = []  # activations<br>        self.z = []  # pre-activations<br>        self.a.append(X)<br>        # print(&quot;a0 shape: &quot;, self.a[0].shape)<br><br>        for i in range(len(self.weights)):<br>            # print(f&quot;w{i} shape: &quot;, self.weights[i].shape)<br>            # print(f&quot;b{i} shape: &quot;, self.biases[i].shape)<br>            z = np.dot(self.a[i], self.weights[i]) + self.biases[i]<br>            self.z.append(z)<br>            # print(f&quot;z{i} shape: &quot;, z.shape)<br><br>            a = self.activation_fn[i][0](z)<br>            self.a.append(a)<br>            # print(f&quot;a{i+1} shape: &quot;, self.a[i+1].shape)<br>            # print(&quot;-&quot;*50)<br>        return self.a[-1]</pre><p><strong>Steps:</strong></p><ol><li>Append the input X to the activations list self.a.</li></ol><p>2. For each layer:</p><ul><li>Compute the pre-activation z as a linear transformation of the input:</li><li>Apply the activation function to z to get the activation a.</li></ul><p>3. Return the final output (activation of the last layer).</p><h4>Backpropagation (backward)</h4><p><strong>Backpropagation</strong> process in a Multi-Layer Perceptron (MLP), Is a key step in training the network, where we compute the gradients of the loss function with respect to weights and biases to update them accordingly.</p><p>Backpropagation is performed layer by layer in reverse order, starting from the output layer and propagating errors back through hidden layers, as showing on this illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6ejtGOO9S8QdWW-vUXlZg.png" /></figure><p><strong>1. Compute Gradient of the Loss Function (Starting at the Output Layer)</strong></p><p>At the output layer, we compute the derivative of the loss function <strong>L</strong> with respect to the activation <strong>a3</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*VgkWYcH11go6H15PLQS1Gw.png" /></figure><p>This represents how much the output contributes to the loss.</p><p><strong>2. Compute Gradients for the Output Layer</strong></p><ul><li>Compute the gradient of the weighted sum (<strong>Z2</strong>) using the derivative of the activation function:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*yNbff-MBlRHhh5l1sVynrQ.png" /></figure><ul><li>Compute the gradients for weights and biases:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*MuGgX-45rRcH0p25osKX5Q.png" /></figure><ul><li>Compute the gradient of the activation of the previous layer:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*cMi3I0CoISmmAOH8SMdOgg.png" /></figure><p><strong>3. Compute Gradients for Hidden Layers</strong></p><p>For each hidden layer, repeat the process:</p><ul><li>Compute dZ using the derivative of the activation function:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*0JGZRNgs1wRPXDBqbCRHEQ.png" /></figure><ul><li>Compute gradients for weights and biases:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*kbdMDwrobuwOC3MKv633pQ.png" /></figure><ul><li>Compute the gradient for the previous layer:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*L7IYnc6YGBsmIFZ0rW5GzA.png" /></figure><p>Continue this process backward until reaching the first hidden layer.</p><p><strong>4. Compute Gradients for the First Hidden Layer</strong></p><p>Following the same logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ooX3AbdafHKmZJKbeL2ntw.png" /></figure><p>At this point, we have computed all the gradients necessary to update the weights and biases.</p><p>The backward method computes the gradients of the loss with respect to the weights and biases using <strong>backpropagation</strong>.</p><pre>class BaseModul:<br>    def backward(self, X, y):<br>        m = X.shape[0]<br>        self.dW = []<br>        self.db = []<br>        self.dA = []<br><br>        # Compute the loss and gradient<br>        # dA = dloss(a[-1], y)/da[-1]<br>        loss, dA = self.loss(y, self.a[-1])<br>        # print(f&quot;dA{len(self.weights)} shape: {dA.shape}&quot;)<br><br>        self.dA.append(dA)<br><br>        # Backpropagate<br>        for i in range(len(self.weights) - 1, -1, -1):<br>            # dZ = dloss(a[-1], y)/dz[-1] = dloss(a[-1], y)/da[-1] * da[-1]/dz[-1] = dA * f&#39;(z[-1])<br>            if self.activation_fn[i][0].__name__ == &quot;_softmax&quot;:<br>                # Special handling for softmax activation<br>                # Compute the Jacobian of the softmax<br>                softmax_jacobian = self.activation_fn[i][1](self.z[i])  # Shape: (N, C, C)<br><br>                # Compute dZ using matrix multiplication<br>                dZ = np.einsum(&#39;ijk,ik-&gt;ij&#39;, softmax_jacobian, dA)  # Shape: (N, C)<br>            else:<br>                # For other activations (e.g., ReLU, sigmoid, tanh)<br>                dZ = dA * self.activation_fn[i][1](self.z[i])  # Shape: (N, C)<br><br>            # dZ = dA * self.activation_fn[i][1](self.z[i])<br>            # print(f&quot;dZ{i} shape: {dZ.shape}&quot;)<br><br>            # dW = dloss(a[-1], y)/dw[-1] = dloss(a[-1], y)/da[-1] * da[-1]/dz[-1] * dz[-1]/dw[-1] = dZ * a[-1]<br>            dW = np.dot(self.a[i].T, dZ) / m<br>            db = np.sum(dZ, axis=0, keepdims=True) / m<br><br>            # print(f&quot;dW{i} shape: {dW.shape}&quot;)<br>            # print(f&quot;db{i} shape: {db.shape}&quot;)<br><br>            dA = np.dot(dZ, self.weights[i].T)<br>            # print(f&quot;dA{i} shape: {dA.shape}&quot;)<br><br>            self.dW.append(dW)<br>            self.db.append(db)<br>            self.dA.append(dA)<br><br>            &#39;&#39;&#39;# Update parameters<br>            self.weights[i] -= lr * self.dW[-1]<br>            self.biases[i] -= lr * self.db[-1]&#39;&#39;&#39;<br><br>        # Reverse the order of the gradients<br>        self.dW.reverse()<br>        self.db.reverse()<br>        self.dA.reverse()<br><br>        return loss<br>  </pre><p><strong>Steps:</strong></p><ol><li>Compute the loss and gradient of the loss with respect to the output (dA).</li></ol><p>2. For each layer (starting from the output layer):</p><ul><li>Compute the gradient of the loss with respect to the pre-activation (dZ).</li><li>Compute the gradients of the loss with respect to the weights (dW) and biases (db).</li><li>Propagate the gradient to the previous layer (dA).</li></ul><p>3. Reverse the order of the gradients to match the layer order.</p><p>4. Return the loss.</p><h4>Parameter Updates (step)</h4><p>Once gradients are calculated, we update the weights and biases using an optimization algorithm like <strong>Gradient Descent</strong>, Adam, or Momentum.</p><p>The step method updates the weights and biases using the chosen optimizer.</p><pre>class BaseModul:    <br>    def step(self):<br>        self.weights, self.biases, self.optimizer_args = self.optimizer(self.weights, self.dW, self.biases, self.db, **self.optimizer_args)</pre><p><strong>Optimizer:</strong></p><ul><li>The optimizer (e.g., Adam, Momentum, AdaGrad) updates the weights and biases using the computed gradients (dW, db).</li></ul><h3>6. Applications of MLPs</h3><blockquote>Note: At the end of this article, I will share a GitHub notebook link for you to view the results and run it yourself.</blockquote><h4>Regression Example</h4><p>In this example, we use an <strong>MLP Regressor</strong> as an instance of <strong>MLP BaseModul</strong> to predict house prices based on the <strong>California Housing dataset</strong>. The process is divided into several steps:</p><p><strong>Load the dataset</strong></p><p>We use the <strong>California Housing dataset</strong> from sklearn.datasets. This dataset contains information on <strong>median house values</strong> in California districts, along with features such as:</p><ul><li>Median income (MedInc)</li><li>House age (HouseAge)</li><li>Average number of rooms (AveRooms), etc.</li></ul><pre>california_housing = fetch_california_housing()<br><br># Create a DataFrame<br>df = pd.DataFrame(california_housing.data, columns=california_housing.feature_names)<br><br># Add target column<br>df[&#39;Target&#39;] = california_housing.target</pre><p><strong>Exploratory Data Analysis (EDA)</strong></p><p>We analyze the dataset to understand its structure and relationships between variables.</p><pre># Basic statistics<br>df.describe()<br><br># Check for missing values<br>df.isnull().sum()<br><br># Correlation matrix<br>corr_matrix = df.corr()<br>plt.figure(figsize=(10, 8))<br>sns.heatmap(corr_matrix, annot=True, cmap=&#39;coolwarm&#39;, fmt=&#39;.2f&#39;, linewidths=0.5)<br>plt.title(&quot;Correlation Matrix&quot;)<br>plt.show()<br><br># Distribution of the target<br>plt.figure(figsize=(8, 6))<br>sns.histplot(df[&#39;Target&#39;], kde=True, color=&#39;skyblue&#39;)<br>plt.title(&quot;Distribution of Target (Median House Value)&quot;)<br>plt.show()<br><br># Pairplot of some features<br>sns.pairplot(df[[&#39;MedInc&#39;, &#39;HouseAge&#39;, &#39;AveRooms&#39;, &#39;AveOccup&#39;, &#39;Target&#39;]])<br>plt.show()</pre><p><strong>Data Preprocessing</strong></p><p>Before training the model, we prepare the data.</p><pre>X = df.drop(&#39;Target&#39;, axis=1)<br>y = df[&#39;Target&#39;]<br><br># Split the data into 70% training and 30% remaining (for validation and test)<br>X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)<br><br># Split the remaining data into 50% validation and 50% test (15% each)<br>X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)<br><br># convert y from pandas dataframe to numpy array<br>y_train = y_train.to_numpy()<br>y_val = y_val.to_numpy()<br>y_test = y_test.to_numpy()<br><br># Standardize the features<br>scaler = StandardScaler()<br><br>X_train_scaled = scaler.fit_transform(X_train)<br>X_val_scaled = scaler.transform(X_val)<br>X_test_scaled = scaler.transform(X_test)<br><br># Create a function to generate batches<br>class BatchIterator:<br>    def __init__(self, X, y, batch_size):<br>        self.X = X<br>        self.y = y<br>        self.batch_size = batch_size<br><br>    def __iter__(self):<br>        # Recreate the generator for each iteration<br>        data_size = self.X.shape[0]<br>        indices = np.random.permutation(data_size)  # Shuffle the data<br>        for i in range(0, data_size, self.batch_size):<br>            batch_indices = indices[i:i+self.batch_size]<br>            yield self.X[batch_indices], self.y[batch_indices]<br><br># Define batch size<br>batch_size = 100<br><br># Create batches for train, validation, and test sets<br>train_batches = BatchIterator(X_train_scaled, y_train, batch_size)<br>val_batches = BatchIterator(X_val_scaled, y_val, batch_size)<br>test_batches = BatchIterator(X_test_scaled, y_test, batch_size)</pre><p><strong>Build and Train MLP Regressor Model</strong></p><ul><li><strong>a. Build Model</strong></li></ul><p>We define an MLP model with:</p><ul><li><strong>Input layer</strong>: Same size as features</li><li><strong>Two hidden layers</strong>: 64 and 32 neurons</li><li><strong>Output layer</strong>: 1 neuron (for regression)</li><li><strong>Activation functions</strong>: ReLU in hidden layers, Linear in the output layer</li><li><strong>Loss function</strong>: Mean Squared Error (MSE)</li><li><strong>Optimizer</strong>: Adam</li></ul><pre>input_size = X_train_scaled.shape[1]<br>output_size = 1<br>hidden_layers = [64, 32]<br>activation_fn = [&#39;relu&#39;, &#39;relu&#39;, &#39;linear&#39;]<br>loss = &#39;MSE&#39;<br>optimizer = &#39;Adam&#39;<br><br># create regression model<br>mlpRegressor = BaseModul(input_size, hidden_layers, output_size, activation_fn, loss, optimizer)</pre><ul><li><strong>b. Train Model</strong></li></ul><p>We train the MLP for <strong>100 epochs</strong> using mini-batch gradient descent.</p><pre>mse_training_history = []<br>r2_training_history = []<br>mse_eval_history = []<br>r2_eval_history = []<br>number_of_epochs = 100<br><br>for epoch in range(number_of_epochs):<br>    mse_epoch = []<br>    r2_epoch = []<br>    for batch_X, batch_y in train_batches:<br>        y_pred = mlpRegressor.forward(batch_X)<br>        loss = mlpRegressor.backward(batch_X, batch_y.reshape(-1,1))<br>        mlpRegressor.step()<br>        mse_epoch.append(loss)<br>        r2_epoch.append(r2_score(batch_y, y_pred))<br>    r2_training_history.append(np.mean(r2_epoch))<br>    mse_training_history.append(np.mean(mse_epoch))<br><br><br>    mse_epoch = []<br>    r2_epoch = []<br>    for batch_X, batch_y in val_batches:<br>        y_pred = mlpRegressor.forward(batch_X)<br>        loss, _ = mlpRegressor.loss(batch_y, y_pred)<br>        mse_epoch.append(loss)<br>        r2_epoch.append(r2_score(batch_y, y_pred))<br><br>    r2_eval_history.append(np.mean(r2_epoch))<br>    mse_eval_history.append(np.mean(mse_epoch))<br></pre><p>Plot Training Progress</p><pre># Create a figure with 2 subplots (1 row, 2 columns)<br>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))<br><br># Plot MSE values (training and evaluation) in the first subplot<br>ax1.plot(mse_training_history, label=&#39;MSE Training&#39;, color=&#39;blue&#39;)<br>ax1.plot(mse_eval_history, label=&#39;MSE Evaluation&#39;, color=&#39;red&#39;)<br>ax1.set_title(&#39;MSE Loss Over Epochs&#39;)<br>ax1.set_xlabel(&#39;Epochs&#39;)<br>ax1.set_ylabel(&#39;MSE&#39;)<br>ax1.legend()<br>ax1.grid(True)<br><br># Plot R² values (training and evaluation) in the second subplot<br>ax2.plot(r2_training_history, label=&#39;R2 Training&#39;, color=&#39;green&#39;)<br>ax2.plot(r2_eval_history, label=&#39;R2 Evaluation&#39;, color=&#39;orange&#39;)<br>ax2.set_title(&#39;R² Over Epochs&#39;)<br>ax2.set_xlabel(&#39;Epochs&#39;)<br>ax2.set_ylabel(&#39;R²&#39;)<br>ax2.legend()<br>ax2.grid(True)<br><br># Adjust layout to prevent overlap<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><p><strong>Model Evaluation</strong></p><p>We test the trained model on unseen data.</p><pre>mse_epoch = []<br>r2_epoch = []<br>for batch_X, batch_y in test_batches:<br>    y_pred = mlpRegressor.forward(batch_X)<br>    loss, _ = mlpRegressor.loss(batch_y, y_pred)<br>    mse_epoch.append(loss)<br>    r2_epoch.append(r2_score(batch_y, y_pred))<br><br>r2, mse = np.mean(r2_epoch), np.mean(mse_epoch)<br>print(f&quot;Mean Squared Error (MSE): {mse:.4f}&quot;)<br>print(f&quot;R-squared: {r2:.4f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*rLZ6irU0AnbMWLOUDKi1Jg.png" /></figure><p>This evaluates how well the model predicts house prices.</p><p>This workflow demonstrates how to <strong>build, train, and evaluate an MLP regressor</strong> for real-world applications like housing price prediction.</p><h4>Binary Classification Example</h4><p>Multi-Layer Perceptrons (MLPs) are widely used in binary classification tasks, where the goal is to predict one of two possible classes based on input features. In this example, we use an MLP Binary Classification as instante of our MLP Base Modul to classify whether a tumor is malignant or benign using the <strong>Breast Cancer dataset</strong>.</p><p><strong>Load the dataset</strong></p><p>The <strong>Breast Cancer dataset</strong> is a well-known dataset in machine learning, containing information on tumor characteristics. Each instance is labeled as <strong>0 (benign)</strong> or <strong>1 (malignant)</strong>.</p><pre>cancer_data = load_breast_cancer()<br><br># Convert to DataFrame for easier manipulation<br>df = pd.DataFrame(cancer_data.data, columns=cancer_data.feature_names)<br>df[&#39;Target&#39;] = cancer_data.target</pre><p><strong>Exploratory Data Analysis (EDA)</strong></p><pre>&quot;&quot;&quot;#### a. Basic Information and Statistical Summary&quot;&quot;&quot;<br><br>print(f&quot;Shape of the dataset: {df.shape}&quot;)<br><br>df.head()<br><br>print(&quot;\nStatistical summary of the dataset:\n&quot;)<br>df.describe()<br><br>&quot;&quot;&quot;#### b. Check for missing values&quot;&quot;&quot;<br><br>print(&quot;\nMissing values in the dataset:\n&quot;)<br>df.isnull().sum()<br><br>&quot;&quot;&quot;#### c. Distribution of the target variable<br><br>&quot;&quot;&quot;<br><br>plt.figure(figsize=(8, 6))<br>sns.countplot(x=&#39;Target&#39;, data=df, palette=&#39;Set2&#39;)<br>plt.title(&#39;Distribution of Target (Malignant vs Benign)&#39;)<br>plt.xlabel(&#39;Target (0 = Benign, 1 = Malignant)&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.show()<br><br>&quot;&quot;&quot;#### d. Correlation heatmap&quot;&quot;&quot;<br><br>plt.figure(figsize=(12, 8))<br>corr_matrix = df.corr()<br>sns.heatmap(corr_matrix, annot=True, fmt=&#39;.2f&#39;, cmap=&#39;coolwarm&#39;, linewidths=0.5)<br>plt.title(&#39;Correlation Matrix&#39;)<br>plt.show()<br><br>&quot;&quot;&quot;#### e. Pairplot of selected features&quot;&quot;&quot;<br><br>sns.pairplot(df[[&#39;mean radius&#39;, &#39;mean texture&#39;, &#39;mean smoothness&#39;, &#39;mean compactness&#39;, &#39;Target&#39;]], hue=&#39;Target&#39;, palette=&#39;Set2&#39;)<br>plt.show()</pre><p><strong>Data Preprocessing</strong></p><pre>X = df.drop(&#39;Target&#39;, axis=1)<br>y = df[&#39;Target&#39;]<br><br># Split the data into 70% training and 30% remaining (for validation and test)<br>X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)<br><br># Split the remaining data into 50% validation and 50% test (15% each)<br>X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)<br><br># convert y from pandas dataframe to numpy array<br>y_train = y_train.to_numpy()<br>y_val = y_val.to_numpy()<br>y_test = y_test.to_numpy()<br><br># Standardize the features<br>scaler = StandardScaler()<br><br>X_train_scaled = scaler.fit_transform(X_train)<br>X_val_scaled = scaler.transform(X_val)<br>X_test_scaled = scaler.transform(X_test)<br><br># Define batch size<br>batch_size = 124<br><br># Create batches for train, validation, and test sets<br>train_batches = BatchIterator(X_train_scaled, y_train, batch_size)<br>val_batches = BatchIterator(X_val_scaled, y_val, batch_size)<br>test_batches = BatchIterator(X_test_scaled, y_test, batch_size)</pre><p><strong>Build and Train MLP Binary Classification Model</strong></p><p><strong>a. Build Model</strong></p><ul><li>Input size = number of features.</li><li>Output size = <strong>1 neuron</strong> (since it’s a binary classification).</li><li>Hidden layers: <strong>[64, 32, 16]</strong> neurons.</li><li>Activation functions:</li><li><strong>ReLU</strong> for hidden layers.</li><li><strong>Sigmoid</strong> for the output layer (to get probabilities).</li><li>Loss function: <strong>Binary Cross-Entropy (BCE)</strong>.</li><li>Optimizer: <strong>Adam</strong> (adaptive learning rate).</li></ul><p>A <strong>BaseModul</strong> class is used to initialize and manage the model.</p><pre>input_size = X_train_scaled.shape[1]<br>output_size = 1<br>hidden_layers = [64, 32, 16]<br>activation_fn = [&#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, &#39;sigmoid&#39;]<br>loss = &#39;BCE&#39;<br>optimizer = &#39;Adam&#39;<br><br>mlpBinaryClassifier = BaseModul(input_size, hidden_layers, output_size, activation_fn, loss, optimizer)</pre><p><strong>b. Train Model</strong></p><ul><li>The model is trained for <strong>100 epochs</strong> using batch processing.</li><li>For each batch:</li></ul><ol><li><strong>Forward pass</strong>: Predicts output.</li><li><strong>Backward pass</strong>: Computes gradients.</li><li><strong>Update weights</strong> using <strong>Adam optimizer</strong>.</li><li>Compute <strong>loss (BCE)</strong> and <strong>accuracy</strong>.</li></ol><pre>mse_training_history = []<br>acc_training_history = []<br>mse_eval_history = []<br>acc_eval_history = []<br>number_of_epochs = 100<br><br>for epoch in range(number_of_epochs):<br>    mse_epoch = []<br>    acc_epoch = []<br>    for batch_X, batch_y in train_batches:<br>        y_pred = mlpBinaryClassifier.forward(batch_X)<br>        loss = mlpBinaryClassifier.backward(batch_X, batch_y.reshape(-1,1))<br>        mlpBinaryClassifier.step()<br>        mse_epoch.append(loss)<br><br>        pred_class = (y_pred &gt;= 0.5).astype(int)<br>        acc_epoch.append(accuracy_score(batch_y, pred_class))<br>    acc_training_history.append(np.mean(acc_epoch))<br>    mse_training_history.append(np.mean(mse_epoch))<br><br><br>    mse_epoch = []<br>    acc_epoch = []<br>    for batch_X, batch_y in val_batches:<br>        y_pred = mlpBinaryClassifier.forward(batch_X)<br>        loss, _ = mlpBinaryClassifier.loss(batch_y, y_pred)<br>        mse_epoch.append(loss)<br>        pred_class = (y_pred &gt;= 0.5).astype(int)<br>        acc_epoch.append(accuracy_score(batch_y, pred_class))<br><br>    acc_eval_history.append(np.mean(acc_epoch))<br>    mse_eval_history.append(np.mean(mse_epoch))</pre><p>Plot Training Progress</p><pre># Create a figure with 2 subplots (1 row, 2 columns)<br>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))<br><br># Plot MSE values (training and evaluation) in the first subplot<br>ax1.plot(mse_training_history, label=&#39;BCE Training&#39;, color=&#39;blue&#39;)<br>ax1.plot(mse_eval_history, label=&#39;BCE Evaluation&#39;, color=&#39;red&#39;)<br>ax1.set_title(&#39;BCE Loss Over Epochs&#39;)<br>ax1.set_xlabel(&#39;Epochs&#39;)<br>ax1.set_ylabel(&#39;BCE&#39;)<br>ax1.legend()<br>ax1.grid(True)<br><br># Plot R² values (training and evaluation) in the second subplot<br>ax2.plot(acc_training_history, label=&#39;Accuracy Training&#39;, color=&#39;green&#39;)<br>ax2.plot(acc_eval_history, label=&#39;Accuracy Evaluation&#39;, color=&#39;orange&#39;)<br>ax2.set_title(&#39;accuracy Over Epochs&#39;)<br>ax2.set_xlabel(&#39;Epochs&#39;)<br>ax2.set_ylabel(&#39;accuracy&#39;)<br>ax2.legend()<br>ax2.grid(True)<br><br># Adjust layout to prevent overlap<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><p><strong>Model Evaluation</strong></p><p>After training, the model is tested on unseen test data for evaluting.</p><pre>y_pred = mlpBinaryClassifier.forward(X_test_scaled)<br>bce, _ = mlpBinaryClassifier.loss(y_test, y_pred)<br><br>pred_class = (y_pred &gt;= 0.5).astype(int)<br><br># Accuracy<br>accuracy = accuracy_score(y_test, pred_class)<br><br># Confusion Matrix<br>conf_matrix = confusion_matrix(y_test, pred_class)<br><br># Classification Report<br>class_report = classification_report(y_test, pred_class)<br><br>print(&quot;Binary cross entropy: &quot;, bce)<br><br>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)<br><br>print(&quot;\nConfusion Matrix:\n&quot;, conf_matrix)<br><br>print(&quot;\nClassification Report:\n&quot;, class_report)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*IMpqn-aYllEvKoa6yJIgzg.png" /></figure><p>This evaluates how well the model predicts.</p><p>This workflow demonstrates how to <strong>build, train, and evaluate </strong>an<strong> MLP Binary Classifier</strong> for real-world applications</p><h4>Multi-Class Classification Example</h4><p>This example demonstrates how our Multi-Layer Perceptron (MLP) can be used for <strong>multi-class classification</strong> using the <strong>Digits dataset</strong>. The dataset consists of <strong>handwritten digits (0–9)</strong> represented as 8x8 pixel images. The goal is to train an MLP model to classify these images correctly.</p><p><strong>Load the dataset</strong></p><pre>digits = load_digits()<br><br># Convert the data into a DataFrame for easier manipulation<br>df = pd.DataFrame(digits.data, columns=digits.feature_names)<br>df[&#39;Target&#39;] = digits.target</pre><p><strong>Exploratory Data Analysis (EDA)</strong></p><pre>&quot;&quot;&quot;#### a. Basic Information and Statistical Summary<br>&quot;&quot;&quot;<br><br>print(f&quot;Shape of the dataset: {df.shape}&quot;)<br><br>df.head()<br><br>print(&quot;\nStatistical summary of the dataset:\n&quot;)<br>df.describe()<br><br>&quot;&quot;&quot;#### b. Check for missing values<br><br>&quot;&quot;&quot;<br><br>print(&quot;\nMissing values in the dataset:\n&quot;)<br>df.isnull().sum()<br><br>&quot;&quot;&quot;#### c. Distribution of the target variable (digits 0-9)<br><br>&quot;&quot;&quot;<br><br>plt.figure(figsize=(8, 6))<br>sns.countplot(x=&#39;Target&#39;, data=df, palette=&#39;Set2&#39;)<br>plt.title(&#39;Distribution of Target Digits&#39;)<br>plt.xlabel(&#39;Target (Digit Labels)&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.show()<br><br>&quot;&quot;&quot;#### d. Visualizing some sample digits (8x8 pixel images)&quot;&quot;&quot;<br><br>fig, axes = plt.subplots(2, 5, figsize=(10, 5))<br>axes = axes.ravel()<br>for i in np.arange(10):<br>    axes[i].imshow(digits.images[i], cmap=&#39;gray&#39;)<br>    axes[i].set_title(f&#39;Digit: {digits.target[i]}&#39;)<br>    axes[i].axis(&#39;off&#39;)<br>plt.show()</pre><p><strong>Data Preprocessing</strong></p><pre><br>X = df.drop(&#39;Target&#39;, axis=1)<br>y = df[&#39;Target&#39;]<br><br>X.shape, y.shape<br><br>y_one_hot = pd.get_dummies(y).values.astype(int)<br>y_one_hot.shape<br><br># Split the data into 70% training and 30% remaining (for validation and test)<br>X_train, X_temp, y_train, y_temp = train_test_split(X, y_one_hot, test_size=0.3, random_state=42)<br><br># Split the remaining data into 50% validation and 50% test (15% each)<br>X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)<br><br># Standardize the features<br>scaler = StandardScaler()<br><br>X_train_scaled = scaler.fit_transform(X_train)<br>X_val_scaled = scaler.transform(X_val)<br>X_test_scaled = scaler.transform(X_test)<br><br># Define batch size<br>batch_size = 124<br><br># Create batches for train, validation, and test sets<br>train_batches = BatchIterator(X_train_scaled, y_train, batch_size)<br>val_batches = BatchIterator(X_val_scaled, y_val, batch_size)<br>test_batches = BatchIterator(X_test_scaled, y_test, batch_size)</pre><p><strong>Build and Train MLP Multi-Class Classification Model</strong></p><ul><li><strong>a. Build Model</strong></li></ul><p>We apply the BaseModul to a multi-class classification problem using the Digits dataset.</p><h4>Steps:</h4><p>Define the MLP architecture:</p><ul><li>Input size: Number of features.</li><li>Hidden layers: [124, 64, 32, 16].</li><li>Output size: Number of classes.</li><li>Activation functions: [&#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, &#39;softmax&#39;].</li><li>Loss: CE.</li><li>Optimizer: Adam.</li></ul><pre>input_size = X_train_scaled.shape[1]<br>output_size = y_one_hot.shape[1]<br>hidden_layers = [124, 64, 32, 16]<br>activation_fn = [&#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, &#39;relu&#39;, &#39;softmax&#39;]<br>loss = &#39;CE&#39;<br>optimizer = &#39;Adam&#39;<br><br>mlpMultiClassifier = BaseModul(input_size, hidden_layers, output_size, activation_fn, loss, optimizer)</pre><ul><li><strong>b. Train Model</strong></li></ul><p>Train the model and evaluate its performance using metrics like <strong>accuracy</strong> and <strong>classification report</strong></p><pre>loss_training_history = []<br>acc_training_history = []<br>loss_eval_history = []<br>acc_eval_history = []<br>number_of_epochs = 100<br><br>for epoch in range(number_of_epochs):<br>    loss_epoch = []<br>    acc_epoch = []<br>    for batch_X, batch_y in train_batches:<br>        y_pred = mlpMultiClassifier.forward(batch_X)<br>        loss = mlpMultiClassifier.backward(batch_X, batch_y)<br>        mlpMultiClassifier.step()<br>        loss_epoch.append(loss)<br><br>        pred_class = np.argmax(y_pred, axis=1)<br>        true_class = np.argmax(batch_y, axis=1)<br>        acc_epoch.append(accuracy_score(true_class, pred_class))<br>    acc_training_history.append(np.mean(acc_epoch))<br>    loss_training_history.append(np.mean(loss_epoch))<br><br><br>    loss_epoch = []<br>    acc_epoch = []<br>    for batch_X, batch_y in val_batches:<br>        y_pred = mlpMultiClassifier.forward(batch_X)<br>        loss, _ = mlpMultiClassifier.loss(batch_y, y_pred)<br>        loss_epoch.append(loss)<br>        pred_class = np.argmax(y_pred, axis=1)<br>        true_class = np.argmax(batch_y, axis=1)<br>        acc_epoch.append(accuracy_score(true_class, pred_class))<br><br>    acc_eval_history.append(np.mean(acc_epoch))<br>    loss_eval_history.append(np.mean(loss_epoch))</pre><p>Plot Training Progress</p><pre># Create a figure with 2 subplots (1 row, 2 columns)<br>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))<br><br># Plot MSE values (training and evaluation) in the first subplot<br>ax1.plot(loss_training_history, label=&#39;CE loss Training&#39;, color=&#39;blue&#39;)<br>ax1.plot(loss_eval_history, label=&#39;CE loss Evaluation&#39;, color=&#39;red&#39;)<br>ax1.set_title(&#39;CE Loss Over Epochs&#39;)<br>ax1.set_xlabel(&#39;Epochs&#39;)<br>ax1.set_ylabel(&#39;CE loss&#39;)<br>ax1.legend()<br>ax1.grid(True)<br><br># Plot R² values (training and evaluation) in the second subplot<br>ax2.plot(acc_training_history, label=&#39;Accuracy Training&#39;, color=&#39;green&#39;)<br>ax2.plot(acc_eval_history, label=&#39;Accuracy Evaluation&#39;, color=&#39;orange&#39;)<br>ax2.set_title(&#39;accuracy Over Epochs&#39;)<br>ax2.set_xlabel(&#39;Epochs&#39;)<br>ax2.set_ylabel(&#39;accuracy&#39;)<br>ax2.legend()<br>ax2.grid(True)<br><br># Adjust layout to prevent overlap<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><p><strong>Model Evaluation</strong></p><p>After training, the model is tested on unseen test data for evaluting.</p><pre>y_pred = mlpMultiClassifier.forward(X_test_scaled)<br>ce, _ = mlpMultiClassifier.loss(y_test, y_pred)<br><br>pred_class = np.argmax(y_pred, axis=1)<br>true_class = np.argmax(y_test, axis=1)<br><br># Accuracy<br>accuracy = accuracy_score(true_class, pred_class)<br><br># Confusion Matrix<br>conf_matrix = confusion_matrix(true_class, pred_class)<br><br># Classification Report<br>class_report = classification_report(true_class, pred_class)<br><br>print(&quot;Cross entropy: &quot;, ce)<br><br>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)<br><br>print(&quot;\nConfusion Matrix:\n&quot;, conf_matrix)<br><br>print(&quot;\nClassification Report:\n&quot;, class_report)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*kV6pm6qLL1gx_7rDZCyYjQ.png" /></figure><p>This MLP model successfully classifies handwritten digits with <strong>high accuracy</strong>.</p><p>This example demonstrates our <strong>MLP in multi-class classification</strong>, a crucial application in <strong>image recognition and digit classification tasks</strong>.</p><h3>7. Conclusion</h3><p>In this article, we explored the foundational concepts of Multi-Layer Perceptrons (MLPs), one of the most fundamental architectures in deep learning. By combining theoretical explanations with practical implementation, we demonstrated how to build an MLP from scratch using NumPy in an object-oriented programming (OOP) style. This approach not only provided a deep understanding of the mathematical principles behind MLPs but also offered hands-on experience in implementing and training neural networks.</p><h4>Key Takeaways:</h4><ol><li><strong>Mathematical Foundations</strong>: We delved into the mathematical principles of MLPs, including linear algebra and calculus, which are essential for understanding how neural networks operate. We covered the forward and backward propagation processes, activation functions, loss functions, and optimization algorithms.</li><li><strong>Implementation from Scratch</strong>: Using NumPy, we built a flexible and reusable MLP framework in an OOP style. This included defining activation functions (ReLU, sigmoid, softmax), loss functions (MSE, BCE, CE), and optimization algorithms (Adam, Momentum, AdaGrad). The modular design allows for easy extension and adaptation to various tasks.</li><li><strong>Real-World Applications</strong>: We applied our MLP implementation to three distinct tasks:</li></ol><ul><li><strong>Regression</strong>: Predicting house prices using the California Housing Dataset, achieving an R² score of 0.80.</li><li><strong>Binary Classification</strong>: Classifying tumors as malignant or benign using the Breast Cancer Dataset, achieving an accuracy of 99%.</li><li><strong>Multi-Class Classification</strong>: Classifying handwritten digits (0–9) using the Digits Dataset, achieving an accuracy of 97%.</li></ul><p><strong>Training and Evaluation</strong>: We walked through the entire process of training and evaluating MLPs, including data preprocessing, model training, and performance evaluation. We also visualized the training progress using metrics like loss and accuracy over epochs.</p><p><strong>Flexibility and Extensibility</strong>: The OOP approach allows for easy customization and extension of the MLP framework. By defining different activation functions, loss functions, and optimizers, the same base class can be adapted to a wide range of machine learning tasks.</p><h4>Final Thoughts:</h4><p>Building an MLP from scratch is an excellent way to gain a deep understanding of how neural networks work. While modern deep learning frameworks like TensorFlow and PyTorch offer high-level abstractions and optimizations, implementing an MLP from the ground up provides invaluable insights into the inner workings of these models. This knowledge is crucial for debugging, optimizing, and innovating in the field of deep learning.</p><p>By following this article, you should now have a solid foundation in MLPs and be equipped to tackle more complex neural network architectures. Whether you’re working on regression, binary classification, or multi-class classification tasks, the principles and techniques covered here will serve as a strong starting point for your deep learning journey.</p><p>🚀 <strong>Next Steps</strong>:</p><ul><li>Experiment with different architectures, activation functions, and optimizers to see how they affect model performance.</li><li>Explore more advanced topics like convolutional neural networks (CNNs) and recurrent neural networks (RNNs).</li><li>Apply the MLP framework to other datasets and real-world problems.</li></ul><blockquote>Authors: <strong>Mohamed STIFI</strong> &amp; <strong>Hafssa BOUNIA</strong></blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/mohamed-stifi/"><strong>Mohamed STIFI</strong></a> &amp; <a href="https://www.linkedin.com/in/hafssa-bounia-a14b7b297/"><strong>Hafssa BOUNIA</strong></a></blockquote><p>you will find the note book of this work <a href="https://colab.research.google.com/drive/1g0HJkZtWCnm2mTmc5KjUuKr7kSXpmRpK?usp=sharing">here</a>.</p><p>Thank you for following along, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b852ffcadf32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Decision Trees with the ID3 Algorithm (Theory) and Scikit-Learn]]></title>
            <link>https://mohamed-stifi.medium.com/understanding-decision-trees-with-the-id3-algorithm-theory-and-scikit-learn-857995bf242c?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/857995bf242c</guid>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[theory]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[entropy]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 13:58:33 GMT</pubDate>
            <atom:updated>2024-11-02T14:47:39.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*_CT30cyHjl0QrYuX4bjs0A.png" /></figure><p>Decision Trees are one of the most interpretable and widely used machine learning algorithms, especially popular for classification tasks. In this article, we’ll dive into the ID3 algorithm, which is foundational to Decision Trees, explore key concepts like entropy and information gain and give a basic implementation of this concept from scatch, and see how to implement decision trees in Python using scikit-learn.</p><h3>The Theory Behind Decision Trees</h3><h3>What is a Decision Tree?</h3><p>A Decision Tree is a flowchart-like structure where each internal node represents a decision based on an attribute, each branch represents the outcome of the decision, and each leaf node represents a final label or outcome. This tree structure is particularly useful for classification tasks because it mirrors human decision-making and can handle both categorical and numerical data.</p><h3>ID3 Algorithm: The Core of Decision Trees</h3><p>One of the first algorithms used to build Decision Trees is the <strong>ID3 (Iterative Dichotomiser 3)</strong> algorithm, which creates a tree by selecting attributes that provide the most “information gain” at each step. Here’s a breakdown of how it works, as shown in the diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*34SDVp0KfUL-lIXpa0eRKQ.png" /></figure><p>One of the first algorithms used to build Decision Trees is the <strong>ID3 (Iterative Dichotomiser 3)</strong> algorithm, which creates a tree by selecting attributes that provide the most “information gain” at each step. Here’s a breakdown of how it works, as shown in the diagram:</p><p><strong>If all examples have the same label</strong>:</p><ul><li>Return a single node tree with that label.</li></ul><p><strong>Otherwise</strong>:</p><ul><li>Create a <strong>root node</strong>.</li><li>Select the attribute that best classifies the data based on <strong>information gain</strong>.</li><li>For each possible value of this attribute:</li><li>Create a branch.</li><li>Recursively apply the ID3 algorithm to the subset of data where this attribute has that value.</li><li><strong>Stop</strong> if there are no remaining attributes or examples.</li></ul><h3>Key Concepts in ID3</h3><ul><li><strong>Entropy</strong>: Entropy measures the<em> disorder</em> or impurity in the dataset. For example, in a binary classification problem, a pure dataset with all examples belonging to the same class has zero entropy. In contrast, a mixed dataset has higher entropy (<strong>High entropy indicates high uncertainty, while low entropy indicates low uncertainty</strong>).</li><li><strong>Information Gain</strong>: Information gain measures the reduction in entropy achieved by splitting the data on an attribute. ID3 chooses the attribute with the highest information gain at each step to build the tree (<strong>An attribute with high information gain indicates that splitting the dataset by this attribute results in low entropy, making it the best classifier for the target</strong>).</li></ul><h3>Calculating Entropy and Information Gain</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*SMr-iuztrL1MX87Xox-7lQ.png" /></figure><h3>Implementing ID3 in Python</h3><p>To implement ID3 from scratch, here is a basic Python code example:</p><pre>import numpy as np<br><br>class DecisionTreeID3:<br>    def __init__(self):<br>        self.tree = None<br><br>    def fit(self, X, y, attributes=None):<br>        self.tree = self._id3(X, y, <br>                attributes if attributes is not None else list(X.columns))<br>        <br>    def _entropy(self, y):<br>        values, counts = np.unique(y, return_counts=True)<br>        probabilities = counts / counts.sum()<br>        return -np.sum(probabilities * np.log2(probabilities))<br>    <br>    def _information_gain(self, X, y, attribute):<br>        total_entropy = self._entropy(y)<br>        values, counts = np.unique(X[attribute], return_counts=True)<br>        <br>        weighted_entropy = sum(<br>                   (counts[i] / np.sum(counts)) * self._entropy(y[X[attribute] == values[i]]) <br>                      for i in range(len(values))<br>                    )<br>        return total_entropy - weighted_entropy<br><br>    def _id3(self, X, y, attributes):<br>        if len(np.unique(y)) == 1:<br>            return np.unique(y)[0]<br>        <br>        if len(attributes) == 0:<br>            return y.mode()[0]<br>        <br>        gains = [self._information_gain(X, y, attr) for attr in attributes]<br>        best_attr = attributes[np.argmax(gains)]<br>        <br>        tree = {best_attr: {}}<br>        attributes = [attr for attr in attributes if attr != best_attr]<br>        <br>        for value in np.unique(X[best_attr]):<br>            subset_X = X[X[best_attr] == value]<br>            subset_y = y[X[best_attr] == value]<br>            subtree = self._id3(subset_X, subset_y, attributes)<br>            tree[best_attr][value] = subtree<br>            <br>        return tree<br><br>    def predict(self, X):<br>        results = []<br>        for _, row in X.iterrows():<br>            results.append(self._predict(row, self.tree))<br>        return results<br>    <br>    def _predict(self, row, tree):<br>        if not isinstance(tree, dict):<br>            return tree<br>        attr = next(iter(tree))<br>        if row[attr] in tree[attr]:<br>            return self._predict(row, tree[attr][row[attr]])<br>        else:<br>            return None  # handle unseen attribute values</pre><h3>ID3 Usage Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*8gdwoU8PNsFJdUr4Le-YGg.png" /></figure><p>The table presents an overview of the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*smwclCsKzmulEKliyeOD0A.png" /></figure><p>The current entropy in the target column Play? is <strong>0.94</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*rIqfLPFmhGRjaIqEu-F0IQ.png" /></figure><p>The attribute <strong>Outlook</strong> provides a final information gain of 0.246.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*EqdVq4epgpTQONu9d7fIjw.png" /></figure><p>The attribute <strong>Humidity</strong> has an information gain of 0.1515, indicating that its expected entropy is greater than that of <strong>Outlook</strong>. This suggests that <strong>Humidity</strong> classifies the target (Play?) with high uncertainty, whereas <strong>Outlook</strong> classifies it with low uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*mpwxn1UDHV7von_xHmJCVQ.png" /></figure><p>The attribute with the highest information gain is <strong>Outlook</strong>, so we will split based on this attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*LPoGJ_XTTVXcI76aWD1-kg.png" /></figure><p>After choosing the best classifier, the next step is to create a node with the name of this chosen attribute in this case <strong>Outlook</strong>, for each value in values(Outlook) = {sunny, overcast, rain} on create an edge, and apply the ID3 algorithm in the subset of our dataset where the chooses attribute equal this value to get a subtree for this value.</p><p>As you show when the Outlook is overcast, the only value for the target Play? is yes. Therefore, we will stop and return yes as the predicted value.</p><p>The remaining values for Outlook are Sunny and Rain, and we will apply ID3 recursively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*NtXDwozU6yxVUvaRrpiKMg.png" /></figure><p>In the subset where <strong>Outlook</strong> is Sunny, the attribute <strong>Humidity</strong> has the highest information gain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*0jklhHwhVvbzDRAzPUe91A.png" /></figure><p>This is our final tree generated by applying the ID3 algorithm to our dataset.</p><h3>Implementing Decision Trees in Python with sklearn.tree</h3><p>Scikit-learn’s tree module provides easy-to-use implementations of decision trees for both classification and regression tasks. Here&#39;s a quick overview:</p><ul><li><strong>DecisionTreeClassifier</strong>: This is a decision tree for classification tasks.</li><li><strong>DecisionTreeRegressor</strong>: This tree is used for regression tasks.</li><li><strong>ExtraTreeClassifier</strong> and <strong>ExtraTreeRegressor</strong>: These are extremely randomized versions of decision trees, which can help reduce overfitting.</li></ul><h3>ID3 in scikit-learn’s Decision Trees</h3><p>While <strong>scikit-learn</strong> does not directly implement ID3, its DecisionTreeClassifier closely resembles the algorithm in spirit but with modifications. Here’s how it compares:</p><ul><li><strong>Gini Impurity vs. Entropy</strong>: By default, DecisionTreeClassifier uses the <strong>Gini impurity</strong> measure instead of entropy to decide on splits, which often perform similarly but is computationally faster. You can switch to entropy by setting criterion=&quot;entropy&quot;, which makes it closer to ID3.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cV0T0UzZxzZxciojW3OUZw.png" /></figure><ul><li><strong>Handling Continuous Variables</strong>: ID3 primarily handles categorical data, whereas DecisionTreeClassifier can handle both categorical and continuous data. It splits continuous variables at various thresholds to optimize classification.</li><li><strong>Pruning</strong>: ID3 doesn’t inherently have pruning mechanisms, but DecisionTreeClassifier provides parameters like max_depth, min_samples_split, and min_samples_leaf to control the depth of the tree, which acts as a form of pre-pruning to prevent overfitting.</li></ul><h3>Example Implementation with Scikit-Learn</h3><p>Let’s walk through a simple example of using DecisionTreeClassifier on a sample dataset. We&#39;ll also see how to visualize and interpret the tree.</p><pre>from sklearn.tree import DecisionTreeClassifier, plot_tree, export_text<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br># Load sample dataset<br>data = load_iris()<br>X = data.data<br>y = data.target<br># Split the data<br>X_train, X_test, y_train, y_test = train_test_split(X, y,<br>                                      test_size=0.3, random_state=42)<br># Initialize and train the model<br>clf = DecisionTreeClassifier(criterion=&#39;entropy&#39;)  # Using entropy to align with ID3<br>clf.fit(X_train, y_train)<br># Make predictions<br>y_pred = clf.predict(X_test)<br><br><br># Evaluate the model<br>accuracy = accuracy_score(y_test, y_pred)<br>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)<br><br><br><br># Visualize the decision tree<br>import matplotlib.pyplot as plt<br>plt.figure(figsize=(12, 8))<br>plot_tree(clf, feature_names=data.feature_names, <br>           class_names=data.target_names, filled=True)<br>plt.show()<br><br><br># Export tree rules as text<br>tree_rules = export_text(clf, feature_names=data.feature_names)<br>print(tree_rules)</pre><h3>Explanation of the Code</h3><ol><li><strong>Data Loading</strong>: We use the popular Iris dataset for classification.</li><li><strong>Model Training</strong>: We initialize DecisionTreeClassifier with criterion=&#39;entropy&#39; to match the ID3 algorithm. Other criteria like gini are also available in scikit-learn.</li><li><strong>Evaluation</strong>: We evaluate the model accuracy on the test set.</li><li><strong>Visualization</strong>: Using plot_tree, we can see the structure of the decision tree, and with export_text, we can print the rules in text format.</li></ol><p>Running this code will yield this output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aia9R3bi713LrT8GlMwjbg.png" /></figure><p>The output of the given code using Scikit-Learn shows:</p><ol><li><strong>Accuracy</strong>: The model achieves an accuracy of 100% on the test dataset, indicating that it perfectly classifies all instances.</li><li><strong>Decision Tree Visualization</strong>: The decision tree is visualized with nodes displaying:</li></ol><ul><li>The feature and threshold used for splitting the data.</li><li>The entropy of the node.</li><li>The number of samples reaching the node.</li><li>The distribution of class labels (values).</li><li>The predicted class for each node.</li></ul><p>This tree effectively classifies the Iris dataset using features like petal length and petal width, highlighting the decision paths for each class (setosa, versicolor, virginica).</p><h3>Advanced Use Cases</h3><ol><li><strong>Exporting in DOT Format</strong>: You can export the tree in DOT format using export_graphviz, which can then be visualized in Graphviz for more control over the appearance.</li><li><strong>Extreme Randomization with Extra Trees</strong>: If overfitting is a concern, ExtraTreeClassifier and ExtraTreeRegressor offer a way to introduce randomness, which can help generalize the model better.</li></ol><p>In conclusion, this article introduced the ID3 algorithm, explained key concepts like entropy and information gain with a basic implementation from scratch, and walked through a scikit-learn implementation of a Decision Tree Classifier. By understanding the theory behind decision trees and using tools like scikit-learn, you can leverage this powerful algorithm in various machine-learning tasks.</p><p>Don’t forget to follow me for more articles on ML/DL topics. I’m planning a series that delves into the theory behind each module in Scikit-Learn. This article is part of that series, focusing on the tree module.</p><p>Here the first article <a href="https://medium.com/@mhmf/exploring-scikit-learn-a-comprehensive-overview-of-its-sub-packages-and-modules-032bea32a65f"><strong>Exploring Scikit-Learn: A Comprehensive Overview of its Sub-Packages and Modules</strong></a></p><p>My Lnkedin <a href="https://www.linkedin.com/in/mohamed-stifi/"><strong>Mohamed Stifi</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=857995bf242c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing an Integrated Drone System: A Conceptual Overview with Use Case, Class, and Sequence…]]></title>
            <link>https://mohamed-stifi.medium.com/designing-an-integrated-drone-system-a-conceptual-overview-with-use-case-class-and-sequence-c966766e1a2d?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c966766e1a2d</guid>
            <category><![CDATA[uav-technology]]></category>
            <category><![CDATA[ai-data-processing]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[real-time-monitoring]]></category>
            <category><![CDATA[drones]]></category>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 01:05:50 GMT</pubDate>
            <atom:updated>2024-10-29T01:05:50.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing an Integrated Drone System: A Conceptual Overview with Use Case, Class, and Sequence Diagrams</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*p8lDVXndCWdDu_Ob.jpg" /></figure><p>With advancements in AI and UAV (Unmanned Aerial Vehicle) technology, drone-based systems are becoming pivotal for data collection, surveillance, and remote operations. This article delves into the architecture of a drone system that connects a <strong>Drone</strong>, <strong>Control Center</strong>, and <strong>Processing Center</strong>. We’ll explore the functionality of each component and how they work together to form a cohesive system. Through detailed use case, class, and sequence diagrams, this breakdown aims to give an end-to-end view of this system’s design for developers, engineers, and system architects.</p><h3>Use Case Diagram: High-Level System Interactions</h3><p>In the use case diagram, we outline the roles and interactions of the <strong>Drone</strong>, <strong>Control Center</strong>, and <strong>Processing Center</strong>. Each actor has a set of responsibilities that collectively form the backbone of the drone’s operational architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*KeworrDiz6o6SzzjCvHmOQ.png" /></figure><h4>1. Drone Platform</h4><p>The <strong>Drone</strong> is the core hardware element, responsible for executing flight maneuvers, capturing data, and transmitting it to other system components. Here’s a closer look at each functionality:</p><ul><li><strong>Capture Data</strong>: The drone is equipped with a camera and sensors to collect visual and telemetry data, capturing high-resolution images, videos, and geospatial data crucial for AI-based processing.</li><li><strong>Flight Operations</strong>: This includes all essential controls for take-off, landing, stabilization, and navigation. This can range from following a predefined flight path to real-time adjustments based on incoming commands.</li><li><strong>Data Transmission</strong>: The drone continuously streams raw data to both the <strong>Control Center</strong> (for monitoring) and the <strong>Processing Center</strong> (for AI-based analysis).</li></ul><h4>2. Control Center</h4><p>The <strong>Control Center</strong> acts as the command hub, where mission control personnel can set parameters, monitor operations, and take necessary actions.</p><ul><li><strong>Setting Mission Parameters</strong>: This step includes defining mission goals, flight routes, altitude, and other parameters critical for successful data capture.</li><li><strong>Monitoring</strong>: The Control Center receives a live data feed from the drone, providing telemetry, video, and images to monitor its status and surroundings.</li><li><strong>Controlling the Drone</strong>: Operators can adjust the drone’s path or capture settings in real-time, issuing commands for navigation, camera focus, or emergency responses.</li><li><strong>Receiving Feedback</strong>: Insights processed by the <strong>Processing Center</strong> are sent back to the Control Center, enhancing decision-making through real-time AI-driven data analysis.</li></ul><h4>3. Processing Center</h4><p>The <strong>Processing Center</strong> is responsible for transforming raw data into actionable insights using AI algorithms. Its responsibilities are:</p><ul><li><strong>Data Processing</strong>: The center applies AI models, such as image recognition and video analysis, to process captured data and derive insights.</li><li><strong>Storage</strong>: All incoming data is stored for future retrieval, analysis, or auditing.</li><li><strong>Feedback</strong>: Processed insights are sent back to the <strong>Control Center</strong> to assist in real-time decision-making or post-mission analysis.</li></ul><p>These components are linked by relationships that drive data exchange and control. For example, <strong>Mission Parameters</strong> include all necessary details that the drone’s flight controller will execute.</p><h3>Class Diagram: Structural Design and Attributes</h3><p>A class diagram provides an in-depth look at the structural components and functions within the <strong>DronePlatform</strong>, <strong>ControlCenter</strong>, and <strong>ProcessingCenter</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*UT8i9STOMnXqLbghMlqsUw.png" /></figure><h4>1. DronePlatform Class</h4><p>This class encapsulates all physical and functional elements related to the drone itself. Here’s a breakdown of its main components:</p><p><strong>Attributes</strong>:</p><ul><li><strong>QuadcopterFrame</strong>: The drone’s structural foundation, including the frame and mechanical components.</li><li><strong>FlightController</strong>: The onboard controller that manages the drone’s stability and trajectory.</li><li><strong>Camera</strong>: Enables visual data capture.</li><li><strong>CommunicationModule</strong>: Handles data transmission to the Control and Processing Centers.</li><li><strong>BatteryPowerManagement</strong>: Manages the drone’s power to maximize flight time.</li><li><strong>OnboardProcessor</strong>: Processes data locally for quick actions or pre-processing before transmission.</li></ul><p><strong>Functions</strong>:</p><ul><li><strong>FlightOperations()</strong>: Manages the various aspects of flight.</li><li><strong>DataCapture()</strong>: Handles the image or video capture functionality.</li><li><strong>Communication()</strong>: Transmits telemetry and data.</li><li><strong>PowerManagement()</strong>: Ensures efficient use of battery power.</li><li><strong>startFlight()</strong> and <strong>stopFlight()</strong>: Commands to start or end the flight.</li></ul><h4>2. ControlCenter Class</h4><p>The Control Center class manages the interface between human operators and the drone’s operational system.</p><p><strong>Attributes</strong>:</p><ul><li><strong>UserInterface</strong>: Provides operators with access to the system.</li><li><strong>DataDisplay</strong>: Displays live telemetry and camera feeds from the drone.</li><li><strong>CommandTransmissionSystem</strong>: Sends commands directly to the drone for flight and camera adjustments.</li><li><strong>FeedbackDisplay</strong>: Shows processed feedback from the Processing Center.</li></ul><p><strong>Functions</strong>:</p><ul><li><strong>SendCommand()</strong>: Issues commands to the drone.</li><li><strong>Monitoring()</strong>: Monitors telemetry and other real-time data.</li><li><strong>FeedbackIntegration()</strong>: Integrates insights from the Processing Center into ongoing operations.</li></ul><h4>3. ProcessingCenter Class</h4><p>The Processing Center class is primarily focused on AI-based data analysis.</p><p><strong>Attributes</strong>:</p><ul><li><strong>DataIngestionSystem</strong>: Collects raw data for processing.</li><li><strong>AIProcessingPipeline</strong>: Manages the workflow for data processing using AI models.</li><li><strong>DatabaseStorage</strong>: Stores both raw and processed data.</li><li><strong>FeedbackLoopSystem</strong>: Sends analyzed data back to the Control Center.</li></ul><p><strong>Functions</strong>:</p><ul><li><strong>DataIngestion()</strong>: Receives raw data from the drone.</li><li><strong>AIProcessing()</strong>: Applies algorithms to analyze images, videos, and telemetry data.</li><li><strong>DataStorageArchiving()</strong>: Manages storage for archival and retrieval.</li><li><strong>SendFeedback()</strong>: Sends results back to the Control Center.</li></ul><h3>Sequence Diagram: Workflow in Real-Time Operation</h3><p>The sequence diagram captures a real-time workflow from mission initialization to data feedback. It involves interactions among the <strong>Operator</strong>, <strong>Control Center</strong>, <strong>Drone</strong>, and <strong>Processing Center</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ptY7iRomD6QrpLomw5Wgxw.png" /></figure><h4>Workflow Steps</h4><ol><li><strong>Mission Setup</strong>: The <strong>Operator</strong> starts by setting mission parameters via the <strong>Control Center</strong>, specifying objectives, flight path, altitude, and other mission-critical details.</li><li><strong>Flight Commands</strong>: Once parameters are set, the <strong>Control Center</strong> sends flight commands to the <strong>Drone</strong> for execution.</li><li><strong>Data Transmission</strong>: As the drone flies, it captures telemetry data and images, which are sent to both the Control and Processing Centers.</li><li><strong>AI Processing</strong>: The <strong>Processing Center</strong> receives and processes the raw data using AI models, transforming it into actionable insights such as object detection, location tagging, or anomaly detection.</li><li><strong>Feedback Display</strong>: Processed data insights are sent to the <strong>Control Center</strong>, where they are displayed for real-time decision-making. The operator can use this feedback to adjust the mission if necessary.</li></ol><h3>Conclusion</h3><p>This architectural breakdown showcases how drone-based systems leverage AI and real-time data processing to enhance situational awareness and operational efficiency. With a structured approach combining use case, class, and sequence diagrams, engineers can understand and develop scalable and efficient UAV systems capable of complex data processing and analysis in real-time environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c966766e1a2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[استكشاف Scikit-Learn: نظرة شاملة على الحزم الفرعية والوحدات الخاصة بها]]></title>
            <link>https://mohamed-stifi.medium.com/%D8%A7%D8%B3%D8%AA%D9%83%D8%B4%D8%A7%D9%81-scikit-learn-%D9%86%D8%B8%D8%B1%D8%A9-%D8%B4%D8%A7%D9%85%D9%84%D8%A9-%D8%B9%D9%84%D9%89-%D8%A7%D9%84%D8%AD%D8%B2%D9%85-%D8%A7%D9%84%D9%81%D8%B1%D8%B9%D9%8A%D8%A9-%D9%88%D8%A7%D9%84%D9%88%D8%AD%D8%AF%D8%A7%D8%AA-%D8%A7%D9%84%D8%AE%D8%A7%D8%B5%D8%A9-%D8%A8%D9%87%D8%A7-4d604338d179?source=rss-ebf899c0a71d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d604338d179</guid>
            <dc:creator><![CDATA[Mohamed Stifi]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 00:36:01 GMT</pubDate>
            <atom:updated>2024-10-22T00:36:01.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*VhsFRd-zxrK-zB-5" /><figcaption>Scikit-Learn Library: Overview of Sub-Packages and Modules</figcaption></figure><p>أصبحت تعلم الآلة جزءاً أساسياً من تطوير الذكاء الاصطناعي، واختيار الأدوات المناسبة قد يحدد نجاح أو فشل المشروع. بين العديد من الأدوات المتاحة في بيئة بايثون، تبرز مكتبة سكيت-ليرن بفضل بساطتها، وتعدد استخداماتها، وقدرتها على التوسع. سواء كنت تعمل على التصنيف أو الانحدار أو التجميع أو اختيار النموذج، توفر سكيت-ليرن مجموعة من الأدوات المصممة لتبسيط هذه العمليات.</p><p>في هذه المقالة، سنستعرض الحزم الفرعية والوحدات الأساسية في مكتبة سكيت-ليرن، موضحين أهميتها في أبحاث الذكاء الاصطناعي وتعلم الآلة.</p><h3>1. sklearn</h3><p>في قلب مكتبة سكيت-ليرن تقع وحدة sklearn، وهي الحزمة الأساسية التي تقدم نقطة دخول منظمة إلى الخوارزميات والأدوات المتعددة التي توفرها سكيت-ليرن. بفضل واجهتها سهلة الاستخدام، تتيح الوصول بسلاسة إلى مجموعة من الأدوات لمعالجة البيانات، وبناء النماذج، وتقييم الأداء، وتنفيذ مهام الحوسبة العلمية المختلفة.</p><h3>2. sklearn.base</h3><p>توفر وحدة sklearn.base فئات أساسية تشكل اللبنات الأولى لمقدري سكيت-ليرن (مثل BaseEstimator وClassifierMixin). هذه الفئات تقدم البنية الضرورية للمطورين لإنشاء خوارزميات جديدة أو توسيع الخوارزميات القائمة. إنها تضع الأساس لإنشاء خطوط نقل بيانات متسقة وقابلة لإعادة الاستخدام داخل النماذج المخصصة.</p><h3>3. sklearn.datasets</h3><p>البيانات هي العمود الفقري لأي مشروع تعلم آلي. توفر وحدة sklearn.datasets وصولًا سهلاً إلى مجموعات بيانات صغيرة مثل Iris وBoston Housing وDigits، بالإضافة إلى أدوات لجلب مجموعات بيانات أكبر من الواقع (مثل 20 Newsgroups وOlivetti faces). كما تقدم هذه الوحدة أدوات لتوليد مجموعات بيانات اصطناعية للتجارب.</p><h3>4. sklearn.feature_extraction</h3><p>تتعامل وحدة sklearn.feature_extraction مع استخراج الميزات من البيانات الخام مثل النصوص أو الصور. تتيح أدوات مثل TfidfVectorizer وCountVectorizer تحويل البيانات النصية إلى تمثيلات رقمية، وهو أمر حاسم في مهام معالجة اللغة الطبيعية.</p><h3>5. sklearn.feature_selection</h3><p>اختيار الميزات الصحيحة لا يقل أهمية عن اختيار النموذج الصحيح. تقدم وحدة sklearn.feature_selection أدوات مثل SelectKBest وRFE (التخلص المتكرر من الميزات)، مما يساعد على تقليل الإفراط في التعميم عن طريق اختيار الميزات الأكثر صلة للنموذج.</p><h3>6. sklearn.manifold</h3><p>يساعد تعلم الطيات في فهم البنية الأساسية للبيانات في الفضاءات ذات الأبعاد العالية. تتضمن وحدة sklearn.manifold تقنيات مثل t-SNE وIsomap، التي تستخدم على نطاق واسع في التصور وكشف البنية الخفية في مجموعات البيانات المعقدة.</p><h3>7. sklearn.impute</h3><p>التعامل مع البيانات المفقودة هو جانب حيوي في خطوط تعلم الآلة. توفر وحدة sklearn.impute تقنيات لتعويض البيانات المفقودة مثل SimpleImputer وKNNImputer، مما يضمن تدفق البيانات بسلاسة إلى النماذج دون فقدان المعلومات الحيوية.</p><h3>8. sklearn.preprocessing</h3><p>تعتبر معالجة البيانات خطوة أساسية في أي مشروع تعلم آلي، وتوفر وحدة sklearn.preprocessing أدوات للتعامل مع التدرج والتطبيع وترميز المتغيرات الفئوية وتوليد الميزات متعددة الحدود. تسهل فئات مثل StandardScaler وMinMaxScaler وOneHotEncoder وPolynomialFeatures تحويل البيانات الخام إلى تنسيق مناسب لنماذج تعلم الآلة.</p><h3>9. sklearn.model_selection</h3><p>تقدم وحدة sklearn.model_selection أدوات مثل train_test_split وcross-validation وGridSearchCV لضبط المعاملات الفائقة. هذه الوحدة لا غنى عنها لضمان تعميم النموذج بشكل جيد وضبطه لتحقيق الأداء الأمثل.</p><h3>10. sklearn.linear_model</h3><p>يعتبر الانحدار الخطي حجر الزاوية في العديد من مهام تعلم الآلة. توفر وحدة sklearn.linear_model مجموعة من الخوارزميات الخطية، من الانحدار الخطي البسيط إلى تقنيات أكثر تعقيدًا مثل Ridge وLasso وElasticNet والانحدار اللوجستي.</p><h3>11. sklearn.ensemble</h3><p>يعتبر التعلم بالجمع تقنية أساسية في تعلم الآلة الحديثة، حيث يتم دمج عدة نماذج لتعزيز الأداء العام. توفر وحدة sklearn.ensemble طرقًا قوية مثل الغابات العشوائية (RandomForest)، التعزيز التدريجي (Gradient Boosting) والمصوتين المجمعين (Voting Classifiers). تساعد هذه الخوارزميات في تحسين التنبؤات من خلال الجمع بين نتائج عدة نماذج، مما يؤدي إلى نتائج قوية ودقيقة.</p><h3>12. sklearn.cluster</h3><p>تعتبر التجميع عملية تصنيف العناصر المتشابهة معًا، وهي متاحة في وحدة sklearn.cluster. تتوفر خوارزميات مثل K-Means، وAgglomerative Clustering، وDBSCAN، التي تساعد في تقسيم البيانات إلى مجموعات مفهومة. هذه الخوارزميات لا غنى عنها في المهام مثل تقسيم السوق أو تقسيم الصور.</p><h3>13. sklearn.naive_bayes</h3><p>يعد مصنف بايز الساذج من المصنفات الاحتمالية الفعالة والبسيطة، ويعتمد على تطبيق مبرهنة بايز مع افتراضات قوية بالاستقلالية بين الميزات. توفر وحدة sklearn.naive_bayes تطبيقات مختلفة مثل GaussianNB وMultinomialNB وBernoulliNB. هذه المصنفات مفيدة بشكل خاص في تصنيف النصوص، واكتشاف الرسائل المزعجة، وتحليل المشاعر.</p><h3>14. sklearn.neighbors</h3><p>توفر وحدة sklearn.neighbors خوارزميات تعتمد على إيجاد أقرب النقاط في الفضاء الميزي، مثل طريقة الجيران الأقرب (K-Nearest Neighbors، KNN) في مهام التصنيف والانحدار. هذه الخوارزميات غير المعلمية مفيدة في مهام مثل اكتشاف الشذوذ، أنظمة التوصيات، والتعرف على الأنماط.</p><h3>15. sklearn.neural_network</h3><p>على الرغم من أن الشبكات العصبية ترتبط أكثر بمكتبات التعلم العميق مثل TensorFlow وPyTorch، إلا أن سكيت-ليرن توفر وحدتها الخاصة بالشبكات العصبية. تتضمن وحدة sklearn.neural_network صنفين هما MLPClassifier وMLPRegressor، وهي نماذج perceptron متعددة الطبقات التي يمكن استخدامها في مهام التعلم الخاضع للإشراف. تعد هذه النماذج مفيدة بشكل خاص في مجموعات البيانات الأصغر حيث قد يكون التعلم العميق مبالغًا فيه، لكن الشبكات العصبية لا تزال فعالة.</p><h3>16. sklearn.svm</h3><p>تعتبر آلات المتجهات الداعمة (Support Vector Machines، SVM) نماذج قوية للتصنيف والانحدار وحتى اكتشاف الشذوذ. توفر وحدة sklearn.svm تطبيقات مختلفة، مثل SVC للتصنيف، وSVR للانحدار، وOneClassSVM لاكتشاف الشذوذ. تعتبر SVM فعالة بشكل خاص في الفضاءات ذات الأبعاد العالية، مما يجعلها مناسبة لتصنيف النصوص والمعلومات البيولوجية.</p><h3>17. sklearn.tree</h3><p>توفر وحدة sklearn.tree أدوات لبناء أشجار القرار، وهي نماذج تعتمد على تقسيم البيانات بشكل متكرر لاتخاذ التنبؤات. تحتوي الوحدة على DecisionTreeClassifier للتصنيف وDecisionTreeRegressor للانحدار. كما تقدم أداة export_graphviz، التي تتيح تصور أشجار القرار، مما يجعلها مفيدة في فهم القرارات التي يتخذها النموذج.</p><h3>18. sklearn.pipeline</h3><p>تعتبر خطوط النقل (pipelines) جزءًا أساسيًا من بناء سير العمل في تعلم الآلة. تقدم وحدة sklearn.pipeline فئة Pipeline، التي تسهل بناء سلاسل من خطوات التحويل والنمذجة، مما يضمن تطبيق كل خطوة من الخطوات بالتسلسل. هذا يسهل دمج استخلاص الميزات، المعالجة المسبقة، وتدريب النموذج في هيكل متماسك، وهو أمر ضروري لضمان إعادة قابلية الاستخدام ونظافة الشيفرة.</p><h3>19. sklearn.metrics</h3><p>يعد تقييم أداء النموذج خطوة حاسمة في أي سير عمل تعلم آلي. تقدم وحدة sklearn.metrics مجموعة شاملة من المقاييس لتصنيف، والانحدار، والتجميع، ومهام الترتيب. سواء كنت تحتاج إلى دقة (accuracy)، أو دقة (precision)، أو استرجاع (recall)، أو معدل AUC، فإن هذه المقاييس تساعد في قياس أداء النموذج واتخاذ القرارات.</p><h3>20. sklearn.calibration</h3><p>تعتبر معايرة النموذج أمرًا بالغ الأهمية عند تفسير التنبؤات الاحتمالية. توفر وحدة sklearn.calibration أدوات مثل CalibratedClassifierCV لضبط مخرجات المصنفات لتقديم تقديرات أفضل للاحتمالات. هذا مفيد بشكل خاص في مجالات مثل التشخيص الطبي أو تقييم المخاطر، حيث تكون الاحتمالات المُعايرة ضرورية لاتخاذ القرارات.</p><h3>21. sklearn.compose</h3><p>تحتاج سير عمل تعلم الآلة غالبًا إلى تحولات معقدة للبيانات. تساعد وحدة sklearn.compose على دمج الميزات من تحولات متعددة في سلسلة واحدة متماسكة. مثال على ذلك هو ColumnTransformer وTransformedTargetRegressor، اللذان يسمحان بتطبيق تحولات مختلفة على أعمدة البيانات، مما يضيف مرونة لكيفية إعداد ومعالجة بياناتك.</p><h3>22. sklearn.covariance</h3><p>عندما يتعلق الأمر بنمذجة البيانات المتعددة المتغيرات، فإن فهم التباين المشترك بين الميزات أمر أساسي. تتيح وحدة sklearn.covariance تقديرًا قويًا لمصفوفات التباين المشترك، وتوفر أدوات مثل EllipticEnvelope لاكتشاف الشذوذ وطرقًا لحساب الهيكل الرسومي لتباين البيانات.</p><h3>23. sklearn.cross_decomposition</h3><p>توفر وحدة sklearn.cross_decomposition أدوات لنمذجة العلاقة بين مجموعتين من البيانات المتعددة المتغيرات. تستخدم طرق مثل التحليل التوافقي القانوني (Canonical Correlation Analysis، CCA) والتحليل الجزئي للأقل مربعات (Partial Least Squares، PLS) على نطاق واسع في مجالات مثل المعلوماتية الحيوية والكيمياء الحيوية، لاكتشاف العلاقات الخفية بين مجموعات البيانات.</p><h3>24. sklearn.decomposition</h3><p>يعد تقليل الأبعاد خطوة شائعة في معالجة البيانات عالية الأبعاد. توفر وحدة sklearn.decomposition تقنيات مثل تحليل المكونات الرئيسية (Principal Component Analysis، PCA) وتحليل المكونات المستقلة (Independent Component Analysis، ICA) وتحليل المصفوفة غير السالبة (Non-negative Matrix Factorization، NMF) لتقليل تعقيد البيانات، مع الحفاظ على الميزات الأكثر أهمية.</p><h3>25. sklearn.discriminant_analysis</h3><p>عند تصنيف البيانات، تتفوق طرق التحليل التمييزي في إيجاد حدود القرارات بين الفئات. تتضمن وحدة sklearn.discriminant_analysis طرقًا مثل Linear Discriminant Analysis (LDA) وQuadratic Discriminant Analysis (QDA)، وهي قوية في سيناريوهات التعلم الخاضع للإشراف، خاصة للمجموعات الصغيرة من البيانات ذات الفئات المتمايزة بقوة.</p><h3>26. sklearn.dummy</h3><p>في أي سير عمل تعلم آلي، من الضروري أن يكون لديك نموذج خط الأساس. توفر وحدة sklearn.dummy نماذج بسيطة تعتمد على القواعد وتستخدم كخط أساس للمقارنة. سواء كانت التنبؤات ثابتة أو تخمينًا عشوائيًا، يضمن مصنف أو معوض Dummy أنك تتجاوز الحد الأدنى من الأداء العشوائي.</p><h3>27. sklearn.exceptions</h3><p>يعرف كل مطور أهمية معالجة الأخطاء. تحتوي وحدة sklearn.exceptions على الاستثناءات التي تثيرها سكيت-ليرن، مثل NotFittedError أو ConvergenceWarning. تساعد هذه الاستثناءات المستخدمين في تحديد المشكلات مبكرًا في عملية التطوير، مما يجعل عملية تصحيح الأخطاء أكثر كفاءة.</p><h3>28. sklearn.experimental</h3><p>الابتكار هو المفتاح في الذكاء الاصطناعي، وسكيت-ليرن دائمًا في تطور. تحتوي وحدة sklearn.experimental على ميزات جديدة وخوارزميات لم يتم اختبارها بالكامل بعد. إنها مساحة حيث يمكن للمطورين استكشاف التقنيات المتطورة والمساهمة في قاعدة كود سكيت-ليرن.</p><h3>29. sklearn.gaussian_process</h3><p>توفر العمليات الغاوسية نهجًا احتماليًا لمشكلات الانحدار والتصنيف. تتضمن وحدة sklearn.gaussian_process طرقًا مثل GaussianProcessRegressor وGaussianProcessClassifier، التي تُستخدم في نمذجة العلاقات المعقدة وغير الخطية بين المتغيرات. تُعتبر هذه الطرق مفيدة بشكل خاص في حالات تكون فيها البيانات محدودة أو تتطلب تقديرات دقيقة.</p><h3>30. sklearn.inspection</h3><p>يعد فهم كيفية اتخاذ النماذج لقراراتها أمرًا بالغ الأهمية، خاصة في الصناعات الخاضعة للتنظيم. توفر وحدة sklearn.inspection أدوات مثل permutation_importance وpartial_dependence، التي تتيح للمطورين فحص أهمية الميزات وسلوك النموذج بطريقة شفافة. تساعد هذه الأدوات على تقديم تفسيرات حول كيفية تأثير كل ميزة على تنبؤات النموذج.</p><h3>31. sklearn.isotonic</h3><p>تركز وحدة sklearn.isotonic على الانحدار الأيزوتوني، وهو نوع من الانحدار يفترض وجود علاقة مرتبة (رتيبة) بين الميزات والمتغير الهدف. يُعد هذا النوع من الانحدار مفيدًا بشكل خاص في مشكلات التصنيف أو الترتيب التي تحتوي على بيانات ذات ترتيب طبيعي.</p><h3>32. sklearn.kernel_approximation</h3><p>تعتبر الأساليب المعتمدة على النواة قوية للعمل مع البيانات غير الخطية. توفر وحدة sklearn.kernel_approximation تقنيات مثل RBFSampler وNystroem، التي تقرّب التعيينات المعتمدة على النواة، مما يتيح استخدام الأساليب المعتمدة على النواة بكفاءة مع مجموعات البيانات الكبيرة.</p><h3>33. sklearn.kernel_ridge</h3><p>يُمزج الانحدار النواة مع انحدار المربعات الصغرى (Ridge Regression) مع خدعة النواة، مما يسمح بالتعامل مع العلاقات غير الخطية بين الميزات. تسهل وحدة sklearn.kernel_ridge استخدام هذه الطريقة، التي غالبًا ما تُستخدم مع مجموعات البيانات المعقدة حيث تكون النماذج الخطية غير كافية.</p><h3>34. sklearn.mixture</h3><p>نماذج المزيج هي نماذج احتمالية لتمثيل الفئات الفرعية داخل مجموعة البيانات العامة. تتضمن وحدة sklearn.mixture أدوات مثل نماذج المزيج الغاوسي (Gaussian Mixture Models، GMMs)، التي تُستخدم في مهام مثل تقدير الكثافة، والتجميع، واكتشاف الشذوذ.</p><h3>35. sklearn.multiclass</h3><p>تظهر مشكلات التصنيف متعدد الفئات بشكل شائع في التطبيقات الواقعية. توفر وحدة sklearn.multiclass أدوات لتمديد المصنفات الثنائية إلى سيناريوهات التصنيف متعدد الفئات. تشمل هذه الأدوات أساليب مثل One-vs-Rest (OvR) وOne-vs-One (OvO) التي تساعد في معالجة هذه المهام.</p><h3>36. sklearn.multioutput</h3><p>في بعض الأحيان، تحتاج نماذج تعلم الآلة إلى التنبؤ بأهداف متعددة في نفس الوقت. توفر وحدة sklearn.multioutput أدوات للتعامل مع هذا التعقيد من خلال توفير حلول للتصنيف والانحدار متعدد المخرجات. تكون هذه الأدوات مفيدة في مهام مثل تصنيف متعدد الملصقات أو التنبؤات المتعددة لسلسلة زمنية.</p><h3>37. sklearn.random_projection</h3><p>عند التعامل مع البيانات عالية الأبعاد، يعد تقليل الأبعاد أمرًا ضروريًا لكفاءة الحوسبة. توفر وحدة sklearn.random_projection طرقًا مثل الإسقاط العشوائي الغاوسي (Gaussian Random Projection) والإسقاط العشوائي المتناثر (Sparse Random Projection) لتقليل الأبعاد مع الحفاظ على بنية البيانات، وهي مفيدة بشكل خاص في تطبيقات تعلم الآلة واسعة النطاق.</p><h3>38. sklearn.semi_supervised</h3><p>التعلم شبه الخاضع للإشراف ذو قيمة عندما تكون نسبة صغيرة فقط من البيانات موسومة، بينما الباقي غير موسوم. توفر وحدة sklearn.semi_supervised خوارزميات مثل LabelPropagation وLabelSpreading التي تستفيد من بنية البيانات لنشر التصنيفات إلى الأمثلة غير الموسومة، مما يجعلها مفيدة في الحالات التي يكون فيها تمييز البيانات مكلفًا أو مستهلكًا للوقت.</p><h3>39. sklearn.utils</h3><p>تحتوي وحدة sklearn.utils على مجموعة من الوظائف والأدوات التي تدعم الوحدات المرئية في سكيت-ليرن. من أدوات التعامل مع البيانات إلى عمليات التحقق من الصلاحية، تساعد هذه الوحدة في التشغيل السلس عبر خوارزميات مختلفة. وظائف مثل shuffle وcheck_random_state وresample لا غنى عنها عند تجهيز البيانات أو ضمان تكرار النتائج في النماذج.</p><h3>خلاصة: لماذا تعد مكتبة سكيت-ليرن لا غنى عنها للذكاء الاصطناعي وتعلم الآلة؟</h3><p>لقد أصبحت مكتبة سكيت-ليرن أساسية في تطوير الذكاء الاصطناعي وتعلم الآلة لسبب وجيه. فهي تقدم مجموعة واسعة من الخوارزميات والأدوات التي تمتاز بالقوة وسهولة الاستخدام. تجعل معماريتها المعيارية والموثقة جيدًا بناء نماذج تعلم الآلة وضبطها أمرًا سهلًا، سواء كنت تبني نموذجًا أوليًا أو تعمل على أنظمة إنتاجية.</p><p>سواء كنت تقوم بتجربة طريقة تجميع جديدة، أو تحتاج إلى مقاييس دقيقة لتقييم نموذج انحدار، أو ترغب في تطبيق نهج تعلم بالجمع، فإن سكيت-ليرن تقدم لك كل ما تحتاجه. تعد قدرتها على التكيف، إلى جانب التزامها بدمج أحدث الأبحاث، سببًا في أنها لا غنى عنها لكل من يعمل في تعلم الآلة اليوم.</p><p>كمهندس أو باحث، فإن استخدامك لسكيت-ليرن يمنحك الحرية للتركيز على حل المشكلة بدلاً من الانشغال بتعقيدات التنفيذ، ولهذا السبب ستبقى هذه المكتبة في قلب العديد من مشاريع الذكاء الاصطناعي لسنوات قادمة.</p><h3>بالتوفيق في الترميز والنمذجة!</h3><p>كتبه: محمد ستيفي</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d604338d179" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>