<?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 Kaletsidik Ayalew (Kal) on Medium]]></title>
        <description><![CDATA[Stories by Kaletsidik Ayalew (Kal) on Medium]]></description>
        <link>https://medium.com/@alexkalalw?source=rss-235359c734dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6k7mOyJQxrzTD9kr</url>
            <title>Stories by Kaletsidik Ayalew (Kal) on Medium</title>
            <link>https://medium.com/@alexkalalw?source=rss-235359c734dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:00:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexkalalw/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[From Localhost to Production: The Ultimate Guide to Deploying a JMS on Windows Server]]></title>
            <link>https://medium.com/@alexkalalw/from-localhost-to-production-the-ultimate-guide-to-deploying-a-jms-on-windows-server-6d2e99cd1439?source=rss-235359c734dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d2e99cd1439</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[journal-management]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[prisma-orm]]></category>
            <dc:creator><![CDATA[Kaletsidik Ayalew (Kal)]]></dc:creator>
            <pubDate>Fri, 01 May 2026 20:14:16 GMT</pubDate>
            <atom:updated>2026-05-01T20:14:16.886Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying a full-stack application isn’t just about moving code from one machine to another; it’s about orchestrating environment variables, security protocols, and network routing to ensure 24/7 availability. After successfully taking the Journal Management System (JMS) live at Addis Ababa University, I’ve documented every technical hurdle and configuration detail to serve as a roadmap for similar enterprise-grade deployments.</p><h3>Phase 1: Building from the Ground Up</h3><p>Before we talk about servers, we need a stable codebase. The JMS project is built with a React (Vite) frontend, a Node.js (Express) backend, and a PostgreSQL database managed via Prisma ORM.</p><h3>1. Backend Foundations</h3><p>The server-side logic handles authentication, manuscript submissions, and database interactions.</p><ul><li>Initialization: We start by setting up a Node environment and installing core dependencies: express, @prisma/client, cors, dotenv, jsonwebtoken, and bcrypt.</li><li>Database Schema: Using Prisma, we define our data models (Users, Manuscripts, Reviews) in schema.prisma.</li><li>Environment Configuration: A .env file is created to store sensitive strings like DATABASE_URL and JWT_SECRET.</li></ul><h3>2. Frontend Development</h3><p>The frontend is built for speed using the Vite build tool.</p><ul><li>API Integration: The frontend communicates with the backend via Axios. A critical step here is setting the VITE_API_URL to point to our backend port (defaulting to 4000 in dev).</li><li>Production Build: When ready, we run npm run build, which compiles the React code into a highly optimized dist folder ready to be served by a web server.</li></ul><h3>Phase 2: Preparing the Windows Server Environment</h3><p>Windows Server requires specific modules to act as a modern web host. You cannot simply run npm start and call it a day.</p><h3>1. The Software Stack</h3><p>A fresh Windows Server needs the following installed:</p><ul><li>Node.js (v18+ LTS): The runtime for our backend.</li><li>PostgreSQL: Our relational database engine.</li><li>IIS (Internet Information Services): The primary web server for Windows.</li><li>NSSM (Non-Sucking Service Manager): A tool to run the Node.js script as a background service.</li></ul><h3>2. IIS Feature Activation</h3><p>You must enable specific features within the “Turn Windows features on/off” menu:</p><ul><li>IIS Web Server: Ensure “Static Content” and “Default Document” are checked.</li><li>URL Rewrite Module: (Manual install) Essential for handling React Router and Proxy rules.</li><li>Application Request Routing (ARR) 3.0: Required to turn IIS into a Reverse Proxy.</li></ul><h3>Phase 3: The Deep-Dive Deployment Process</h3><p>This is where the magic happens. We need to bridge the gap between the internal Node process and the public-facing internet.</p><h3>1. Running the Backend as a Windows Service (NSSM)</h3><p>In production, if the server reboots or the Node process crashes, it must restart automatically.</p><ul><li>Installation: Open PowerShell and run C:\nssm\nssm.exe install JMS-Server.</li></ul><p>Configuration:</p><ul><li>Path: C:\Program Files\nodejs\node.exe.</li><li>Startup Directory: C:\jms\server.</li><li>Arguments: server.js.</li><li>Persistence: Set the service to SERVICE_AUTO_START to ensure zero manual intervention after power cycles.</li></ul><h3>2. Mastering the IIS Reverse Proxy</h3><p>Since our backend runs on port 4000 and IIS runs on port 80/443, we use ARR to tunnel traffic.</p><p>Step A: Enable Proxy in IIS Navigate to Server &gt; Application Request Routing Cache &gt; Server Proxy Settings. Check Enable Proxy and Reverse rewrite host in response headers.</p><p>Step B: The web.config Masterpiece Place this file in your frontend dist folder. It handles three vital tasks:</p><ol><li>API Proxying: Redirects /api requests to localhost:4000.</li><li>HTTPS Redirection: Forces all traffic to be secure.</li><li>React Router Support: Redirects all non-file requests to index.html to prevent 404 errors on page refresh.</li></ol><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;configuration&gt;<br>  &lt;system.webServer&gt;<br>    &lt;rewrite&gt;<br>      &lt;rules&gt;<br>        &lt;rule name=&quot;API Proxy&quot; stopProcessing=&quot;true&quot;&gt;<br>          &lt;match url=&quot;^api/(.*)&quot; /&gt;<br>          &lt;action type=&quot;Rewrite&quot; url=&quot;http://localhost:4000/api/{R:1}&quot; /&gt;<br>        &lt;/rule&gt;<br>        &lt;rule name=&quot;React Routes&quot; stopProcessing=&quot;true&quot;&gt;<br>          &lt;match url=&quot;.*&quot; /&gt;<br>          &lt;conditions logicalGrouping=&quot;MatchAll&quot;&gt;<br>            &lt;add input=&quot;{REQUEST_FILENAME}&quot; matchType=&quot;IsFile&quot; negate=&quot;true&quot; /&gt;<br>            &lt;add input=&quot;{REQUEST_FILENAME}&quot; matchType=&quot;IsDirectory&quot; negate=&quot;true&quot; /&gt;<br>          &lt;/conditions&gt;<br>          &lt;action type=&quot;Rewrite&quot; url=&quot;/index.html&quot; /&gt;<br>        &lt;/rule&gt;<br>      &lt;/rules&gt;<br>    &lt;/rewrite&gt;<br>  &lt;/system.webServer&gt;<br>&lt;/configuration&gt;</pre><h3>Phase 4: Networking, DNS, and the SSL Mystery</h3><p>One of the biggest hurdles in university-scale deployments is the “Split-Horizon” network architecture.</p><h3>1. Solving the “Failed to Fetch” SSL Error</h3><p>During deployment, background API calls often fail even if the main page loads. This is usually due to SSL Termination.</p><ul><li>The Problem: If you use a self-signed certificate, the browser trusts the page but blocks background fetch() calls.</li><li>The Solution: The university uses a Central Gateway Proxy (e.g., 213.55.95.87) that handles SSL. Our internal IIS server communicates via the internal IP (10.4.9.100), but the Gateway presents a trusted, CA-signed certificate to the public.</li></ul><h3>2. DNS and IP Mapping</h3><p>Your server has several identities:</p><ul><li>Internal IP: 10.4.9.100 (Used for departmental access).</li><li>Inbound Gateway: 213.55.95.87 (Where sinet.aau.edu.et points).</li><li>Outbound Interface: 196.189.55.75 (How the server sees the internet).</li></ul><p>A tracert command reveals the complex path data takes through the university fiber backbone and Ethio Telecom routers before reaching the global web.</p><h3>Troubleshooting &amp; Troubleshooting Tips</h3><ul><li>“wants to access local network” Popup: This happens if your frontend .env is still pointing to the 10.x.x.x IP instead of the official domain.</li><li>Port 80 Conflict: Ensure no other site in IIS is using “All Unassigned” port 80 if you have multiple bindings.</li><li>Prisma Errors: If the DB fails to connect, verify that your Windows Firewall allows inbound traffic on port 5432.</li></ul><h3>Future Works and Scaling</h3><p>Now that Sinet-JMS is live and stable, the roadmap for expansion includes:</p><ol><li>Amharic AI Integration: Building on local research to provide automated sentiment analysis for Amharic manuscript summaries.</li><li>Dockerization: Moving to a container-based deployment to allow other colleges to spin up their own instances in minutes.</li><li>Real-time Monitoring: Implementing Grafana dashboards to track server health and request latency.</li></ol><p>Final Status: Live, Secure, and Persistent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d2e99cd1439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Fixing “No Space Left on Device” During Kernel Updates on Ubuntu (Complete Guide)]]></title>
            <link>https://medium.com/@alexkalalw/%EF%B8%8F-fixing-no-space-left-on-device-during-kernel-updates-on-ubuntu-complete-guide-477f2c0ede13?source=rss-235359c734dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/477f2c0ede13</guid>
            <dc:creator><![CDATA[Kaletsidik Ayalew (Kal)]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 21:39:10 GMT</pubDate>
            <atom:updated>2026-04-08T21:52:12.323Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>🚨 Problem Overview</strong></h3><p><strong>If you’re working on an Ubuntu system (especially a VM or server), you may encounter a critical error while installing packages:</strong></p><pre>zstd: error 25 : Write error : No space left on device<br>E: mkinitramfs failure<br>update-initramfs: failed<br>dpkg: error processing package linux-image...</pre><p><strong>At first glance, this looks like a general disk issue — but often, your main disk has plenty of space.</strong></p><p><strong>So what’s really going on?</strong></p><h3><strong>🔍 Root Cause</strong></h3><p><strong>The problem is almost always caused by a full </strong><strong>/boot partition.</strong></p><p><strong>In many Linux setups:</strong></p><ul><li><strong>/boot is a small, separate partition (~300–500MB)</strong></li><li><strong>Kernel updates install files there:</strong></li><li><strong>vmlinuz-* (kernel image)</strong></li><li><strong>initrd.img-* (initramfs)</strong></li><li><strong>System.map-*</strong></li><li><strong>config-*</strong></li></ul><p><strong>When </strong><strong>/boot fills up:</strong></p><ul><li><strong>New kernel installation fails</strong></li><li><strong>initramfs cannot be generated</strong></li><li><strong>dpkg gets stuck in a broken state</strong></li></ul><h3><strong>🧪 Step 1: Diagnose the Problem</strong></h3><p><strong>Check disk usage:</strong></p><pre>df -h</pre><p><strong>Look specifically for:</strong></p><pre>/boot</pre><p><strong>If it’s near 100%, that’s your issue.</strong></p><h3><strong>📦 Step 2: Inspect Installed Kernels</strong></h3><pre>dpkg --list | grep linux-image</pre><p><strong>You may see something like:</strong></p><pre>ii  linux-image-5.x.x-old<br>iF  linux-image-5.x.x-new   (FAILED)</pre><p><strong>👉 </strong><strong>iF means:</strong></p><ul><li><strong>Installed</strong></li><li><strong>Failed configuration</strong></li></ul><h3><strong>⚠️ Important Concepts</strong></h3><p><strong>Before fixing:</strong></p><ul><li><strong>You must keep at least one working kernel</strong></li><li><strong>Never delete the currently running kernel:</strong></li></ul><pre>uname -r</pre><h3><strong>🔗 Step 3: Understand Dependency Chains</strong></h3><p><strong>Kernel packages are tied together:</strong></p><pre>linux-generic<br>  └── linux-image-generic<br>        └── linux-image-&lt;version&gt;<br>              ├── linux-modules<br>              └── linux-modules-extra</pre><p><strong>👉 This creates a dependency chain, which can block removal.</strong></p><h3><strong>🧨 Step 4: Remove Broken Kernel (Correct Way)</strong></h3><h3><strong>1. Remove meta packages first</strong></h3><pre>sudo dpkg --remove --force-remove-reinstreq linux-generic linux-image-generic</pre><h3><strong>2. Remove the broken kernel stack</strong></h3><pre>sudo dpkg --remove --force-remove-reinstreq \<br>linux-modules-extra-&lt;version&gt; \<br>linux-modules-&lt;version&gt; \<br>linux-image-&lt;version&gt;</pre><h3><strong>🧹 Step 5: Clean Package System</strong></h3><pre>sudo apt install -f<br>sudo apt autoremove -y</pre><h3><strong>💥 Step 6: Still Failing? Check </strong><strong>/boot Again</strong></h3><p><strong>Even after cleanup, you may still see:</strong></p><pre>No space left on device</pre><p><strong>List </strong><strong>/boot:</strong></p><pre>ls -lh /boot</pre><p><strong>You might find:</strong></p><pre>initrd.img-&lt;kernel&gt; → 200MB+ (very large)</pre><p><strong>👉 This is the real culprit.</strong></p><h3><strong>🔓 Step 7: Free Space Properly</strong></h3><h3><strong>❌ Common Mistake</strong></h3><p><strong>Moving the file <em>inside </em></strong><strong><em>/boot</em>:</strong></p><pre>mv file /boot/file.backup   ❌ (no space freed)</pre><h3><strong>✅ Correct Fix</strong></h3><p><strong>Move it outside </strong><strong>/boot:</strong></p><pre>sudo mv /boot/initrd.img-&lt;kernel&gt; /tmp/</pre><p><strong>Now check:</strong></p><pre>df -h /boot</pre><p><strong>You should see significant free space.</strong></p><h3><strong>🔄 Step 8: Rebuild initramfs</strong></h3><pre>sudo update-initramfs -c -k &lt;working-kernel&gt;</pre><p><strong>This recreates a fresh initrd.</strong></p><h3><strong>🔗 Step 9: Fix Symlink</strong></h3><pre>sudo ln -sf initrd.img-&lt;kernel&gt; /boot/initrd.img</pre><h3><strong>🔧 Step 10: Finalize Package State</strong></h3><pre>sudo dpkg --configure -a</pre><p><strong>No errors = system is healthy again.</strong></p><h3><strong>🧪 Step 11: Verify System</strong></h3><pre>df -h /boot<br>uname -r</pre><p><strong>Expected:</strong></p><ul><li><strong>/boot has free space</strong></li><li><strong>Kernel is valid</strong></li><li><strong>No dpkg errors</strong></li></ul><h3><strong>🚀 Optional: Restore Normal Kernel Updates</strong></h3><pre>sudo apt install linux-generic</pre><h3><strong>🧠 Lessons Learned</strong></h3><h3><strong>1. </strong><strong>/boot is a critical bottleneck</strong></h3><p><strong>Even if your system has hundreds of GB free, a tiny </strong><strong>/boot can break everything.</strong></p><h3><strong>2. Kernel installs are space-sensitive</strong></h3><p><strong>They require:</strong></p><ul><li><strong>Final space for files</strong></li><li><strong>Temporary space for compression</strong></li></ul><h3><strong>3. Dependency chains matter</strong></h3><p><strong>You cannot remove kernels without removing:</strong></p><ul><li><strong>linux-generic</strong></li><li><strong>linux-image-generic</strong></li></ul><h3><strong>4. Large initrd files are common</strong></h3><p><strong>Especially when:</strong></p><ul><li><strong>NVIDIA drivers are installed</strong></li><li><strong>Many modules are included</strong></li></ul><h3><strong>🔥 Prevention Tips</strong></h3><h3><strong>a. Clean unused kernels regularly:</strong></h3><pre>sudo apt autoremove</pre><h3><strong>b. Monitor </strong><strong>/boot usage:</strong></h3><pre>df -h /boot</pre><h3><strong>c. Avoid multiple kernels on small partitions</strong></h3><h3>Conclusion</h3><p>This issue is a <strong>classic Linux system failure scenario</strong>, especially on:</p><ul><li>VMs</li><li>Cloud instances</li><li>Systems with small /boot partitions</li></ul><p>By understanding:</p><ul><li>Kernel packaging</li><li>Dependency chains</li><li>initramfs behavior</li></ul><p>You can <strong>diagnose and fix it confidently</strong> without reinstalling your system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=477f2c0ede13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Package manager cache relocation and verification]]></title>
            <link>https://medium.com/@alexkalalw/package-manager-cache-relocation-and-verification-0e99cca49ae7?source=rss-235359c734dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e99cca49ae7</guid>
            <dc:creator><![CDATA[Kaletsidik Ayalew (Kal)]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 05:38:29 GMT</pubDate>
            <atom:updated>2026-04-02T05:38:29.224Z</atom:updated>
            <content:encoded><![CDATA[<p>This document shows how to move package-manager caches (pip / npm / yarn / pnpm) to another drive (example: D:) to keep your system drive (C:) free.</p><p>It includes cross-platform steps, per-user config examples, verification commands, safe deletion guidance, and troubleshooting tips.</p><h3>Why move caches</h3><ul><li>Package managers keep downloaded artifacts to speed up reinstalls and reduce bandwidth.</li><li>On systems with limited C: space, caches can fill up quickly (wheels, tarballs, npm packages).</li><li>Moving caches to a larger drive (e.g., D:\DevCache) keeps C: available.</li></ul><h3>Overview (Windows example)</h3><p>We demonstrate moving caches to D:\DevCache and creating per-user config so settings persist across sessions.</p><ol><li>Create folders on D: (example):</li></ol><pre>New-Item -ItemType Directory -Force -Path &#39;D:\DevCache\pip&#39;<br>New-Item -ItemType Directory -Force -Path &#39;D:\DevCache\npm-cache&#39;<br>New-Item -ItemType Directory -Force -Path &#39;D:\DevCache\yarn-cache&#39;</pre><ol><li>Configure each package manager (see below).</li><li>Verify with the package manager’s cache dir/list commands.</li><li>Optionally purge old cache on C: after verification.</li></ol><h3>pip (Python)</h3><p>Recommended approaches (Windows / macOS / Linux): either set the PIP_CACHE_DIR environment variable or use the pip config file.</p><h3>Option A — Per-user environment variable (Windows)</h3><p>Permanently set for your user (PowerShell):</p><pre>setx PIP_CACHE_DIR &quot;D:\DevCache\pip&quot;</pre><p>Then restart your terminal (or sign out/in). Verify in a new PowerShell session:</p><pre>echo $env:PIP_CACHE_DIR<br>python -m pip cache dir</pre><p>To set for the current session (immediate effect):</p><pre>$env:PIP_CACHE_DIR = &#39;D:\DevCache\pip&#39;</pre><h3>Option B — pip config file (preferred/permanent)</h3><p>Create a per-user config file:</p><ul><li>Windows: %APPDATA%\pip\pip.ini</li><li>macOS/Linux: ~/.config/pip/pip.conf or ~/.pip/pip.conf</li></ul><p>Example pip.ini content:</p><pre>[global]<br>cache-dir = D:\DevCache\pip</pre><p>After creating that file, pip will use the specified cache directory.</p><h3>Verify and manage cache</h3><pre>python -m pip cache dir      # shows active cache dir<br>python -m pip cache info     # shows cache info (if supported)<br>python -m pip cache list     # list cached files (older versions may not support)<br>python -m pip cache purge    # safely remove all cache files</pre><p>Notes:</p><ul><li>Deleting the cache does NOT remove installed packages in virtualenvs or site-packages.</li><li>If you delete the cache, future installs will re-download packages.</li></ul><h3>npm (Node.js)</h3><h3>Option A — npm config (global)</h3><p>Set global cache path:</p><pre>npm config set cache &quot;D:\DevCache\npm-cache&quot; --global</pre><p>Alternatively create/edit a per-user .npmrc file in your user home directory (%USERPROFILE%\.npmrc) and add:</p><pre>cache=D:\DevCache\npm-cache</pre><h3>Verify and manage</h3><pre>npm config get cache<br>npm cache verify          # checks integrity and reports size<br>npm cache clean --force   # clear the cache</pre><p>Notes:</p><ul><li>npm cache verify is safe and recommended to inspect cache.</li><li>npm cache clean --force removes files; it is safe (re-downloads later) but slower when reinstalling.</li></ul><h3>Yarn</h3><p>Yarn v1 (classic):</p><pre># set cache folder globally<br>yarn config set cache-folder &quot;D:\DevCache\yarn-cache&quot;<br># verify<br>yarn cache dir</pre><p>Yarn v2+ (berry) uses a different architecture (plug’n’play). Check yarn config for cacheFolder or workspace-level settings.</p><p>To clear cache (v1):</p><pre>yarn cache clean</pre><h3>pnpm</h3><p>pnpm has a global store. Set store-dir in .npmrc or via CLI:</p><pre>pnpm config set store-dir &quot;D:\DevCache\pnpm-store&quot;<br>pnpm store path<br># clear<br>pnpm store prune</pre><h3>Moving existing cache from C: to D:</h3><ol><li>Stop any package manager operations.</li><li>Copy the folder (so you have a backup) then verify:</li></ol><pre># copy (example for pip)<br>robocopy &quot;C:\Users\&lt;you&gt;\AppData\Local\pip\Cache&quot; &quot;D:\DevCache\pip&quot; /E</pre><ol><li>Update config/env variable (see above).</li><li>Verify python -m pip cache dir etc. shows new path.</li><li>After confirming everything works for a few installs, you can delete the old cache on C: to free space.</li></ol><h3>Inspecting cache size and largest files (PowerShell)</h3><p>Show total size for a cache folder:</p><pre>Get-ChildItem -Path &#39;D:\DevCache\pip&#39; -Recurse -ErrorAction SilentlyContinue |<br>  Measure-Object -Property Length -Sum |<br>  ForEach-Object { &#39;{0:N2} MB&#39; -f ($_.Sum/1MB) }</pre><p>List largest files (top 20):</p><pre>Get-ChildItem -Path &#39;D:\DevCache\pip&#39; -Recurse |<br>  Sort-Object Length -Descending |<br>  Select-Object FullName,@{Name=&#39;SizeMB&#39;;Expression={$_.Length/1MB}} -First 20</pre><h3>Safety and best practices</h3><ul><li>Deleting the cache does not uninstall packages; installed packages live in virtualenvs or system site-packages.</li><li>Use package-manager-provided commands (e.g., pip cache purge, npm cache verify) to safely manage caches.</li><li>If multiple users on the same machine need separate caches, configure per-user settings (do not use a shared folder unless permissions are handled).</li><li>Ensure antivirus or security software allows the chosen cache directory.</li><li>On Windows, watch for path-length issues when choosing deep folder structures.</li></ul><h3>Troubleshooting</h3><ul><li>If pip still shows the old cache location:</li><li>Restart your terminal/VS Code.</li><li>Ensure %APPDATA%\pip\pip.ini or ~/.config/pip/pip.conf has the correct cache-dir and no typos.</li><li>Check environment precedence: explicit PIP_CACHE_DIR env var overrides config file.</li><li>Permission errors:</li><li>Make sure your user account has read/write to the target folder.</li><li>Use icacls on Windows to adjust permissions if needed.</li><li>Disk quota / NTFS compression:</li><li>If space is still tight, consider compressing D:\DevCache with NTFS compression or moving to an external drive.</li></ul><h3>Example checklist to reproduce on a new machine (Windows)</h3><ol><li>Create folders on D: as needed.</li><li>Add per-user pip config:</li></ol><ul><li>create %APPDATA%\pip\pip.ini with cache-dir = D:\DevCache\pip.</li></ul><ol><li>Set npm/yarn/pnpm config as shown above.</li><li>Restart terminal/IDE and run:</li></ol><pre>python -m pip cache dir<br>npm config get cache<br>yarn cache dir<br>pnpm store path</pre><ol><li>If satisfied, optionally delete old C: cache after backing up.</li></ol><h3>Notes for sharing this across a team</h3><ul><li>Add a short docs/package_manager_cache.md (this file) to your repo and/or onboarding docs.</li><li>Keep instructions OS-specific and include commands for macOS/Linux where export PIP_CACHE_DIR=... and ~/.config/pip/pip.conf apply.</li><li>Consider an automation script (PowerShell) to create directories and write config files for new developer machines.</li></ul><p>If you want, I can:</p><ul><li>Add an automation PowerShell script to create the folders and write pip.ini / .npmrc / yarn settings for you.</li><li>Run a disk-usage report on D:\DevCache now and add its output to this doc.</li></ul><p>Let me know which (if any) to proceed with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e99cca49ae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MobileViT on CIFAR-10: The Hybrid Architecture that’s Redefining Edge AI]]></title>
            <link>https://medium.com/@alexkalalw/mobilevit-on-cifar-10-the-hybrid-architecture-thats-redefining-edge-ai-7d7f201c4d84?source=rss-235359c734dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7f201c4d84</guid>
            <dc:creator><![CDATA[Kaletsidik Ayalew (Kal)]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 08:38:10 GMT</pubDate>
            <atom:updated>2026-01-23T08:38:10.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Mobile Vision Dilemma</h3><p>In the world of mobile and edge computing, every millisecond and megabyte counts. When Apple researchers Sachin Mehta and Mohammad Rastegari introduced <a href="https://arxiv.org/pdf/2110.02178">MobileViT</a> in 2021, they promised a hybrid architecture that could deliver Transformer-level accuracy with CNN-like efficiency. But does this promise hold up in practice?</p><p>I set out to test MobileViT on the <a href="https://www.cs.toronto.edu/~kriz/cifar.html">CIFAR-10 dataset</a> — 60,000 32x32 RGB images across 10 classes — to answer a critical question: Is MobileViT ready for real-world edge deployment, or is it still a research curiosity?</p><h3>The Test: From Theory to Implementation</h3><h3>The “Dimension Defense” Challenge</h3><p>MobileViT’s core innovation is treating “Transformers as Convolutions” through an “unfold-transform-fold” mechanism. But could this handle real-world edge cases?</p><p>My first test threw six weird input shapes at the MobileViT block:</p><pre>test_shapes = [<br>    (3, 47, 33, 33),    # Batch=3, 47 channels, 33×33 resolution<br>    (1, 3, 31, 31),     # Single RGB image with odd dimensions<br>    (4, 64, 17, 17),    # Small batch with odd resolution<br>    (2, 32, 64, 64),    # Standard even dimensions<br>    (1, 16, 15, 15),    # Single channel with odd resolution<br>    (8, 128, 65, 65),   # Large batch with high channel count<br>]</pre><p>Result: 6/6 tests passed ✓<br>MobileViT’s dynamic unfolding and folding mechanism handled every single edge case, maintaining perfect input-output shape consistency. This robustness is crucial for real applications where input sizes can vary dramatically.</p><h3>Training on CIFAR-10</h3><p>I trained five models for a fair comparison:</p><ol><li>MobileViT-XXS (0.91M parametes)</li><li>MobileViT-XS (1.89M parameters)</li><li>MobileViT-S (3.82M parameters)</li><li>ResNet-18 (11.17M parameters)</li><li>MobileNetV2 (2.24M parameters)</li></ol><p>All models were trained for 10–15 epochs with the same basic augmentation (random cropping, flipping) and AdamW optimizer.</p><h3>The Results: Numbers Don’t Lie</h3><h3>Accuracy Showdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*D3-v2-DBfPxqu7eReKSomg.png" /></figure><p>Key Finding: MobileViT-XS achieves 87.79% accuracy with just 1.89M parameters — that’s 4.9× fewer parameters than ResNet-18 while sacrificing only 2.89% accuracy.</p><h3>The Speed-Accuracy Tradeoff</h3><p>This is where the real story unfolds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*ROIWOZOlhVEszq_2px3SSA.png" /></figure><p>The Tradeoff: MobileViT-XXS is 2.1× slower than MobileNetV2 but delivers +9.9% higher accuracy with 2.5× fewer parameters.</p><h3>The MobileViT Magic: Why It Works</h3><h3>Architecture Innovation</h3><p>MobileViT’s brilliance lies in three key innovations:</p><ol><li>Local-Global Fusion: Combines 3×3 convolutions (local) with Transformer attention (global)</li><li>Unfold-Transform-Fold: Treats spatial dimensions as sequence dimensions without losing structural information</li><li>Parameter Efficiency: Maintains CNN’s spatial inductive bias while gaining Transformer’s global context</li></ol><pre># The core MobileViT block operation<br>Input: (B, C, H, W) → Unfold → (B, P, N, d) <br>→ Transformer → Fold → (B, C, H, W)</pre><h3>Efficiency Analysis</h3><p>MobileViT’s parameter efficiency is staggering:</p><ul><li>MobileViT-XXS: 86.49% accuracy with 0.91M parameters = 95,159 parameters per % accuracy</li><li>MobileNetV2: 76.62% accuracy with 2.24M parameters = 292,352 parameters per % accuracy</li><li>ResNet-18: 90.68% accuracy with 11.17M parameters = 1,232,457 parameters per % accuracy</li></ul><p>MobileViT is 3× more parameter-efficient than MobileNetV2!</p><h3>The Reality Check: Current Limitations</h3><h3>The Speed Bottleneck</h3><p>Despite its parameter efficiency, MobileViT faces speed challenges:</p><ol><li>Transformer Operations: Self-attention’s O(N²) complexity adds overhead</li><li>Unfold/Fold Operations: Memory-intensive transformations not optimized for mobile</li><li>Lack of Hardware Acceleration: Unlike CNNs, Transformers lack dedicated mobile kernels</li></ol><h3>The Optimization Gap</h3><p>Our export attempts revealed current deployment challenges:</p><ul><li>Mobile Optimization: Needs framework-specific optimizations for CoreML/TFLite</li></ul><h3>Practical Implications</h3><h3>When to Choose MobileViT:</h3><p>✓ Accuracy-critical applications with strict size constraints<br>✓ Global context matters (scene understanding, object relationships)<br>✓ Memory is tighter than compute (embedded systems)<br>✓ Targeting future hardware with Transformer accelerators</p><h3>When to Stick with CNNs:</h3><p>✓ Maximum inference speed is non-negotiable<br>✓ Deploying on current-generation mobile CPUs<br>✓ Local features suffice (simple object detection)<br>✓ Working with established deployment pipelines</p><h3>The Future: Why MobileViT Matters</h3><h3>Hardware Evolution</h3><p>Current mobile chips (like Apple’s Neural Engine) are adding Transformer accelerators. When these become widespread, MobileViT’s speed disadvantage will shrink while its accuracy advantage remains.</p><h3>Research Impact</h3><p>MobileViT demonstrates that hybrid architectures aren’t just academic — they’re practical. The “CNNs vs Transformers” debate is giving way to “CNNs and Transformers” collaboration.</p><h3>Development Strategy</h3><p>For edge AI developers, MobileViT represents a strategic bet on hardware trends. Investing in MobileViT optimization today prepares you for tomorrow’s hardware landscape.</p><h3>Key Takeaways</h3><ol><li>Parameter Efficiency Champion: MobileViT delivers superior accuracy with significantly fewer parameters than any CNN counterpart</li><li>Speed-Accuracy Tradeoff Exists: Currently 2× slower than optimized CNNs, but the gap will narrow with hardware evolution</li><li>Production-Ready with Caveats: Robust architecture needs deployment optimization for mobile frameworks</li><li>Future-Proof Design: As mobile chips gain Transformer acceleration, MobileViT’s value proposition strengthens</li></ol><h3>The Bottom Line</h3><p>MobileViT isn’t just another research paper — it’s a practical blueprint for the future of edge vision. While currently slower than optimized CNNs on existing hardware, its parameter efficiency is undeniable. For applications where accuracy matters more than speed, or where memory is extremely constrained, MobileViT offers a compelling alternative.</p><p>The era of choosing between CNNs and Transformers is ending. The era of intelligent hybrids like MobileViT is just beginning.</p><p>Resources:</p><ul><li>Original Paper: <a href="https://arxiv.org/pdf/2110.02178">MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer</a></li><li>Dataset: <a href="https://www.cs.toronto.edu/~kriz/cifar.html">CIFAR-10</a></li><li>Code Implementation: <a href="https://colab.research.google.com/drive/1CoyRVWHEOas7I2wHAsCvCNft2OYULWm_?usp=sharing">Full Colab Notebook</a></li></ul><p>Next Steps: Optimizing MobileViT’s inference latency through kernel fusion and quantization could reduce the speed gap by 30–40%.</p><p>#MobileViT #EdgeAI #ComputerVision #Transformers #CNNs #MobileML #AIResearch #CIFAR10 #MachineLearning #DeepLearning #AppleResearch</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7f201c4d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gaussian Mixture Models and the EM Algorithm: A Complete Guide with Python Implementation]]></title>
            <link>https://medium.com/@alexkalalw/gaussian-mixture-models-and-the-em-algorithm-a-complete-guide-with-python-implementation-37ab7b46d7c9?source=rss-235359c734dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ab7b46d7c9</guid>
            <category><![CDATA[expectation-max-algorithm]]></category>
            <category><![CDATA[datascience-gmm]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mgm]]></category>
            <dc:creator><![CDATA[Kaletsidik Ayalew (Kal)]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 14:44:31 GMT</pubDate>
            <atom:updated>2025-12-31T14:44:31.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Gaussian Mixture Models (GMMs) represent a powerful approach to probabilistic clustering that goes beyond traditional hard-clustering methods like k-means. Unlike k-means, which assigns each data point to exactly one cluster, GMMs perform soft clustering — each point has a probability of belonging to each Gaussian component. This makes GMMs particularly useful for real-world data where boundaries between clusters are often ambiguous.</p><p>In this comprehensive guide, we’ll explore the mathematical foundations of GMMs, implement the Expectation-Maximization (EM) algorithm from scratch using only NumPy and Matplotlib, and demonstrate its application to synthetic 2D data. We’ll also cover model selection criteria (AIC/BIC) and provide complete, ready-to-use Python code.</p><h3>What are Gaussian Mixture Models?</h3><p>GMMs assume that data are generated from a mixture of several Gaussian distributions. Each Gaussian component has its own:</p><ul><li>Mean vector (μₖ) — the center of the cluster</li><li>Covariance matrix (Σₖ) — the shape and orientation of the cluster</li><li>Mixing weight (πₖ) — the probability that a randomly chosen data point comes from this component</li></ul><p>The probability density of observing a data point x is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*V8m6OfqxQ1u8T29qywq-xg.png" /></figure><p>where:</p><ul><li>K is the number of Gaussian components</li><li>πₖ ≥ 0 and ∑πₖ = 1 (valid probability distribution)</li><li>the Equation is the multivariate Gaussian distribution</li></ul><h3>The Expectation-Maximization (EM) Algorithm</h3><p>Since cluster assignments are latent (hidden) variables, we can’t directly compute maximum likelihood estimates. The EM algorithm solves this problem by iterating between two steps:</p><ol><li>E-step (Expectation): Estimate the posterior probabilities (responsibilities) of cluster assignments given current parameters</li><li>M-step (Maximization): Update parameters to maximize the expected complete-data log-likelihood</li></ol><p>The algorithm guarantees that the log-likelihood never decreases with each iteration, converging to a local maximum.</p><h3>Complete Python Implementation</h3><h3>1. Import Libraries</h3><p>python</p><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><h3>2. Generate Synthetic 2D Data</h3><pre>np.random.seed(42)<br><br># Dataset parameters<br>N = 300        # number of samples<br>D = 2          # dimensionality<br>K_true = 3     # true clusters<br># True parameters<br>true_means = np.array([[0, 0], [5, 5], [0, 5]])<br>true_covs = np.array([<br>    [[1.0, 0.5], [0.5, 1.0]],<br>    [[1.2, -0.3], [-0.3, 1.0]],<br>    [[0.5, 0.0], [0.0, 0.5]]<br>])<br>true_weights = np.array([0.3, 0.4, 0.3])<br># Sample cluster indices<br>cluster_ids = np.random.choice(K_true, size=N, p=true_weights)<br># Generate data<br>X = np.zeros((N, D))<br>for k in range(K_true):<br>    X[cluster_ids == k] = np.random.multivariate_normal(<br>        true_means[k], true_covs[k], size=(cluster_ids == k).sum()<br>    )<br># Visualize raw data<br>plt.figure(figsize=(8, 6))<br>plt.scatter(X[:, 0], X[:, 1], s=20, alpha=0.7)<br>plt.title(&quot;Synthetic 2D Dataset from Gaussian Mixture&quot;)<br>plt.xlabel(&quot;x₁&quot;)<br>plt.ylabel(&quot;x₂&quot;)<br>plt.grid(True, alpha=0.3)<br>plt.show()</pre><h3>3. Multivariate Gaussian Probability Density Function</h3><pre>def gaussian_pdf(X, mean, cov):<br>    &quot;&quot;&quot;<br>    Compute multivariate Gaussian density for all points in X.<br>    <br>    Parameters:<br>    X: (N, D) data matrix<br>    mean: (D,) mean vector<br>    cov: (D, D) covariance matrix<br>    <br>    Returns:<br>    densities: (N,) array of probabilities<br>    &quot;&quot;&quot;<br>    D = X.shape[1]<br>    diff = X - mean<br>    inv_cov = np.linalg.inv(cov)<br>    det_cov = np.linalg.det(cov)<br>    norm_const = 1.0 / np.sqrt((2 * np.pi)**D * det_cov)<br>    exponent = -0.5 * np.sum(diff @ inv_cov * diff, axis=1)<br>    return norm_const * np.exp(exponent)</pre><h3>4. E-Step: Computing Responsibilities</h3><p>The responsibility γᵢₖ represents the probability that data point i belongs to component k:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*vkYq3bhrMDYMQMhdzfI2dg.png" /></figure><pre>def e_step(X, weights, means, covs):<br>    &quot;&quot;&quot;<br>    Compute responsibilities matrix gamma (N x K)<br>    <br>    Returns:<br>    gamma: (N, K) responsibility matrix<br>    &quot;&quot;&quot;<br>    N = X.shape[0]<br>    K = len(weights)<br>    gamma = np.zeros((N, K))<br>    for k in range(K):<br>        gamma[:, k] = weights[k] * gaussian_pdf(X, means[k], covs[k])<br>    # Normalize rows (each row sums to 1)<br>    gamma /= gamma.sum(axis=1, keepdims=True)<br>    return gamma</pre><h3>5. M-Step: Parameter Updates</h3><p>Given responsibilities, we update parameters to maximize expected likelihood:</p><pre>def m_step(X, gamma):<br>    &quot;&quot;&quot;<br>    Update GMM parameters using current responsibilities<br>    <br>    Returns:<br>    weights: (K,) updated mixing coefficients<br>    means: (K, D) updated means<br>    covs: (K, D, D) updated covariance matrices<br>    &quot;&quot;&quot;<br>    N, D = X.shape<br>    K = gamma.shape[1]<br>    # Effective number of points in each cluster<br>    Nk = gamma.sum(axis=0)<br>    # Update weights<br>    weights = Nk / N<br>    # Update means<br>    means = (gamma.T @ X) / Nk[:, None]<br>    # Update covariances<br>    covs = np.zeros((K, D, D))<br>    for k in range(K):<br>        diff = X - means[k]<br>        covs[k] = (gamma[:, k][:, None] * diff).T @ diff / Nk[k]<br>        # Add small regularization for numerical stability<br>        covs[k] += 1e-6 * np.eye(D)<br>    return weights, means, covs</pre><h3>6. Log-Likelihood Computation</h3><pre>def compute_log_likelihood(X, weights, means, covs):<br>    &quot;&quot;&quot;<br>    Compute log-likelihood of data under current GMM parameters<br>    &quot;&quot;&quot;<br>    N = X.shape[0]<br>    K = len(weights)<br>    likelihood = np.zeros(N)<br>    for k in range(K):<br>        likelihood += weights[k] * gaussian_pdf(X, means[k], covs[k])<br>    return np.sum(np.log(likelihood + 1e-300))  # Add small constant for stability</pre><h3>7. EM Training Loop</h3><pre># Model parameters<br>K = 3<br>max_iters = 100<br>tol = 1e-4<br># Initialize parameters<br>weights = np.ones(K) / K<br>means = X[np.random.choice(N, K, replace=False)]<br>covs = np.array([np.cov(X, rowvar=False) for _ in range(K)])<br>log_likelihoods = []<br>print(&quot;Starting EM algorithm...&quot;)<br>print(&quot;-&quot; * 50)<br>for iteration in range(max_iters):<br>    # E-step<br>    gamma = e_step(X, weights, means, covs)<br>    <br>    # M-step<br>    weights, means, covs = m_step(X, gamma)<br>    <br>    # Compute log-likelihood<br>    log_likelihood = compute_log_likelihood(X, weights, means, covs)<br>    log_likelihoods.append(log_likelihood)<br>    <br>    # Print progress<br>    if iteration % 10 == 0:<br>        print(f&quot;Iteration {iteration:3d}: Log-likelihood = {log_likelihood:.2f}&quot;)<br>    <br>    # Convergence check<br>    if iteration &gt; 0 and abs(log_likelihoods[-1] - log_likelihoods[-2]) &lt; tol:<br>        print(f&quot;\nConverged after {iteration + 1} iterations&quot;)<br>        break<br>if iteration == max_iters - 1:<br>    print(f&quot;\nReached maximum iterations ({max_iters})&quot;)<br>print(&quot;-&quot; * 50)<br>print(f&quot;Final log-likelihood: {log_likelihoods[-1]:.2f}&quot;)</pre><h3>8. Visualization of Convergence</h3><pre>plt.figure(figsize=(10, 4))<br># Plot 1: Log-likelihood convergence<br>plt.subplot(1, 2, 1)<br>plt.plot(log_likelihoods, marker=&#39;o&#39;, linestyle=&#39;-&#39;, linewidth=2, markersize=5)<br>plt.xlabel(&quot;Iteration&quot;)<br>plt.ylabel(&quot;Log-Likelihood&quot;)<br>plt.title(&quot;EM Algorithm Convergence&quot;)<br>plt.grid(True, alpha=0.3)<br># Plot 2: Final clustering<br>plt.subplot(1, 2, 2)<br>labels = np.argmax(gamma, axis=1)<br>plt.scatter(X[:, 0], X[:, 1], c=labels, cmap=&quot;viridis&quot;, s=25, alpha=0.7)<br>plt.scatter(means[:, 0], means[:, 1], c=&quot;red&quot;, marker=&quot;X&quot;, s=200, <br>            linewidths=2, edgecolors=&#39;black&#39;, label=&#39;Cluster Centers&#39;)<br>plt.title(&quot;GMM Clustering Result&quot;)<br>plt.xlabel(&quot;x₁&quot;)<br>plt.ylabel(&quot;x₂&quot;)<br>plt.legend()<br>plt.grid(True, alpha=0.3)<br>plt.tight_layout()<br>plt.show()</pre><h3>9. Model Selection: AIC and BIC</h3><p>To choose the optimal number of clusters, we can use information criteria:</p><pre>def compute_model_criteria(X, weights, means, covs):<br>    &quot;&quot;&quot;<br>    Compute AIC and BIC for model selection<br>    &quot;&quot;&quot;<br>    N, D = X.shape<br>    K = len(weights)<br>    <br>    # Number of parameters<br>    # (K-1) mixing coefficients + K*D means + K*D*(D+1)/2 covariance parameters<br>    p = (K - 1) + K * D + K * (D * (D + 1) // 2)<br>    <br>    logL = compute_log_likelihood(X, weights, means, covs)<br>    <br>    # Akaike Information Criterion<br>    AIC = 2 * p - 2 * logL<br>    <br>    # Bayesian Information Criterion<br>    BIC = p * np.log(N) - 2 * logL<br>    <br>    return p, logL, AIC, BIC<br><br># Compute for our model<br>p, logL, AIC, BIC = compute_model_criteria(X, weights, means, covs)<br>print(&quot;\nModel Selection Criteria:&quot;)<br>print(&quot;=&quot; * 30)<br>print(f&quot;Number of parameters (p): {p}&quot;)<br>print(f&quot;Log-Likelihood: {logL:.2f}&quot;)<br>print(f&quot;AIC: {AIC:.2f}&quot;)<br>print(f&quot;BIC: {BIC:.2f}&quot;)<br>print(&quot;\nNote: Lower AIC/BIC values indicate better models&quot;)</pre><h3>10. Visualizing the Gaussian Components</h3><pre>def plot_gmm_components(X, weights, means, covs, gamma):<br>    &quot;&quot;&quot;<br>    Visualize GMM components with confidence ellipses<br>    &quot;&quot;&quot;<br>    plt.figure(figsize=(10, 8))<br>    <br>    # Plot data points colored by hard assignments<br>    labels = np.argmax(gamma, axis=1)<br>    scatter = plt.scatter(X[:, 0], X[:, 1], c=labels, cmap=&quot;tab20&quot;, <br>                         s=30, alpha=0.6, edgecolors=&#39;k&#39;, linewidth=0.5)<br>    <br>    # Plot means<br>    plt.scatter(means[:, 0], means[:, 1], c=&#39;red&#39;, marker=&#39;X&#39;, <br>                s=200, linewidths=2, edgecolors=&#39;black&#39;, zorder=5)<br>    <br>    # Plot covariance ellipses (2 standard deviations)<br>    from matplotlib.patches import Ellipse<br>    import matplotlib.transforms as transforms<br>    <br>    def confidence_ellipse(mean, cov, ax, n_std=2.0, **kwargs):<br>        &quot;&quot;&quot;<br>        Create a plot of the covariance confidence ellipse<br>        &quot;&quot;&quot;<br>        pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])<br>        ell_radius_x = np.sqrt(1 + pearson)<br>        ell_radius_y = np.sqrt(1 - pearson)<br>        ellipse = Ellipse((0, 0), width=ell_radius_x * 2, <br>                         height=ell_radius_y * 2, **kwargs)<br>        <br>        scale_x = np.sqrt(cov[0, 0]) * n_std<br>        scale_y = np.sqrt(cov[1, 1]) * n_std<br>        <br>        transf = transforms.Affine2D() \<br>            .rotate_deg(45) \<br>            .scale(scale_x, scale_y) \<br>            .translate(mean[0], mean[1])<br>        <br>        ellipse.set_transform(transf + ax.transData)<br>        return ax.add_patch(ellipse)<br>    <br>    # Plot ellipses for each component<br>    colors = plt.cm.tab20(np.linspace(0, 1, len(means)))<br>    for k, (mean, cov, color) in enumerate(zip(means, covs, colors)):<br>        confidence_ellipse(mean, cov, plt.gca(), n_std=2.0,<br>                          alpha=0.3, color=color, label=f&#39;Component {k+1}&#39;)<br>    <br>    plt.title(&quot;GMM Components with Confidence Ellipses (2σ)&quot;)<br>    plt.xlabel(&quot;x₁&quot;)<br>    plt.ylabel(&quot;x₂&quot;)<br>    plt.legend()<br>    plt.grid(True, alpha=0.3)<br>    plt.show()<br><br># Generate the visualization<br>plot_gmm_components(X, weights, means, covs, gamma)</pre><h3>Practical Applications and Considerations</h3><h3>When to Use GMMs:</h3><ol><li>Soft clustering needs (data points can belong to multiple clusters)</li><li>Density estimation tasks</li><li>Anomaly detection (low probability points are potential outliers)</li><li>Generative modeling (sampling new data points)</li></ol><h3>Common Challenges and Solutions:</h3><ol><li>Initialization sensitivity: Use k-means++ initialization or multiple random starts</li><li>Singular covariance matrices: Add regularization (as we did with 1e-6 * I)</li><li>Choosing K: Use cross-validation with AIC/BIC or the elbow method</li><li>Local optima: Run EM multiple times with different initializations</li></ol><h3>Extensions and Variants:</h3><ul><li>Bayesian GMMs: Place priors on parameters for regularization</li><li>Diagonal covariance GMMs: Faster computation for high dimensions</li><li>Spherical covariance GMMs: Simpler model (k-means-like)</li><li>Variational GMMs: Bayesian inference for very large datasets</li></ul><h3>Complete Code in One Block</h3><p>For easy copying, here’s the complete implementation:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br># Data generation<br>np.random.seed(42)<br>N, D, K_true = 300, 2, 3<br>true_means = np.array([[0, 0], [5, 5], [0, 5]])<br>true_covs = np.array([[[1.0, 0.5], [0.5, 1.0]], <br>                      [[1.2, -0.3], [-0.3, 1.0]], <br>                      [[0.5, 0.0], [0.0, 0.5]]])<br>true_weights = np.array([0.3, 0.4, 0.3])<br>cluster_ids = np.random.choice(K_true, size=N, p=true_weights)<br>X = np.zeros((N, D))<br>for k in range(K_true):<br>    X[cluster_ids == k] = np.random.multivariate_normal(<br>        true_means[k], true_covs[k], size=(cluster_ids == k).sum()<br>    )<br>    # GMM functions<br>def gaussian_pdf(X, mean, cov):<br>    D = X.shape[1]<br>    diff = X - mean<br>    inv_cov = np.linalg.inv(cov)<br>    det_cov = np.linalg.det(cov)<br>    norm_const = 1.0 / np.sqrt((2 * np.pi)**D * det_cov)<br>    exponent = -0.5 * np.sum(diff @ inv_cov * diff, axis=1)<br>    return norm_const * np.exp(exponent)<br>def e_step(X, weights, means, covs):<br>    N, K = X.shape[0], len(weights)<br>    gamma = np.zeros((N, K))<br>    for k in range(K):<br>        gamma[:, k] = weights[k] * gaussian_pdf(X, means[k], covs[k])<br>    gamma /= gamma.sum(axis=1, keepdims=True)<br>    return gamma<br>def m_step(X, gamma):<br>    N, D, K = X.shape[0], X.shape[1], gamma.shape[1]<br>    Nk = gamma.sum(axis=0)<br>    weights = Nk / N<br>    means = (gamma.T @ X) / Nk[:, None]<br>    covs = np.zeros((K, D, D))<br>    for k in range(K):<br>        diff = X - means[k]<br>        covs[k] = (gamma[:, k][:, None] * diff).T @ diff / Nk[k]<br>        covs[k] += 1e-6 * np.eye(D)<br>    return weights, means, covs<br>def compute_log_likelihood(X, weights, means, covs):<br>    N, K = X.shape[0], len(weights)<br>    likelihood = np.zeros(N)<br>    for k in range(K):<br>        likelihood += weights[k] * gaussian_pdf(X, means[k], covs[k])<br>    return np.sum(np.log(likelihood + 1e-300))<br># EM Algorithm<br>K, max_iters, tol = 3, 100, 1e-4<br>weights = np.ones(K) / K<br>means = X[np.random.choice(N, K, replace=False)]<br>covs = np.array([np.cov(X, rowvar=False) for _ in range(K)])<br>log_likelihoods = []<br>for iteration in range(max_iters):<br>    gamma = e_step(X, weights, means, covs)<br>    weights, means, covs = m_step(X, gamma)<br>    log_likelihood = compute_log_likelihood(X, weights, means, covs)<br>    log_likelihoods.append(log_likelihood)<br>    if iteration &gt; 0 and abs(log_likelihoods[-1] - log_likelihoods[-2]) &lt; tol:<br>        break<br># Results<br>print(f&quot;Converged in {iteration + 1} iterations&quot;)<br>print(f&quot;Final log-likelihood: {log_likelihoods[-1]:.2f}&quot;)<br># Visualization<br>labels = np.argmax(gamma, axis=1)<br>plt.figure(figsize=(12, 4))<br>plt.subplot(1, 2, 1)<br>plt.plot(log_likelihoods, marker=&#39;o&#39;)<br>plt.xlabel(&quot;Iteration&quot;)<br>plt.ylabel(&quot;Log-Likelihood&quot;)<br>plt.title(&quot;EM Convergence&quot;)<br>plt.grid(True)<br>plt.subplot(1, 2, 2)<br>plt.scatter(X[:, 0], X[:, 1], c=labels, cmap=&quot;viridis&quot;, s=25)<br>plt.scatter(means[:, 0], means[:, 1], c=&quot;red&quot;, marker=&quot;X&quot;, s=150)<br>plt.title(&quot;GMM Clustering Result&quot;)<br>plt.xlabel(&quot;x₁&quot;)<br>plt.ylabel(&quot;x₂&quot;)<br>plt.tight_layout()<br>plt.show()</pre><h3>Conclusion</h3><p>Gaussian Mixture Models combined with the EM algorithm provide a powerful framework for probabilistic clustering and density estimation. Unlike hard clustering methods, GMMs capture uncertainty in cluster assignments and can model clusters with different shapes and orientations.</p><p>Key takeaways:</p><ol><li>GMMs perform soft clustering via probability distributions</li><li>The EM algorithm efficiently handles latent variables</li><li>Model selection (AIC/BIC) helps choose the right number of components</li><li>Regularization is crucial for numerical stability</li><li>GMMs are generative models that can sample new data</li><li>This implementation provides a solid foundation that can be extended for various applications, from image segmentation to anomaly detection systems.</li></ol><h3>Further Reading</h3><ol><li>Bishop, C. M. (2006). <em>Pattern Recognition and Machine Learning</em>. Chapter 9.</li><li>Murphy, K. P. (2012). <em>Machine Learning: A Probabilistic Perspective</em>. Chapter 11.</li><li>Scikit-learn documentation on Gaussian Mixture Models</li><li>The original EM paper: Dempster, A. P., Laird, N. M., &amp; Rubin, D. B. (1977)</li></ol><p><em>Let’s connect on </em><a href="https://www.linkedin.com/in/kaletsidik-ayalew/"><em>LinkedIn</em></a><em> &amp; check out my </em><a href="https://github.com/AlexKalll/"><em>GitHub</em></a><em> for more implementations.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ab7b46d7c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>