<?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 Hussain Wali on Medium]]></title>
        <description><![CDATA[Stories by Hussain Wali on Medium]]></description>
        <link>https://medium.com/@hussainwali?source=rss-586da242886e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CQSN-W2-zTlbdc2Z.jpeg</url>
            <title>Stories by Hussain Wali on Medium</title>
            <link>https://medium.com/@hussainwali?source=rss-586da242886e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:03:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hussainwali/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[The Day Postgres Forgot Our Data Existed]]></title>
            <link>https://hussainwali.medium.com/the-day-postgres-forgot-our-data-existed-cb61c7ec3848?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb61c7ec3848</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[supabase]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 11:52:18 GMT</pubDate>
            <atom:updated>2026-10-22T11:52:18.851Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How out-of-date statistics turned a 4-second query into a 4-minute timeout, and why our test database couldn’t see it</em></p><p>**TL;DR**</p><ul><li>Before PostgreSQL runs a query, it first makes a plan: which table to read first, whether to use an index, how to combine the results. To make that plan quickly, it doesn’t count the rows in your tables. Instead it reads a short set of notes it keeps about each table, called <strong>statistics</strong> (for example: “this table has 150,000 rows, and these are it’s most common values”). Those notes are only as up to date as the last time Postgres refreshed them. So that</li></ul><blockquote>PostgreSQL doesn’t look at your data when it decides *how* to run a query. It looks at <strong>statistics</strong>: a small summary of the data it collected earlier.</blockquote><ul><li>On big tables, those statistics are refreshed only after about <strong>10% of the rows have changed.</strong> If you add a few thousand new rows to a table with millions, Postgres may not “see” them for days.</li><li>When Postgres thinks a table holds <strong>1 matching row</strong> but it really holds 60k, it can pick a strategy that works fine for 1 row but would be catastrophic for 60k rows.</li><li>Local copy of the database always has fresh statistics, so the bug <strong>never shows up in testing, </strong>also on server like supabase there are timeout limits which are not there locally so its unlikely you will see any issue locally until it’s too late.</li><li>The fix is simple once you know it: run ANALYZE right after a bulk write, before a heavy query that depends on the data.</li></ul><p>For the sake of understanding lets imagine you are working on a learning platform. Students join a <strong>cohort, </strong>take a course made of 8 modules, and get a score for each module. At the end, the platform adds up each student’s module scores, checks who meets the requirements for a certificate and builds a leaderboard.</p><p>Launching a new cohort looks like this:</p><ol><li>create the cohort and enroll students.</li><li>run <strong>grading: </strong>store a score for each student and module, then add those up into one total per student.</li><li>run the <strong>certificate check</strong>: test every student against the rules(minimum total score, all modules attempted and so on).</li><li>build the <strong>leaderboard.</strong></li></ol><p>The backend is Postgresql behind an API layer that cancels any database query that runs longer than 4 seconds. That limit is a good thing. It stops one runaway query from hogging the database. But it also means a slow query doesn’t just feel slow; it fails.</p><p>One afternoon, someone on the team launches a brand new cohort of 5000 students, runs grading and run certificate check. It fails with:</p><pre>canceling statement due to statement timeout (error code 57014)</pre><p>On retry the same error. When you look closer, there’s something even stranger: <strong>every student’s total score is 0, </strong>even though the individual module scores were stored just fine.</p><p>Two separate symptoms. As it turns out, one root cause.</p><p>— — — -</p><h4>First, a two-minue lesson on query planner</h4><p>when you send Postgres a query, it doesn’t run it straight away. First, a component called <strong>query planner </strong>decides <em>how</em> to run it. For a query that joins two tables, it might choose between strategies like:</p><ul><li><strong>nested loop</strong>: for each row in table A, look up the matching row in table B. Excellent when A has a very few rows.</li><li><strong>Hash join: </strong>build a lookup table from B once, then stream A through it. Excellent when both sides are large.</li></ul><p>The planner picks a strategy by <strong>estimating how many rows each step will produce. </strong>It doesn’t count the rows to do that, because counting would often cost as much as running the query. Instead it reads its <strong>statistics: </strong>roughly how many rows each table has and which values are most common in each column.</p><h4>How statistics get refreshed (and why big tables fall behind)</h4><p>Postgres refreshes statistics with a command called ANALYZE. You can run it yourself as well, but mostly a background process called <strong>autovacuum</strong> runs it for you when “enough” of the table has changed.</p><p>“Enough” is defined by this formula (these are default settings):</p><pre>refresh when changed rows &gt; 50+10% of the table&#39;s rows</pre><p>For a small table, that’s nothing: a table with 1,000 rows gets refreshed after 150 changes. But look at what it means for a big table, in our Learning Platform scenario:</p><ul><li>the enrollments table has about 200,000 rows. the refresh trigger is around 20,000 changed rows. The new cohort addes 5000.</li><li>the module_scores table has about 3 million rows. The trigger is around 300,000 changed rows. Grading the new cohort writes 40000 rows.</li></ul><p>Neither table comes close to its trigger. So as far as the planner is concerned, <strong>the new cohort doesn’t even exist yet.</strong></p><p>You can check this yourself on any table:</p><pre>select relname,<br>       n_live_tup as row,<br>       n_mod_since_analyse as changed_since_last_refresh,<br>       last_autoanalyze<br>from pg_stat_user_tables<br>where relname = &#39;your_tables&#39;</pre><p>In a case like this, you’ll typically see that the last refresh happened <em>before </em>the new rows arrived, and that tens of thousands of rows have changed since. Postgres took its snapshot of the guest list before anyone showed up.</p><p>— -</p><h4>What a wrong estimate actually does</h4><p>To see what the planner decides, you put EXPLAIN in front of a query. <strong>EXPLAIN </strong>only shows the plan; it doesn’t run anything, so it’s a safe even for an UPDATE on production.</p><p>This is a shorthand version of what a plan for the score-totalling step can look like in this situation:</p><pre>Update on module_scores<br>  -&gt; Nested Loop (rows=1)<br>    -&gt; Index Scan on module_scores (rows=1)<br>      index cond: (cohort_id=2121)<br>    -&gt; Subquery scan on attempt_counts (rows=1)<br>      -&gt; GroupAggregate (rows=1)<br>        -&gt; Nested Loop Left join (rows=1)<br>          ...</pre><p>See all those row=1 , Postgres believes the new cohort has <strong>one</strong> module-score row. The real number is <strong>40000</strong>.</p><p>Believing there’s only one row, it chooses a nested loop and places a whole sub-calculation (counting attempts per student and module) <em>inside</em> the loop. For 1 row, that sub-calculation runs once. for 40000 rows it runs 40,000 TIMES, and each run processes about 40,000 rows itself. That’s well over <strong>a billion steps.</strong></p><p>With fresh statistics, the same query is planned with rows =40,000, uses hash joins and finishes in seconds instead of timeout error. With stale statisticis it can run for many minutes and never finish within any sensible timeout.</p><h4>Why exactly “1 row”?</h4><p>Part of the statistics is a list of the <strong>most common values</strong> in a column, with how often each appears. If almost every existing cohort is on that list, the list covers nearly 100% of the rows. When the planner meets a value that isn’t on the list (like a brand-new cohort), it assumes the value must be rare, because the list already accounts for nearly everything. So the new cohort is estimated at almost no rows, which gets rounded to 1.</p><p>It comes from how its notes are written.</p><ol><li>the notes contian a<strong> top list</strong> for each column. for the ‘cohort_id’ column of ‘module_score’, Postgres writes down the most common values and what share of the table each one takes up. Something like this:</li></ol><pre>cohort 14 -&gt; 4.1% of all rows<br>cohort 9  -&gt; 3.8% of all rows<br>cohort 28 -&gt; 3.5% of all rows<br>... and so on, for every cohort that existend when the notes were written</pre><p>2. Together, the list adds up to almost 100%. the platform has a few dozen cohorts, so all of them fit on the list. As far as the notes are concerned, the whole table is accounted for.</p><p>3. The new cohort isn’t on the list: the notes were written before it.</p><p>4. So postgres reasons: “My list already covers practically every row in this table. Anything that’s <strong>not</strong> on the list can only be sharing a tiny bit that’s left over. So this cohort must have almost now rows”</p><p>5. Postgres never estimates fewer than 1 row, so “almost none” becomes 1</p><p>Back to the wedding: imagine the printed guest list is grouped by family, and the families on it already fill every seat in the hall. A family that isn’t on the list yet gets planned for as if almost nobody from it is coming. Your friend still sets out one seat for them, just incase, because planning for zero would be odd. that one seat is postgres’s `<em>rows=1`</em></p><p>— -</p><h4>The detective work, step by step</h4><p>Every tool here is built into postgres, and this is the order that gets you to the answer fastest.</p><ol><li><strong>Is it slow, or is it waiting?</strong></li></ol><p>while the slow query is running check what it’s doing:</p><pre>select <br> pid,<br> now() - query_start as running_for,<br> state,<br> wait_event_type,<br> wait_event<br>from pg_stat_activity<br>where state = &#39;active&#39;;</pre><p>if wait_event is empty, the query isn’t stuck waiting for a lock or for the disk. It’s busy computing the whole time. That points at a bad plan rather than contention.</p><p>You can stop it safely with select pg_cancel_backend(&lt;pid&gt;); . Cancelling rolls the query back; nothing is half-written.</p><p><strong>2. Are the tables unhealthy?</strong></p><p>A common suspect for “slow on production, fast locally” is <strong>bloat</strong>: tables full of dead rows after many updates. Compare table sizes and dead-row counts ( n_dead_tupin pg_stat_user_tables ) between production and your test copy. If they’re similar, bloat isn’t the cause.</p><p><strong>3. How stale are the statistics?</strong></p><p>Run the pg_stat_user_tables query from earlier on the tables the new data just landed. A large n_mod_since_analyze and an old last_autoanalyze are the warning signs.</p><p><strong>4. What plan does production actually choose?</strong></p><p>run EXPLAIN on production. Tiny rows= numbers where you know there are thousands of rows, combined with Nested Loop , are the signals there is something wrong.</p><p><strong>5. Prove it.</strong></p><p>Run `ANALYZE` on the affected tables. This only refreshes statistics and doesn’t change any data. Then re-run the slow step. In our scenario:</p><p>| Step | Before `ANALYZE` | After `ANALYZE` |</p><p>| — -| — -| — -|</p><p>| Totalling the new cohort’s scores | 6+ minutes, never finished | about 12 seconds |</p><p>| Certificate check | timed out at 10 seconds | under 1 second |</p><p>And the cohort goes from “0 of 5,000 students certified” to the number you’d expect.</p><p><strong>Why tests don’t catch it</strong></p><p>This is the most important lesson.</p><p>Many teams test changes on a local copy of production, restored from a backup. <strong>Restoring a backup reloads every table, and that triggers a full statistics refresh.</strong> So on the local copy, the statistics are always perfectly fresh. The exact condition that breaks production (new rows the planner hasn’t seen) can never exist there.</p><p>Even trying to simulate it is tricky. If you delete the new rows, refresh statistics, and put the rows back, the planner may estimate a few dozen rows instead of 1, pick a different plan, and stay fast. The test looks realistic in every way except the one that matters.</p><p><strong>The takeaway:</strong> if a bug only appears on production, ask what is <em>different</em> about production that isn’t the data itself. Statistics, cache warmth, concurrent users, and table bloat are all invisible in a freshly restored copy.</p><p>— -</p><p><strong>A trap worth knowing: the “harmless” optimisation</strong></p><p>Here’s a mistake that’s very easy to make. You find a slow query and, while you’re in there, add a small optimisation: restrict one of the counts to only the students in the current cohort, since the rest will be thrown away anyway.</p><p>It tests beautifully. But it also makes the query’s speed depend on the planner knowing <strong>**how many students the cohort has**</strong>. For a brand-new cohort, the planner thinks the answer is 1, and the “optimisation” turns into a sub-query being re-run for every single student: 25 seconds instead of half a second.</p><p><strong>The takeaway:</strong> a clever restriction that makes a query faster <em>*when the estimates are right*</em> can make it dramatically slower <em>*when they’re wrong*</em>. If a query has to stay fast on brand-new data, prefer the plain version that doesn’t depend on the planner’s guess.</p><p>— -</p><p><strong>A bonus lesson: two jobs, one set of rows</strong></p><p>In our scenario, the failed certificate checks were clicked <strong>while grading was still running</strong> for the same cohort. Both processes update the same rows, and Postgres makes the second one wait until the first one is done.</p><p>You can reproduce this on purpose: one session updates a cohort’s rows and keeps its transaction open, a second session runs the certificate check on the same cohort. The second session shows `wait_event_type = Lock` and gets cancelled when it hits the timeout.</p><p>It’s an easy trap: if a long job and a user action touch the same rows, the user action can time out simply from waiting. The usual fix is for the second action to check whether the first is still running and refuse to start.</p><p>— -</p><p><strong>How to prevent it</strong></p><ol><li><strong>Refresh statistics right after bulk writes, before the heavy query.**</strong> This is the main fix. If a job writes tens of thousands of rows and then, seconds later, runs a big query over them, autovacuum (which checks for work only about once a minute) will usually be too late. An explicit refresh can’t lose that race:</li></ol><pre>ANALYZE module_scores;<br>ANALYZE enrollments;</pre><p>On a table with a few million rows this typically takes a second or two, because `ANALYZE` reads a random sample of rows, not the whole table. Compared with a multi-minute failure, that’s an easy trade.</p><p><strong>2. Lower the automatic refresh threshold on tables that grow in bursts.</strong> You can override the 10 % rule per table:</p><pre>ALTER TABLE enrollments<br>SET (autovacuum_analyze_scale_factor = 0.01,<br>autovacuum_analyze_threshold = 500);</pre><p>Now a refresh happens after about 2,500 changes instead of 20,000. It’s a safety net, not a guarantee, because of the timing issue above.</p><p><strong>3. Test with stale statistics on purpose.**</strong> Before changing a query that runs on fresh data, also time it in a state where the planner hasn’t seen that data yet, not only on a freshly restored copy.</p><p><strong>4. Measure on production without changing production.**</strong> Wrap the slow step in a block that raises an error at the end. The error rolls everything back, and the error message carries the timing:</p><pre>DO $$<br>DECLARE t0 timestamptz; ms int;<br>BEGIN<br>t0 := clock_timestamp();<br>PERFORM my_slow_function(&#39;some-id&#39;);<br>ms := round(extract(epoch FROM clock_timestamp() - t0) * 1000);<br>RAISE EXCEPTION &#39;RESULT (nothing committed): % ms&#39;, ms;<br>END $$;</pre><p>You get a real production measurement and nothing is saved. Just make sure the function only touches data you’re allowed to experiment with, and that nobody else is working on the same rows at the time.</p><p>— -</p><p><strong>Cheat sheet</strong></p><p>- The planner decides <strong>**how**</strong> to run a query from <strong>**statistics**</strong>, not by counting your data.</p><p>- Statistics refresh automatically after `50 + 10 %` of a table changes. On large tables, that can take days.</p><p>- New data the planner hasn’t seen is often estimated at <strong>**1 row**</strong>, which can lead to nested loops that explode.</p><p>- `EXPLAIN` shows the plan without running the query. Look for `rows=1` where you know there are thousands.</p><p>- `pg_stat_user_tables.n_mod_since_analyze` tells you how stale a table’s statistics are.</p><p>- `pg_stat_activity.wait_event` empty while a query runs for minutes means it’s computing, not waiting: suspect the plan.</p><p>- Run `ANALYZE` after bulk writes, before the query that depends on them.</p><p>- Restored backups have fresh statistics. “Works locally” doesn’t prove it works on production.</p><p>— -</p><p><em>*If this saved you an afternoon of head-scratching, I’d love to hear about the strangest planner surprise you’ve run into.*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb61c7ec3848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PostgreSQL Write-Ahead Logging (WAL), Pages, Memory, and Crash Recovery]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://hussainwali.medium.com/understanding-postgresql-write-ahead-logging-wal-pages-memory-and-crash-recovery-7eca432c7d37?source=rss-586da242886e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://hussainwali.medium.com/understanding-postgresql-write-ahead-logging-wal-pages-memory-and-crash-recovery-7eca432c7d37?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eca432c7d37</guid>
            <category><![CDATA[wal]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres-wal]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 15:50:59 GMT</pubDate>
            <atom:updated>2026-07-02T15:50:59.286Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Tutorial: Deploy a FastAPI Application to AWS ECS Fargate Using GitHub Actions CI/CD]]></title>
            <link>https://hussainwali.medium.com/tutorial-deploy-a-fastapi-application-to-aws-ecs-fargate-using-github-actions-ci-cd-39ac69446622?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ac69446622</guid>
            <category><![CDATA[cicd-pipeline]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 13:26:47 GMT</pubDate>
            <atom:updated>2025-11-06T09:35:10.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Deploy a FastAPI Application to AWS ECS Fargate Using GitHub Actions CI/CD" src="https://cdn-images-1.medium.com/max/1024/1*Jf_EDH-OQ63hor8Ta4quVA.png" /><figcaption>© <a href="https://www.linkedin.com/in/hussain-wali/">Hussain Wali</a></figcaption></figure><h3>Introduction</h3><p>Deploying a FastAPI application to AWS ECS Fargate with automated CI/CD using GitHub Actions is a robust, cloud-native workflow that delivers reliability, scalability, and operational efficiency. This modern approach leverages containerization, managed AWS infrastructure, and GitHub’s powerful automation features. In this hands-on guide, you’ll learn, step by step, to containerize a FastAPI app with Docker, push the image to Amazon ECR, and automate deployments to an ECS Fargate service via GitHub Actions.</p><p><strong>Scope:</strong></p><ul><li>FastAPI app project structure (best practices)</li><li>Creating a production-ready Dockerfile for FastAPI</li><li>Amazon ECR repository creation and authentication</li><li>Setting up an AWS ECS Cluster, Task Definition, and Fargate Service</li><li>GitHub Actions CI/CD workflow — authentication, build, push, and deploy</li><li>Security best practices for CI/CD and secrets</li><li>Troubleshooting ECS deployment errors</li><li>Concise Markdown formatting, with a workflow summary table</li></ul><p><strong>Result:</strong> <br> By the end, you’ll have a fully automated pipeline: each git push to main builds, publishes, and deploys a new version of your FastAPI service to production.</p><h3>Table: Key Steps &amp; Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Bds-yirGG7eYee4puzKpQ.png" /><figcaption>FastAPI CICD with github actions aws ecs fargate</figcaption></figure><p><strong>Elaboration:</strong> <br> This table lays out the DevOps lifecycle from app source to live deployment. For each step, you’ll find detailed instruction in the relevant section below. The flow matches real-world, modern workflows as implemented in current YouTube and web-based tutorials.</p><h3>1. FastAPI App Setup and Structure</h3><p>Set a solid foundation by structuring your FastAPI project for maintainability and ease of containerization.</p><p><strong>Recommended Structure:</strong></p><pre>my_fastapi_project/<br>├── app/<br>│   ├── __init__.py<br>│   ├── main.py<br>│   ├── routers/<br>│   │   └── users.py<br>│   ├── models/<br>│   ├── schemas/<br>│   ├── dependencies.py<br>│   ├── core/<br>│   │   ├── config.py<br>│   │   └── security.py<br>│   └── db/<br>│       └── database.py<br>├── tests/<br>│   ├── test_main.py<br>│   └── ...<br>├── requirements.txt<br>├── Dockerfile<br>├── .env<br>├── .gitignore<br>├── README.md</pre><p><strong>Key principles:</strong></p><ul><li>Separate routing, models, dependencies, and services for clarity.</li><li>Keep configs and secrets out of the code by using .env and environment variables.</li><li>Place entrypoint at app/main.py for consistent Docker use.</li></ul><p><strong>Sample entrypoint — </strong><strong>app/main.py:</strong></p><pre>from fastapi import FastAPI<br>from app.routers import users</pre><pre>app = FastAPI()<br>app.include_router(users.router)</pre><p>Using this scalable structure keeps your project production-ready and supports smooth testing and extension in the future.</p><h3>2. Creating a Production-Ready Dockerfile for FastAPI</h3><p><strong>Why Docker?</strong> <br> Containerization ensures that your app runs identically in development, CI, and production, eliminating “works on my machine” pain.</p><p><strong>Best Practices:</strong></p><ul><li>Use an official, slim Python base image (e.g., python:3.11-slim).</li><li>Install only production dependencies.</li><li>Expose only the necessary port (typically 80 or 8000).</li><li>Use Uvicorn for ASGI serving, set the working directory, and use non-root users as appropriate.</li></ul><h3>Example Dockerfile:</h3><pre>FROM python:3.11-slim</pre><pre>WORKDIR /app</pre><pre># Install dependencies first for better Docker cache usage<br>COPY requirements.txt .</pre><pre>RUN pip install --no-cache-dir -r requirements.txt</pre><pre># Copy application code<br>COPY ./app /app/app</pre><pre># Expose port<br>EXPOSE 80</pre><pre># Set non-root user (optional but recommended for security)<br># RUN useradd -m appuser<br># USER appuser</pre><pre># Start FastAPI app using Uvicorn<br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;80&quot;]</pre><ul><li><strong>requirements.txt:</strong></li></ul><pre>fastapi<br>uvicorn[standard]</pre><p><strong>Build and run locally for testing:</strong></p><pre>docker build -t fastapi-app .<br>docker run -p 80:80 fastapi-app</pre><p>Visit http://localhost/docs to confirm your OpenAPI docs appear.</p><p><em>Tip:</em> For advanced builds, consider multi-stage Dockerfiles or using Gunicorn with UvicornWorker for multi-process concurrency in high-traffic scenarios.</p><p>That little “Tip” is about making your FastAPI container more <strong>efficient</strong> and more <strong>capable of handling heavy traffic</strong> once it’s running in production:</p><h3>Multi‑stage Dockerfiles</h3><ul><li><strong>What it is:</strong> A Dockerfile that’s split into multiple build phases — e.g., one stage for compiling/installing dependencies, another for producing the slim final image.</li><li><strong>Why it’s useful:</strong></li><li>Your final image is <strong>smaller</strong>, so it pulls faster in ECS and costs less in storage.</li><li>You keep build‑only tools (compilers, test frameworks) out of production for <strong>security and speed</strong>.</li><li><strong>Example pattern:</strong></li></ul><pre># Stage 1: <br>Build FROM python:3.11-slim AS builder <br>WORKDIR /app <br>COPY requirements.txt . <br>RUN pip install --user -r requirements.txt  <br><br># Stage 2: Final image <br>FROM python:3.11-slim <br>WORKDIR /app <br>COPY --from=builder /root/.local /root/.local<br><br>COPY ./app /app/app <br>ENV PATH=/root/.local:$PATH<br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;80&quot;]</pre><ul><li>This keeps your runtime image lean — and lean images start faster in ECS.</li></ul><h3>Gunicorn with UvicornWorker</h3><ul><li><strong>What it is:</strong> Gunicorn is a battle‑tested Python WSGI/ASGI server that can manage <strong>multiple worker processes</strong>. UvicornWorker lets Gunicorn serve ASGI apps like FastAPI using Uvicorn under the hood.</li><li><strong>Why it’s useful:</strong></li><li>By default, Uvicorn in single‑process mode can only handle one request at a time per worker.</li><li>Gunicorn can launch <strong>multiple workers</strong> across available CPU cores — a must for high‑traffic APIs.</li></ul><p><strong>Example run command:</strong></p><pre>gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:80</pre><ul><li>Here, -w 4 means 4 worker processes — good for parallel request handling.</li></ul><p>Why should you do this? becaause:</p><ul><li><em>Multi‑stage builds</em> = faster, smaller, more secure containers.</li><li><em>Gunicorn + UvicornWorker</em> = parallel request handling, better performance under load.</li></ul><h3>3. Create and Authenticate with an Amazon ECR Repository</h3><p><strong>Amazon Elastic Container Registry (ECR)</strong> is AWS’s secure, managed Docker image registry. ECS services fetch images here.</p><p><strong>Step 1: Create the ECR repository</strong></p><pre>aws ecr create-repository --repository-name fastapi-ecs-app --region eu-central-1</pre><p>Take note of the <strong>repository URI</strong> output, which will be similar to:</p><pre>123456789012.dkr.ecr.eu-central-1.amazonaws.com/fastapi-ecs-app</pre><p><em>Tip:</em> Creating resources in eu-central-1 is ideal for deployments from Munich, Germany.</p><p><strong>Step 2: Authenticate Docker with ECR</strong></p><pre>aws ecr get-login-password --region eu-central-1 | \<br>docker login --username AWS --password-stdin 123456789012.dkr.ecr.eu-central-1.amazonaws.com</pre><p>You should see Login Succeeded if successful.</p><p><strong>Step 3: Tag and Push Docker Image</strong></p><pre>docker tag fastapi-app:latest 123456789012.dkr.ecr.eu-central-1.amazonaws.com/fastapi-ecs-app:latest<br>docker push 123456789012.dkr.ecr.eu-central-1.amazonaws.com/fastapi-ecs-app:latest</pre><p>This process can be incorporated into your GitHub Actions workflow for full automation (see section 6 below).</p><h3>4. Configuring AWS ECS Fargate Cluster and Service</h3><p><strong>Why ECS Fargate?</strong> <br> Fargate is AWS’s serverless compute engine for containers. No EC2 management, automatic scaling, and you only pay for resources used.</p><h3>Step A: Create an ECS Cluster</h3><ol><li>Go to the AWS ECS Console.</li><li>Click “Clusters” → “Create Cluster”.</li><li>Choose “Networking only (Fargate)”.</li><li>Name your cluster (fastapi-ecs-cluster).</li><li>Leave other defaults; create the cluster.</li></ol><h3>Step B: Register a Task Definition</h3><p>A <strong>task definition</strong> describes your container(s), resource needs, port mappings, logging, and more.</p><ol><li>Go to ECS → Task Definitions → Create new Task Definition → Fargate.</li><li>Configure container:</li></ol><ul><li>Image: 123456789012.dkr.ecr.eu-central-1.amazonaws.com/fastapi-ecs-app:latest</li><li>Memory: 512 MiB (or as needed)</li><li>CPU: 0.25 vCPU (or as needed)</li><li>Port mappings: 80 (container port)</li></ul><ol><li>Set Task Role and Task Execution Role.</li></ol><ul><li>Attach AmazonECSTaskExecutionRolePolicy for pull/log permissions.</li></ul><ol><li>Save the task definition. Note the family name (e.g., fastapi-ecs-task).</li></ol><h3>Step C: Create an ECS Service</h3><ol><li>ECS Console → Services → Create</li><li>Launch type: Fargate</li><li>Cluster: fastapi-ecs-cluster</li><li>Task Definition: select the previous or latest revision.</li><li>Service name: fastapi-ecs-service</li><li>Number of tasks: 1+ (for scaling)</li><li>Networking: Choose subnets/security groups as needed (ensure inbound port 80 and/or assign public IP or use an ALB for production).</li><li>(Optional but recommended) Integrate an Application Load Balancer.</li></ol><p><strong>At this point, your service will attempt to deploy, but will only start running cleanly once the Docker image is present in ECR and permissions are set correctly</strong>.</p><h3>5. GitHub Actions: AWS Authentication and Security Best Practices</h3><p><strong>Why GitHub Actions?</strong> <br> GitHub Actions provides a robust, native automation platform for CI/CD, integrating directly with your repository for event-driven workflows.</p><h3>Securing AWS Credentials</h3><p><strong>Best Practice:</strong> <br> Use short-lived credentials and OpenID Connect (OIDC) for AWS authentication, instead of storing AWS keys in GitHub Secrets.</p><h4>Option 1: OIDC (Recommended)</h4><ul><li>Create an IAM Role in AWS with trust policy for GitHub OIDC provider (https://token.actions.githubusercontent.com), scoping the audience and repository as necessary.</li><li>Grant least-privilege permissions needed for ECR/ECS automation.</li><li>In your workflow:</li></ul><pre>permissions:<br>  id-token: write<br>  contents: read<br>steps:<br>  - name: Configure AWS credentials<br>    uses: aws-actions/configure-aws-credentials@v4<br>    with:<br>      aws-region: eu-central-1<br>      role-to-assume: arn:aws:iam::123456789012:role/&lt;github-actions-role&gt;</pre><ul><li><strong>Documentation:</strong> <a href="https://github.com/aws-actions/configure-aws-credentials">aws-actions/configure-aws-credentials</a></li></ul><h4>Option 2: GitHub Secrets (Legacy but common)</h4><ul><li>Store AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as <a href="https://docs.github.com/en/actions/security-guides/encrypted-secrets">GitHub repository secrets</a>.</li><li>Reference them in the workflow:</li></ul><pre>with:<br>  aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>  aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>  aws-region: eu-central-1</pre><p><strong>Additional Tips:</strong></p><ul><li>Never hardcode credentials in code or YAML.</li><li>Use environment or organization-level secrets for fine-grained control.</li><li>Rotate secrets every 30–90 days.</li><li>Use least privilege IAM policies.</li></ul><h3>6. GitHub Actions: Workflow to Build, Push, and Deploy</h3><p>The centerpiece of the CI/CD automation is the .github/workflows/deploy.yml file.</p><p><strong>Below is a practical, modern workflow adapted from recent official and community guides, supporting OIDC authentication and safe image versioning:</strong></p><pre>name: Deploy FastAPI to AWS ECS<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>permissions:<br>  id-token: write<br>  contents: read<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout source code<br>        uses: actions/checkout@v4<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          aws-region: eu-central-1<br>          role-to-assume: arn:aws:iam::123456789012:role/github-actions-ecs-deploy<br><br>      - name: Log in to ECR<br>        uses: aws-actions/amazon-ecr-login@v2<br><br>      - name: Build, tag, and push Docker image to ECR<br>        env:<br>          ECR_REGISTRY: 123456789012.dkr.ecr.eu-central-1.amazonaws.com<br>          ECR_REPOSITORY: fastapi-ecs-app<br>          IMAGE_TAG: ${{ github.sha }}<br>        run: |<br>          docker build -t $ECR_REPOSITORY:$IMAGE_TAG .<br>          docker tag $ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG<br>          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG<br><br>      - name: Fill in the new image ID in the ECS task definition<br>        id: task-def<br>        uses: aws-actions/amazon-ecs-render-task-definition@v1<br>        with:<br>          task-definition: task-def.json<br>          container-name: fastapi-app<br>          image: 123456789012.dkr.ecr.eu-central-1.amazonaws.com/fastapi-ecs-app:${{ github.sha }}<br><br>      - name: Deploy to Amazon ECS<br>        uses: aws-actions/amazon-ecs-deploy-task-definition@v2<br>        with:<br>          task-definition: ${{ steps.task-def.outputs.task-definition }}<br>          service: fastapi-ecs-service<br>          cluster: fastapi-ecs-cluster<br>          wait-for-service-stability: true</pre><p><strong>Explanation by step:</strong></p><ul><li><strong>Checkout</strong>: Pulls code for build.</li><li><strong>Configure AWS credentials</strong>: Uses OIDC for secure, short-lived AWS access.</li><li><strong>Login to ECR</strong>: Authenticates Docker to your ECR registry.</li><li><strong>Build and push Docker</strong>: Tags your new image with the commit SHA for traceability, pushes to ECR.</li><li><strong>Render task definition</strong>: Updates the ECS task definition JSON to reference the new image.</li><li><strong>Deploy to ECS</strong>: Triggers an update of your ECS service, rolling out the new container image.</li></ul><p>This workflow ensures each GitHub push to main builds, pushes, and deploys your container in ECS Fargate, providing a fast feedback loop.</p><h3>Example: ECS Task Definition Snippet (task-def.json)</h3><p>A minimal ECS Fargate task definition referencing the FastAPI container:</p><pre>{<br>  &quot;family&quot;: &quot;fastapi-ecs-task&quot;,<br>  &quot;networkMode&quot;: &quot;awsvpc&quot;,<br>  &quot;containerDefinitions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;fastapi-app&quot;,<br>      &quot;image&quot;: &quot;123456789012.dkr.ecr.eu-central-1.amazonaws.com/fastapi-ecs-app:latest&quot;,<br>      &quot;portMappings&quot;: [<br>        { &quot;containerPort&quot;: 80, &quot;protocol&quot;: &quot;tcp&quot; }<br>      ],<br>      &quot;essential&quot;: true,<br>      &quot;logConfiguration&quot;: {<br>        &quot;logDriver&quot;: &quot;awslogs&quot;,<br>        &quot;options&quot;: {<br>          &quot;awslogs-group&quot;: &quot;/ecs/fastapi-ecs-service&quot;,<br>          &quot;awslogs-region&quot;: &quot;eu-central-1&quot;,<br>          &quot;awslogs-stream-prefix&quot;: &quot;ecs&quot;<br>        }<br>      }<br>    }<br>  ],<br>  &quot;requiresCompatibilities&quot;: [<br>    &quot;FARGATE&quot;<br>  ],<br>  &quot;cpu&quot;: &quot;256&quot;,<br>  &quot;memory&quot;: &quot;512&quot;<br>}</pre><ul><li>Keep this file in the root or in /deploy/aws/ and check it into git.</li><li>Images will be replaced with a new SHA tag on each build for traceability and rollback.</li></ul><p><strong>AWS resources required for the above setup:</strong></p><ul><li>ECS Cluster and Service (Fargate-compatible)</li><li>An ECR repository in your region</li><li>Load Balancer (ALB/NLB) for production traffic (recommended)</li><li>IAM roles and policies for ECS task execution and OIDC</li></ul><h3>7. Automating ECS Service Updates</h3><p>With the workflow above, ECS updates and rolls out new containers automatically via aws-actions/amazon-ecs-deploy-task-definition.</p><p><strong>For workflows using only AWS CLI (as in some tutorials), use:</strong></p><pre>aws ecs update-service \<br>  --cluster fastapi-ecs-cluster \<br>  --service fastapi-ecs-service \<br>  --task-definition fastapi-ecs-task:2 \<br>  --force-new-deployment</pre><p>But the aws-actions/* suite in GitHub Actions automates this in a code-managed, traceable way. The action waits for the update to complete, providing fail-fast feedback.</p><p><em>Best practice:</em> <br> <strong>Use unique image tags for each deployment</strong> (e.g., commit SHA); this supports safe rollback and traceability, instead of always overwriting the :latest tag.</p><h3>8. Security Best Practices in CI/CD</h3><h3>Storing and Using Secrets</h3><ul><li><strong>Never store AWS credentials in source code or logs</strong>.</li><li>Use OIDC for short-lived, ephemeral credentials whenever possible (now the industry standard).</li><li>Keep secrets in GitHub’s Secrets store; for critical workloads, explore using AWS Secrets Manager and referencing secrets from within task definitions.</li><li>Rotate credentials regularly and audit IAM permissions to minimize supply chain risk.</li><li>Use security context and non-root users in your Dockerfile where feasible.</li><li>Enable branch protections and CODEOWNERS in GitHub to restrict workflow edits.</li></ul><h3>Principle of Least Privilege</h3><ul><li>Configure IAM roles, policies, and GitHub repository permissions to grant only those rights necessary for deployment and monitoring.</li><li>Use separate OIDC roles or user credentials for different environments (staging, production).</li></ul><h3>Action Version Pinning &amp; Dependabot</h3><ul><li>Pin third-party GitHub Actions by SHA, not tag.</li><li>Use Dependabot to monitor for vulnerable actions and package updates.</li></ul><h3>9. Troubleshooting ECS Deployment Errors</h3><h4>Common Pitfalls and How to Fix Them:</h4><p><strong>1. Tasks Stay in PENDING/STOPPED State</strong></p><ul><li>Check your subnet: does it have enough free IPs for Fargate ENIs?</li><li>Is the security group open for the needed ports?</li><li>Does the task definition resource allocation (CPU, RAM) match your available capacity?</li><li>Are roles and policies correct for ECR pull and CloudWatch logging?</li></ul><p><strong>2. ECS Cannot Pull Image from ECR</strong></p><ul><li>Incorrect or missing IAM permissions for the ECS Task Execution Role.</li><li>ECR login failed or image tag mismatch.</li><li>Private subnet without NAT Gateway or VPC endpoint for ECR — Fargate cannot communicate with ECR.</li></ul><p><strong>3. Health Checks Fail</strong></p><ul><li>Security group/firewall prohibits ALB → container traffic.</li><li>FastAPI app is listening on a different port or interface than the ECS definition expects.</li><li>Health check path misconfigured (e.g., FastAPI default root is /, not /health unless coded).</li></ul><p><strong>4. Application Crashes at Startup</strong></p><ul><li>Syntax errors in code or in your Dockerfile’s CMD.</li><li>Code depends on environment variables not set.</li><li>Architecture mismatch (built for ARM, run on x86, or vice versa).</li><li>Check CloudWatch Logs for the relevant container log stream for error output.</li></ul><h3>How to Debug</h3><ul><li>Use <strong>ECS Task logs</strong> and AWS <strong>CloudWatch</strong> for stdout from your FastAPI app.</li><li>Enable <strong>ECS Exec</strong> to run a shell inside a running or failing task for live debugging.</li><li>Run your container locally with the docker run command to reproduce issues before deploying.</li></ul><p><strong>More troubleshooting guidance:</strong> <br> <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/failed-to-start-error.html">Amazon ECS Troubleshooting Guide</a> <br> <a href="https://chariotsolutions.com/blog/post/troubleshooting-ecs-deployments/">Chariot Solutions: ECS Troubleshooting</a> <br> <a href="https://infinitejs.com/posts/troubleshooting-ecs-deployment-issues/">InfiniteJS: Troubleshooting ECS Deployments</a></p><p>You now have a concise, modern, and practical workflow to deploy FastAPI applications to AWS ECS Fargate using GitHub Actions CI/CD. You learned to:</p><ol><li>Organize your FastAPI project for production.</li><li>Write a Dockerfile for consistent, secure image builds.</li><li>Store and push images to ECR.</li><li>Set up ECS Fargate infrastructure.</li><li>Use GitHub Actions with OIDC for secure, automated deployments.</li><li>Update ECS services and guarantee zero-downtime rollouts.</li><li>Secure your pipeline and credentials following modern DevOps security best practices.</li><li>Troubleshoot and resolve typical ECS container and AWS errors.</li></ol><p>This is a future-proof workflow used by thousands of teams worldwide as of 2025, and is adaptable to monoliths, microservices, ML APIs, and more.</p><p><strong>Ready to go live? Every push to your GitHub main branch will trigger a build, upload, and seamless production deployment on AWS — securely, repeatably, and with minimal friction.</strong></p><p><strong>If you run into issues, always check your AWS CloudWatch logs, ECS task definitions, IAM role permissions, and networking first. Consider automating more — blue/green or canary deployments, ALB/SSL setup, and infrastructure as code (e.g., with Terraform or AWS CDK) as your team grows.</strong></p><p><strong>Happy deploying! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ac69446622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI: BackgroundTasks vs Threads vs Async]]></title>
            <link>https://hussainwali.medium.com/fastapi-backgroundtasks-vs-threads-vs-async-f0020540bb87?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0020540bb87</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[threading]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 12:23:39 GMT</pubDate>
            <atom:updated>2025-07-17T12:40:11.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D62U1Ck4Z4vbNmO95c3V0A.png" /><figcaption>understanding background work in FastAPI</figcaption></figure><p>Have you ever wanted to run something in the background when a FastAPI endpoint is called? Like sending a notification, logging something, or listening to <strong>Kafka messages in the background</strong>?</p><p>There are multiple ways to run background tasks in FastAPI, and choosing the <strong>right one</strong> depends on what you’re trying to do.</p><p>In this guide, we’ll break it all down in simple language with examples, analogies, and code.</p><h4>Imagine you’re running a pizza shop:</h4><ul><li>A customer places an order.</li><li>You take the order, and immediately<em> move to the next customer.</em></li><li>Meanwhile, your team starts making the pizza <strong>in the background</strong>.</li></ul><p>This is the basic idea behind background tasks: <strong>handle the customer fast, but still finish the full job behind the scenes</strong>.</p><h3>🛠️ 1. BackgroundTasks in FastAPI</h3><p>BackgroundTasks is a <strong>FastAPI feature</strong> that lets you schedule a function to run <strong>after the response is sent</strong> — without blocking the user, meaning FastAPI gives you a built-in way to run background work <strong>after</strong> sending the response</p><h4>🔹 Use Case:</h4><ul><li>Logging</li><li>Sending emails/webhooks</li><li>Cleaning up temp files</li></ul><h4>Example:</h4><pre>from fastapi import FastAPI, BackgroundTasks<br>app = FastAPI()<br>def write_log(message: str):<br>    with open(&quot;log.txt&quot;, &quot;a&quot;) as f:<br>        f.write(message + &quot;\n&quot;)<br>@app.post(&quot;/order&quot;)<br>def place_order(background_tasks: BackgroundTasks):<br>    background_tasks.add_task(write_log, &quot;Order placed!&quot;)<br>    return {&quot;message&quot;: &quot;Your order is being processed!&quot;}</pre><ul><li>Runs <strong>after</strong> the response is sent</li><li>Uses the same thread or threadpool</li><li><strong>Not meant for long-running</strong> or infinite tasks</li></ul><h4>Don’t Use It For:</h4><ul><li>Kafka consumers</li><li>Long async jobs</li><li>Real-time background loops</li></ul><p><strong>🚫 Why Not Use </strong><strong>BackgroundTasks for Kafka?</strong></p><p>Kafka consumers:</p><ul><li>Run <strong>forever</strong></li><li>Block the thread or event loop</li><li>Need <strong>manual cancellation/cleanup</strong></li></ul><p>BackgroundTasks is designed for <strong>fire-and-forget</strong> short jobs, not for starting background loops.</p><h3>🔁 2. Async Background Loops using lifespan</h3><p>Let’s say you want to start a <strong>Kafka consumer</strong> that listens to events as long as the app is running.</p><p>This is more like a staff member who’s <strong>always listening for new pizza orders</strong>.</p><p>Use @asynccontextmanager and asyncio.create_task() to start it when FastAPI starts:</p><h4>Example:</h4><pre>from fastapi import FastAPI<br>from contextlib import asynccontextmanager<br>import asyncio<br><br>async def consume_kafka():<br>    while True:<br>        print(&quot;Listening to Kafka...&quot;)<br>        await asyncio.sleep(5)  # simulate waiting for messages<br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    task = asyncio.create_task(consume_kafka())<br>    print(&quot;App started. Kafka consumer running.&quot;)<br>    yield<br>    print(&quot;App shutting down. Cancelling task.&quot;)<br>    task.cancel()<br><br>app = FastAPI(lifespan=lifespan)</pre><h4>Use Cases:</h4><ul><li>Long-running async tasks</li><li>Kafka consumers</li><li>Monitoring loops</li></ul><h4>Why This Works:</h4><ul><li>Uses Python’s async event loop</li><li>Starts/stops cleanly with the app</li></ul><h3>🧵 3. Threads for Blocking Tasks</h3><p>Sometimes, you’re working with libraries that aren’t async at all (like kafka-python). These <strong>block</strong> the event loop.</p><p>This is like a worker who refuses to use the walkie-talkie system and only takes direct phone calls. You can’t interrupt them!</p><p>In that case, we offload them to a <strong>thread</strong>.</p><h4>Example:</h4><pre>import threading<br>from kafka import KafkaConsumer<br><br>def blocking_consumer():<br>    consumer = KafkaConsumer(&quot;my-topic&quot;, bootstrap_servers=&quot;localhost:9092&quot;)<br>    for msg in consumer:<br>        print(&quot;Got Kafka message&quot;, msg.value)<br><br>threading.Thread(target=blocking_consumer, daemon=True).start()</pre><p>You can put this inside lifespan() if you want it to start with FastAPI.</p><h3>Reminders:</h3><p>BackgroundTasks</p><ul><li>Good for Quick fire-and-forget jobs</li><li>Runs in Threadpool</li><li>not good for long running tasks</li></ul><p>lifespan + asyncio.task()</p><ul><li>For Async background loops</li><li>Runs in Event Loop</li><li>Use for long running tasks</li></ul><p>threading.Thread</p><ul><li>Use for unblocking Blocking libs like kafka-python</li><li>Runs in a separate thread.</li><li>Als can be used for long running tasks</li></ul><p>I want you to leave a comment even if you don’t like what you read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0020540bb87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how to implement logistic regression in PyTorch for Beginners]]></title>
            <link>https://hussainwali.medium.com/learn-how-to-implement-logistic-regression-in-pytorch-and-boost-your-ml-skills-1d7937fbd80e?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d7937fbd80e</guid>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 10:15:01 GMT</pubDate>
            <atom:updated>2025-07-17T12:40:50.617Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are Tensors?<br></strong>Tensors are multi-dimensional arrays with a uniform type (called a dtype). They are mathematical objects that generalize scalars, vectors, and matrices to higher dimensions. They are a key concept in fields such as physics and engineering, and more recently, in machine learning and data science, particularly in the context of deep learning frameworks like TensorFlow and PyTorch.</p><p>Here’s a simple way to understand tensors:</p><p>- A scalar, such as a single number like 7, can be considered a rank-0 tensor.<br>- A vector, which is an ordered array of numbers like [1, 2, 3], can be considered a rank-1 tensor.<br>- A matrix, which is a 2D grid of numbers, can be considered a rank-2 tensor.<br>- Tensors can have rank 3, 4, or more. For example, a rank-3 tensor could be visualized as a cube of numbers.</p><p>In the context of machine learning, tensors are used to encode the inputs, outputs, and transformations within neural networks. For example, an image might be represented as a rank-3 tensor, with dimensions corresponding to the height, width, and color channels of the image. <a href="https://www.tensorflow.org/guide/tensor">Tensors are immutable like Python numbers and strings: you can never update the contents of a tensor, only create a new one</a>.</p><p>Tensors are a fundamental data structure in PyTorch. They are a generalization of vectors and matrices to higher dimensions. Tensors can be used to represent any type of data, including images, audio, and text.</p><p>Here is an example of a tensor:</p><pre>import torch<br>tensor = torch.tensor([1, 2, 3, 4])<br>print(tensor)</pre><p>This code will print the following output:</p><pre>tensor(1, 2, 3, 4)</pre><p>As you can see, the tensor has 4 elements, and each element is a number.</p><h3>What is data preprocessing?</h3><p>Data preprocessing is the process of preparing data for analysis. This includes cleaning the data, formatting it, and transforming it into a format that is suitable for the analysis task at hand.</p><p>Data preprocessing is an important step in the machine learning process. It can help to improve the accuracy and efficiency of machine learning models.</p><h3>Why do we need data preprocessing?</h3><p>There are a number of reasons why we need data preprocessing. These include:</p><ul><li>To remove noise from the data. Noise is any unwanted data that can interfere with the analysis process. For example, if there are missing values in the data, these values will need to be removed before the data can be analyzed.</li><li>To format the data. The data may need to be formatted in a specific way before it can be used by machine learning algorithms. For example, the data may need to be converted into a numerical format or a categorical format.</li><li>To transform the data. The data may need to be transformed in a way that makes it more informative for machine learning algorithms. For example, the data may need to be normalized or standardized to reduce the impact of outliers.</li></ul><h3>Difference between PyTorch Tensors and Numpy array</h3><p>PyTorch tensors and NumPy arrays are both data structures that can be used to represent data. However, there are some key differences between the two data structures.</p><ul><li>PyTorch tensors are more flexible than NumPy arrays. PyTorch tensors can be used to represent data of any dimension, while NumPy arrays are limited to 2-dimensional data.</li><li>PyTorch tensors are more efficient than NumPy arrays. PyTorch tensors are optimized for use with machine learning algorithms, while NumPy arrays are not.</li><li>PyTorch tensors are easier to use with GPU acceleration. PyTorch tensors can be easily used with GPU acceleration, while NumPy arrays cannot.</li></ul><h3>What are categorical and numerical features?</h3><p>Categorical features are features that can be divided into categories, such as gender or race. Numerical features are features that can be represented as numbers, such as height or weight.</p><h3>What is data sampling?</h3><p>Data sampling is the process of selecting a subset of data from a larger dataset. Data sampling can be used to improve the performance of machine learning models by reducing the amount of data that needs to be processed.</p><p>There are two main types of data sampling:</p><ul><li>Random sampling: This is the simplest type of data sampling. A random sample is a subset of data that is selected randomly from the larger dataset.</li><li>Stratified sampling: This type of data sampling ensures that the subset of data is representative of the larger dataset. This is done by dividing the larger dataset into strata, and then randomly sampling from each stratum.</li></ul><h3>What is upsampling and downsampling?</h3><p>Upsampling and downsampling are two techniques that can be used to change the size of a dataset. Upsampling is the process of increasing the size of a dataset, while downsampling is the process of decreasing the size of a dataset.</p><p>Upsampling can be used to improve the performance of machine learning models by increasing the amount of data that is available. Downsampling can be used to improve the performance of machine learning models by reducing the amount of noise in the data.</p><h3>How to do label encoding of categorical features?</h3><p>Label encoding is a technique that can be used to convert categorical features into numerical features. This is done by assigning a unique number to each category.</p><p>For example, if you have a categorical feature with three categories, you could assign the number 0 to the first category, the number 1 to the second category, and the number 2 to the third category.</p><h3>How to scale numerical features?</h3><p>Scaling numerical features is a technique that can be used to normalize the data. This is done by subtracting the mean from each feature and then dividing by the standard deviation.</p><p>Scaling the data can help to improve the performance of machine learning models by making the data more consistent.</p><h3>What is Logistic Regression?</h3><p>Logistic regression is a type of machine learning algorithm that can be used for classification problems. It is a statistical model that predicts the probability of an event.</p><p>Logistic regression is a linear model, which means that it predicts the probability of an event as a linear function of the features. However, the output of the linear function is passed through a sigmoid function, which transforms the output into a probability.</p><p>The sigmoid function is a non-linear function that takes a real number as input and outputs a number between 0 and 1. The sigmoid function is often used in machine learning to transform the output of a linear model into a probability.</p><p>Logistic regression is a powerful tool for classification problems. It is relatively easy to understand and implement, and it can be very accurate.</p><h3>Types of Logistic Regression</h3><p>There are two main types of logistic regression:</p><ul><li>Binary logistic regression: This is the most common type of logistic regression. It is used to predict the probability of a binary event, such as whether a customer will click on an ad or not.</li><li>Multinomial logistic regression: This type of logistic regression is used to predict the probability of a multinomial event, such as which of three products a customer will buy.</li></ul><h3>What is a sigmoid function?</h3><p>The sigmoid function is a non-linear function that takes a real number as input and outputs a number between 0 and 1. The sigmoid function is often used in machine learning to transform the output of a linear model into a probability.</p><p>The sigmoid function is defined as:</p><pre>f(x) = 1 / (1 + e^(-x))</pre><p>where x is a real number.</p><p>The sigmoid function is a S-shaped curve that has a value of 0 when x is negative, a value of 0.5 when x is 0, and a value of 1 when x is positive.</p><h3>What is model optimization?</h3><p>Model optimization is the process of finding the best parameters for a machine learning model. This is done by iteratively adjusting the parameters of the model until the model achieves the desired performance.</p><p>There are a number of different optimization algorithms that can be used for model optimization. These algorithms include gradient descent, stochastic gradient descent, and Adam.</p><h3>What is an ADAM optimizer?</h3><p>ADAM is a popular optimization algorithm that is used for training machine learning models. ADAM stands for Adaptive Moment Estimation.</p><p>ADAM is a stochastic gradient descent algorithm that uses adaptive learning rates for each parameter of the model. This means that the learning rate for each parameter is adjusted based on the history of the parameter&#39;s gradients.</p><p>ADAM is a very effective optimization algorithm that can be used to train machine learning models quickly and efficiently.</p><h3>Implementation of logistic regression in PyTorch using all the aforementioned methods.</h3><p>Here is an example of how to implement logistic regression in PyTorch using all the aforementioned methods:</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br><br>class LogisticRegression(nn.Module):<br>    def __init__(self, num_features):<br>        super(LogisticRegression, self).__init__()<br>        self.linear = nn.Linear(num_features, 1)<br><br>    def forward(self, x):<br>        x = self.linear(x)<br>        x = torch.sigmoid(x)<br>        return x<br><br>def train(model, data, labels, epochs):<br>    optimizer = optim.Adam(model.parameters())<br>    for epoch in range(epochs):<br>        loss = 0<br>        for x, y in zip(data, labels):<br>            y_pred = model(x)<br>            loss += (y_pred - y).pow(2).sum()<br>            optimizer.zero_grad()<br>            loss.backward()<br>            optimizer.step()<br>    print(loss)<br><br>if __name__ == &#39;__main__&#39;:<br>    data = torch.randn(100, 10)<br>    labels = torch.randint(0, 2, (100,))<br>    model = LogisticRegression(10)<br>    train(model, data, labels, 10)</pre><p>This code will train a logistic regression model on a dataset of 100 features. The model will be trained for 10 epochs. The output of the code will be the loss of the model after the last epoch.</p><p>I hope this article has been helpful. Please let me know if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d7937fbd80e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Ubuntu Cuda for Obaabooga]]></title>
            <link>https://hussainwali.medium.com/setup-ubuntu-cuda-for-obaabooga-d033da0dbe80?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d033da0dbe80</guid>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Mon, 29 May 2023 10:27:30 GMT</pubDate>
            <atom:updated>2023-05-29T10:27:30.434Z</atom:updated>
            <content:encoded><![CDATA[<p>Go to this link and download the cuda toolkit:</p><p><a href="https://developer.nvidia.com/cuda-11-8-0-download-archive?target_os=Linux&amp;target_arch=x86_64&amp;Distribution=Ubuntu&amp;target_version=22.04&amp;target_type=deb_local">CUDA Toolkit 11.8 Downloads</a></p><p>This is my target platform config:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LX6nk6ZBtgNXIgkn31XKWw.png" /></figure><p>You will see these lines below the platfor configs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYnUlnDjMNa9UVZhgFfdag.png" /></figure><p>wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pinsudo mv cuda-ubuntu2204.pin/etc/apt/preferences.d/cuda-repository-pin-600</p><p>wget <a href="https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda-repo-ubuntu2204-11-8-local_11.8.0-520.61.05-1_amd64.deb">https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda-repo-ubuntu2204-11-8-local_11.8.0-520.61.05-1_amd64.deb</a></p><p>sudo dpkg -i cuda-repo-ubuntu2204-11-8-local_11.8.0-520.61.05-1_amd64.deb</p><p>sudo cp /var/cuda-repo-ubuntu2204-11-8-local/cuda-*-keyring.gpg /usr/share/keyrings/</p><p>sudo apt-get update</p><p>don’t run the last line instead run this:<br>sudo apt-get cuda-toolkit-11-8</p><p>This link is helpful in getting things fixed:<br><a href="https://docs.heavy.ai/v/v6.1.1/installation-and-configuration/installation/installing-on-ubuntu/centos-yum-gpu-os">https://docs.heavy.ai/v/v6.1.1/installation-and-configuration/installation/installing-on-ubuntu/centos-yum-gpu-os</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d033da0dbe80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Tensor Dimensions: A Comprehensive Guide for Deep Learning Practitioners]]></title>
            <link>https://hussainwali.medium.com/understanding-dimensions-in-tensors-8a852e6577c9?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a852e6577c9</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dimensions-in-tensors]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 14:26:14 GMT</pubDate>
            <atom:updated>2023-04-18T05:14:33.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2nKHBunf5aU7URW9" /><figcaption>Photo by <a href="https://unsplash.com/@adityachinchure?utm_source=medium&amp;utm_medium=referral">Aditya Chinchure</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Tensors are the fundamental data structure used in deep learning and machine learning algorithms. They are multi-dimensional arrays that can store and manipulate data efficiently. The concept of dimensions in tensors is essential to understand the structure and properties of tensors. In this article, we will discuss the dimensions in tensors, including real-world analogies. We will explain each point and provide examples, including code examples using PyTorch.</p><p><strong>Definition of Dimensions in Tensors:</strong></p><p>A dimension in tensors is a particular axis or direction in which the data is arranged. Each dimension represents a specific mode of variation or type of information that the tensor contains. The number of dimensions in a tensor is known as its rank. A scalar is a tensor with zero dimensions, a vector is a tensor with one dimension, and a matrix is a tensor with two dimensions.</p><p>To understand the dimensions in tensors, let’s consider an example of a black and white image. The image can be represented as a matrix where each pixel value is a scalar. The matrix has two dimensions — height and width. The height dimension represents the number of rows in the matrix, and the width dimension represents the number of columns in the matrix. In this case, the rank of the tensor is 2.</p><p>Another example is a color image, which can be represented as a tensor with three dimensions — height, width, and channels. The height and width dimensions represent the same as in the black and white image, while the third dimension represents the color channels — red, green, and blue. In this case, the rank of the tensor is 3.</p><p><strong>Representing Data with Tensors:</strong></p><p>Tensors are a convenient way to represent data in deep learning and machine learning algorithms. They are used to store and manipulate data of different types, including images, audio, text, and other forms of structured or unstructured data. Each dimension in the tensor represents a particular aspect of the data.</p><p>For example, a tensor representing a set of images can have four dimensions — batch size, height, width, and channels. The batch size dimension represents the number of images in the batch, and the other dimensions represent the same as in the color image example.</p><p><strong>Manipulating Tensors with Dimensions:</strong></p><p>Tensors can be manipulated using various mathematical operations and transformations. The operations are performed on specific dimensions of the tensor, depending on the desired outcome. For example, we can apply a convolution operation on the channels dimension of an image tensor to extract features.</p><p>In PyTorch, we can manipulate tensors using built-in functions and methods. Let’s consider the following example:</p><pre>import torch<br><br># Create a tensor of size 3x4x5<br>x = torch.randn(3, 4, 5)<br># Get the shape of the tensor<br>print(x.shape) # Output: torch.Size([3, 4, 5])<br># Get the size of a specific dimension<br>print(x.size(1)) # Output: 4<br># Reshape the tensor<br>y = x.view(3, 20)<br>print(y.shape) # Output: torch.Size([3, 20])<br># Transpose the tensor<br>z = x.transpose(0, 2)<br>print(z.shape) # Output: torch.Size([5, 4, 3])</pre><p>Here we create a tensor of size 3x4x5 and perform various operations on it. We get the shape of the tensor using the shape method and the size of a specific dimension using the size method. We also reshape the tensor using the view method and transpose it using the transpose method.</p><p><strong>Conclusion:</strong></p><p>In conclusion, dimensions in tensors are an essential concept in deep learning and machine learning algorithms. Understanding the dimensions of tensors is crucial to working with them effectively. By understanding the structure and properties of tensors, we can manipulate and process data more efficiently and accurately.</p><p>In this article, we have discussed the definition of dimensions in tensors, real-world analogies to help understand the concept, and how to represent and manipulate data using tensors. We have also provided examples and code using PyTorch to illustrate these concepts.</p><p>If you found this article helpful, please consider following me for more content on deep learning and machine learning. Also, don’t forget to clap for this article to show your appreciation and help others discover it. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a852e6577c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning with Limited Data: A Deep Dive into Zero-Shot and Few-Shot Learning]]></title>
            <link>https://hussainwali.medium.com/machine-learning-with-limited-data-a-deep-dive-into-zero-shot-and-few-shot-learning-b04c0d3bf1ec?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b04c0d3bf1ec</guid>
            <category><![CDATA[zero-shot-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[few-shot-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 09:37:54 GMT</pubDate>
            <atom:updated>2023-04-13T09:37:54.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h1qaxUN6BELJB3Es.jpg" /></figure><p>Machine learning has revolutionized the way we solve problems, from image recognition to natural language processing. However, in some cases, it may not be possible to gather labeled data for all possible classes or to have a large number of examples per class. This is where zero-shot learning and few-shot learning come into play. Zero-shot learning is a machine learning technique that allows models to recognize and classify objects it has never seen before, while few-shot learning is a technique that enables models to learn to recognize new classes with only a few examples. In this article, we will delve deeper into these two techniques, exploring how they work, where they are used, and their limitations. We will also discuss popular methods for implementing zero-shot learning and few-shot learning and the challenges associated with each technique. By the end of this article, you will have a better understanding of these two important machine learning techniques and their potential applications.</p><p><strong>Zero-Shot Learning:</strong></p><p>Have you ever wondered how a machine learning model can recognize objects it has never seen before? This is where zero-shot learning comes into play. Zero-shot learning is a machine learning technique where a model can recognize and classify objects it has never seen before.</p><p><strong>How Does Zero-Shot Learning Work?</strong></p><p>In zero-shot learning, the model is trained on a set of classes, but the model is evaluated on a different set of classes that were not used during training. The model leverages semantic relationships between classes to generalize to new classes. This means that the model learns how different classes are related to each other, allowing it to recognize new classes based on their similarity to known classes.</p><p><strong>Where is Zero-Shot Learning Used?</strong></p><p>Zero-shot learning is useful in situations where it is not feasible or practical to gather labeled data for all possible classes. For example, in image recognition, it may not be possible to gather labeled data for every possible object that the model may encounter.</p><p><strong>Popular Methods for Zero-Shot Learning</strong></p><p>Some popular methods for zero-shot learning include attribute-based methods, generative methods, and embedding-based methods. Attribute-based methods use a set of attributes to describe each class, allowing the model to recognize new classes based on their attribute similarities to known classes. Generative methods use a generative model to synthesize examples of new classes based on their semantic descriptions. Embedding-based methods learn a continuous representation of classes in a high-dimensional space, allowing the model to recognize new classes based on their proximity to known classes in this space.</p><p><strong>Few-Shot Learning:</strong></p><p>In some cases, it may be possible to gather labeled data for a set of classes, but there may be limited examples available for each class. This is where few-shot learning comes into play. Few-shot learning is a machine learning technique where a model is trained on a small number of examples per class.</p><p><strong>How Does Few-Shot Learning Work?</strong></p><p>Few-shot learning is a subset of the broader field of transfer learning, which aims to leverage knowledge learned from one task to improve performance on another task. In few-shot learning, the model is trained on a small number of examples per class, allowing it to learn to recognize new classes with only a few examples.</p><p><strong>Where is Few-Shot Learning Used?</strong></p><p>Few-shot learning is useful when there are limited labeled examples available for training, which is often the case in real-world applications. For example, in medical image analysis, there may be only a small number of labeled examples for a rare disease.</p><p><strong>Popular Methods for Few-Shot Learning</strong></p><p>Few-shot learning can be accomplished through methods such as meta-learning, model-agnostic meta-learning, and metric-based learning. Meta-learning involves training the model on a set of tasks, each with its own set of classes and a small number of examples per class. The model learns to learn new tasks by generalizing from its previous experiences. Model-agnostic meta-learning involves training a separate model to learn how to adapt the primary model to new tasks. Metric-based learning involves learning a distance metric between examples and using this metric to classify new examples based on their similarity to known examples.</p><p>Conclusion:</p><p>In conclusion, both zero-shot learning and few-shot learning are useful machine learning techniques that allow models to recognize new classes with limited labeled data. Zero-shot learning leverages semantic relationships between classes to generalize to new classes, while few-shot learning leverages knowledge learned from a small number of examples to recognize new classes. Both techniques have a wide range of applications in fields such as image recognition, natural language processing, and medical image analysis. If you found this article helpful, please don’t hesitate to give it a clap!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b04c0d3bf1ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding TextCNN]]></title>
            <link>https://hussainwali.medium.com/understanding-textcnn-bbcec4044eb0?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbcec4044eb0</guid>
            <category><![CDATA[textcnn]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[cnn]]></category>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 07:29:08 GMT</pubDate>
            <atom:updated>2023-03-21T07:29:08.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*F6ZSPV6iMpgjrNH0.jpg" /></figure><p>Have you ever wondered how we can analyze and extract useful information from text data? Well, one of the most popular methods used for this purpose is TextCNN (Convolutional Neural Network for Text Classification).</p><p>In this article, I will explain what TextCNN is, its pros and cons, the types of projects it can be used to build, and provide examples for each. Additionally, I will provide a step-by-step guide for beginners to advanced understanding, using PyTorch. Lastly, I will list some TextCNN alternatives that can also be used for text classification tasks.</p><p><strong>What is TextCNN?</strong></p><p>TextCNN is a deep learning algorithm that uses a convolutional neural network to classify text. It is a popular method for text classification tasks such as sentiment analysis, spam detection, and topic categorization.</p><p>It takes the text input and converts it into a matrix of numbers by representing each word as a vector. The convolutional layer applies filters over the input matrix to detect features such as n-grams (groups of n consecutive words) and their combinations. These features are then passed through a max-pooling layer to reduce the dimensionality of the output. The resulting features are then fed into a fully connected layer for classification.</p><p>One of the main advantages of TextCNN is that it can effectively capture local and global features in text data. This makes it suitable for tasks where the order and arrangement of words are important, such as sentiment analysis. TextCNN is also computationally efficient, making it faster than some other deep learning algorithms.</p><p>However, TextCNN has some limitations. It may struggle with longer texts as it may lose the context of the whole document. Additionally, TextCNN requires a large amount of training data to achieve good performance.</p><p><strong>Project Types and Examples</strong></p><p>TextCNN can be used for a variety of text classification tasks such as sentiment analysis, spam detection, and topic categorization. Let’s take a look at some examples of projects that can be built using TextCNN.</p><ol><li>Sentiment Analysis: TextCNN can be used to analyze the sentiment of movie reviews, tweets, and customer feedback. For example, a sentiment analysis model can be trained on the IMDB movie reviews dataset using TextCNN to classify reviews as positive or negative.</li><li>Spam Detection: TextCNN can be used to detect spam messages in email and text messages. For example, a spam detection model can be trained on the SMS Spam Collection dataset using TextCNN to classify messages as spam or not spam.</li><li>Topic Categorization: TextCNN can be used to categorize news articles, academic papers, and social media posts. For example, a topic categorization model can be trained on the 20 Newsgroups dataset using TextCNN to classify news articles into different categories such as sports, politics, and technology.</li></ol><p><strong>Step-by-Step Guide to Learning TextCNN</strong></p><p>Here is a step-by-step guide for beginners to advanced understanding of TextCNN using PyTorch:</p><ol><li>Install PyTorch: Install PyTorch using pip or conda. You can follow the instructions on the PyTorch website.</li><li>Prepare Data: Download and preprocess the data for your text classification task. You can use popular datasets such as <a href="https://www.kaggle.com/datasets/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews/download?datasetVersionNumber=1">IMDB</a>, <a href="https://www.kaggle.com/datasets/amananandrai/ag-news-classification-dataset/download?datasetVersionNumber=2">AG News</a>, and <a href="https://www.kaggle.com/datasets/crawford/20-newsgroups/download?datasetVersionNumber=1">20 Newsgroups</a>.</li><li>Create Vocabulary: Create a vocabulary of words and their corresponding indices. You can use the torchtext library to do this.it’s important to represent words as numerical vectors because deep learning algorithms work with numerical data. Creating a vocabulary of words and their corresponding indices means mapping each unique word in the dataset to a unique numerical index. For example, the word “cat” might be assigned the index 1, and the word “dog” might be assigned the index 2. This vocabulary is then used to convert the words in the dataset into numerical vectors.The torchtext library is a popular Python library for natural language processing tasks that can be used to create a vocabulary. It provides tools for preprocessing text data, building a vocabulary, and creating data iterators for training deep learning models, using the torchtext library:</li></ol><pre>import torchtext<br># define the fields for the data<br>TEXT = torchtext.data.Field(sequential=True, tokenize=&#39;spacy&#39;)<br>LABEL = torchtext.data.LabelField()<br># load the dataset<br>train_data, test_data = torchtext.datasets.IMDB.splits(TEXT, LABEL)<br># build the vocabulary using the training data<br>TEXT.build_vocab(train_data, max_size=10000)<br># print the size of the vocabulary<br>print(&#39;Vocabulary size:&#39;, len(TEXT.vocab))</pre><p>Here we first define two fields TEXT and LABEL that we will use to process our text data. TEXT is set to be sequential, meaning it represents a sequence of words, and is tokenized using the Spacy tokenizer. LABEL is used to represent the label of each example in our dataset.</p><p>We then load the <strong>IMDB </strong>dataset using these fields, which contains movie reviews along with their positive/negative sentiment labels.</p><p>Next, we build the vocabulary using the TEXT field and the training data. We set a maximum vocabulary size of 10,000 words. The build_vocab function creates a mapping of each unique word in the training data to a numerical index, which we can use to represent the text data as numerical vectors.</p><p>4. Define Model: Define the TextCNN model using PyTorch. You can define the model using nn.Module class and implement the forward function.</p><p>5. Train Model: Train the TextCNN model on the training dataset using the Adam optimizer and Cross Entropy Loss. You can train the model using the torch.utils.data.DataLoader class and nn.CrossEntropyLoss function.</p><p>6. Evaluate Model: Evaluate the trained TextCNN model on the test dataset. You can use accuracy, precision, recall, and F1-score metrics to evaluate the performance of the model.</p><p>7. Tune Hyperparameters: Tune the hyperparameters of the TextCNN model to improve its performance. You can experiment with different learning rates, batch sizes, filter sizes, and dropout rates.</p><p>8. Save and Load Model: Save the trained TextCNN model and load it for later use. You can use the torch.save() and torch.load() functions to save and load the model respectively.</p><p><strong>TextCNN Alternatives</strong></p><p>While TextCNN is a popular method for text classification tasks, there are also other deep learning algorithms that can be used for this purpose. Some alternatives to TextCNN include:</p><ol><li>LSTM (Long Short-Term Memory): LSTM is a type of recurrent neural network that can capture long-term dependencies in sequential data.</li><li>GRU (Gated Recurrent Unit): GRU is another type of recurrent neural network that can capture temporal dependencies in sequential data.</li><li>Transformer: Transformer is a type of neural network that can process variable-length sequences of data without relying on sequential processing. It is commonly used in natural language processing tasks.</li></ol><p>It has its pros and cons, and can be used for various text classification tasks such as sentiment analysis, spam detection, and topic categorization. If you’re interested in learning more about TextCNN, follow the step-by-step guide and try it out for yourself using Pytorch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbcec4044eb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Multiclass Classification using PyTorch and FastText: A Step-by-Step Guide]]></title>
            <link>https://hussainwali.medium.com/simplifying-multiclass-classification-using-pytorch-and-fasttext-a-step-by-step-guide-a593f34eb260?source=rss-586da242886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a593f34eb260</guid>
            <dc:creator><![CDATA[Hussain Wali]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 12:43:04 GMT</pubDate>
            <atom:updated>2023-03-17T12:43:04.235Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you looking to classify your data into multiple classes but not sure where to start? Look no further! In this article, we will guide you through the process of implementing a multiclass classification model using PyTorch and FastText.</p><p>First, let’s start by understanding what multiclass classification is. In simple terms, multiclass classification is a type of machine learning problem where the task is to classify input data into multiple categories or classes. For example, classifying images of animals into different categories such as cats, dogs, and birds.</p><p>To start our implementation, we will first install the required libraries, namely PyTorch and FastText. You can install these libraries by running the following commands in your terminal:</p><pre>pip install torch<br>pip install fasttext</pre><p>Once we have installed the required libraries, let’s move on to the data loading process. For this example, let’s assume that our input data is in a file called ‘input_data.txt’. We can load this data into our program using the following code:</p><pre>import pandas as pd<br>data = pd.read_csv(&#39;input_data.txt&#39;, sep=&#39;\t&#39;, header=None)</pre><p>Next, we need to preprocess our data. Preprocessing involves converting our raw data into a format that can be easily understood by our machine learning model. In this example, we will be using FastText for preprocessing our data. We can preprocess our data using the following code:</p><pre>import fasttext<br>model = fasttext.train_unsupervised(&#39;input_data.txt&#39;)</pre><p>Once we have preprocessed our data, we can start building our neural network. For our multiclass classification model, we will be using a simple feedforward neural network with a single hidden layer. We can build our neural network using the following code:</p><p>Next, we need to define our loss function and optimizer. For this example, we will be using the cross-entropy loss function and the stochastic gradient descent optimizer. We can define our loss function and optimizer using the following code:</p><pre>import torch.optim as optim<br>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)</pre><p>Now, let’s move on to the training loop. The training loop involves iterating over our dataset, passing our input data through the neural network, calculating the loss, and updating the weights of our neural network. We can define our training loop using the following code:</p><pre>for epoch in range(100):  <br>    running_loss = 0.0<br>    for i in range(len(data)):<br>        inputs = torch.tensor(model[data.iloc[i][0]]).unsqueeze(0)<br>        labels = torch.tensor(data.iloc[i][1])<br>        optimizer.zero_grad()<br>        outputs = net(inputs)<br>        loss = criterion(outputs, labels)<br>        loss.backward()<br>        optimizer.step()<br>        running_loss += loss.item()<br>    print(&#39;Epoch %d loss: %.3f&#39; % (epoch + 1, running_loss / len(data)))</pre><p>Finally, we can use our trained neural network to make predictions on new data. We can make predictions using the following code:</p><pre>with torch.no_grad():<br>    inputs = torch.tensor</pre><p>Now, let’s move on to the inference part where we will use our trained neural network to make predictions on new data. We can make predictions using the following code:</p><pre>with torch.no_grad():<br>    inputs = torch.tensor(model[&#39;new input data&#39;]).unsqueeze(0)<br>    outputs = net(inputs)<br>    _, predicted = torch.max(outputs.data, 1)<br>    print(&#39;Predicted class:&#39;, predicted.item())</pre><p>In this code, we pass our new input data to our FastText model to preprocess it and then pass it to our neural network to make predictions. We use the torch.max() function to find the index of the class with the highest probability and print the predicted class.</p><p>While the model we have built is functional, there are some issues that may make it unsuitable for use in a production environment. Here are some of the issues and recommendations to fix them:</p><ol><li>Lack of data preprocessing: In our model, we have only used FastText for preprocessing our data. However, in a real-world scenario, the input data may require more extensive preprocessing such as data cleaning, feature extraction, and normalization. It is important to ensure that the input data is properly preprocessed to improve the accuracy of the model.</li><li>Overfitting: In our training loop, we have only used a simple feedforward neural network with a single hidden layer. While this may work well for small datasets, it may lead to overfitting when dealing with larger and more complex datasets. To address this issue, we can use techniques such as dropout, regularization, and early stopping.</li><li>Limited model evaluation: In our model, we have only evaluated the accuracy of the model on the training data. However, it is important to evaluate the model’s performance on a separate validation or test dataset to ensure that the model is not overfitting and to get a better estimate of the model’s accuracy.</li><li>Deployment and scalability: Finally, when deploying the model to a production environment, we need to ensure that the model is scalable and can handle a large volume of data in real-time. We may need to use techniques such as distributed training, model parallelism, and batch processing to ensure that the model is able to handle large datasets and high traffic.</li></ol><p>To make the model production-ready, we can take the following recommendations:</p><ol><li>Use a more extensive data preprocessing pipeline that includes data cleaning, feature extraction, and normalization.</li><li>Use a more complex neural network architecture such as convolutional neural networks or recurrent neural networks to address the issue of overfitting.</li><li>Evaluate the model’s performance on a separate validation or test dataset to get a better estimate of the model’s accuracy.</li><li>Use a containerization platform such as Docker to deploy the model to a production environment and ensure that the model is scalable and can handle a large volume of data in real-time.</li><li>Use a logging and monitoring system to track the model’s performance and detect any issues or errors that may arise.</li></ol><p>By following these recommendations, we can build a robust and scalable multiclass classification model that can be deployed to a production environment with high accuracy and reliability.</p><p>And that’s it! We have successfully built a multiclass classification model using PyTorch and FastText. With this model, we can classify our input data into multiple categories or classes with high accuracy.</p><p>We hope that you found this step-by-step guide useful and easy to follow. If you have any questions or feedback, feel free to leave a comment below. Don’t forget to follow us for more exciting articles on machine learning and data science, and please clap if you found this article helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a593f34eb260" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>