<?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 Manjinder Singh on Medium]]></title>
        <description><![CDATA[Stories by Manjinder Singh on Medium]]></description>
        <link>https://medium.com/@manjindersingh_10145?source=rss-357a921631be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gz2tUSzvoaqDa6Z07hDIkA.jpeg</url>
            <title>Stories by Manjinder Singh on Medium</title>
            <link>https://medium.com/@manjindersingh_10145?source=rss-357a921631be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manjindersingh_10145/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[Data Engineering interviews are shifting towards System Design at a significant rate]]></title>
            <link>https://medium.com/@manjindersingh_10145/data-engineering-interviews-are-shifting-towards-system-design-at-a-significant-rate-87698c3a2e6a?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/87698c3a2e6a</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 20:04:52 GMT</pubDate>
            <atom:updated>2026-04-06T20:04:52.040Z</atom:updated>
            <content:encoded><![CDATA[<p>For years, the data engineering interview playbook was simple. Grind SQL window functions. Memorize PySpark transformations. Write Airflow DAGs on a whiteboard. Get an offer.</p><p><strong>That playbook is dead.</strong></p><p>In 2026, AI coding agents like Claude Code, Cursor, and GitHub Copilot aren’t just autocompleting your code. They’re writing entire ETL pipelines from a two-sentence prompt. They’re generating dbt models, Kafka consumers, and Spark jobs faster than any human ever could.</p><p>So if an AI agent can produce the same pipeline code as a candidate in under 60 seconds, what is that coding round even measuring anymore?</p><h3>The coding interview signal has collapsed.</h3><p>A recent survey of 400 engineering leaders confirmed what many of us already felt: take-home projects and automated code tests are losing their effectiveness fast. Interviewers can no longer distinguish between someone who understands the problem and someone who is merely relaying an AI-generated solution.</p><p>Meta has already responded, replacing one of its two traditional coding rounds with a 60-minute AI-assisted session. Candidates are <em>encouraged</em> to use GPT-5, Claude, and Gemini. What’s actually being evaluated? Problem decomposition. Critical assessment of AI output. Architectural reasoning.</p><p><strong>Implementation is table stakes. Thinking is the differentiator.</strong></p><h3>System design is the new kingmaker, because AI can’t fake it.</h3><p>You can prompt an LLM to write a CDC pipeline. You can’t prompt it to sit in a 45-minute interview and navigate <em>“Design a real-time analytics platform for 50M daily active users”</em> while an interviewer probes your trade-off reasoning, challenges your assumptions, and asks why you chose Kafka over Kinesis for this specific use case.</p><p>System design exposes the <strong>depth</strong> behind your experience. It reveals whether you’ve operated at scale or just read about it.</p><p>For data engineering, this is the round that separates mid-level from senior. Interviewers want to see you reason through:</p><blockquote><strong><em>Ingestion</em></strong><em> — CDC vs full loads? What happens when data arrives late?</em></blockquote><blockquote><strong><em>Storage</em></strong><em> — Lakehouse vs warehouse? When does Iceberg beat Delta Lake?</em></blockquote><blockquote><strong><em>Reliability</em></strong><em> — How do you make a pipeline idempotent? What’s your DLQ strategy?</em></blockquote><blockquote><strong><em>Processing</em></strong><em> — Lambda vs Kappa? Batch-first or streaming-first? </em>Why?</blockquote><blockquote><strong><em>Modeling</em></strong><em> — Star schema or OBT? How do you handle SCDs at scale?</em></blockquote><blockquote><strong><em>Ops</em></strong><em> — What does monitoring look like? How do you detect drift? What triggers a backfill?</em></blockquote><p>None of these can be outsourced to an AI agent running in a background tab.</p><h3>The new data engineering interview loop looks like this:</h3><p><strong>SQL</strong> — Still present, but shifting toward optimization and debugging over puzzle-solving.</p><p><strong>System Design (where offers are won or lost)</strong> — A vague prompt, 45 minutes, and you drive. Requirements, architecture, trade-offs, failure modes, observability, all on you.</p><p><strong>Behavioral</strong> — Communication, collaboration, handling ambiguity.</p><p>Notice what’s shrinking? The pure coding round. Not because coding doesn’t matter — but because the <em>interview signal</em> from it has been permanently diluted by AI. System design, on the other hand, is more valuable than ever.</p><h3>Flip your prep ratio.</h3><p>If you’re spending 80% of your prep time on LeetCode and 20% on system design, <strong>you’ve got it backwards.</strong></p><p>The engineer who can design a fault-tolerant, cost-efficient, real-time data platform and articulate <em>why</em> behind every decision will beat the engineer who solves Medium-difficulty LeetCode in their sleep. Every single time.</p><p>The highest-leverage things you can study right now: distributed systems fundamentals, data pipeline patterns (CDC, idempotency, exactly-once, backfills), storage architecture (lakes, warehouses, lakehouses, table formats), stream processing internals, data modeling at scale, and observability.</p><p>And critically <strong>practice talking through designs out loud.</strong> The best candidates don’t just draw boxes. They narrate the data journey from source to consumer, explain every trade-off, and address failure modes before the interviewer asks.</p><h3>Want a head start?</h3><p>I created a <a href="https://youtu.be/auIupgKGNTg"><strong>Data Engineering System Design Crash Course</strong></a> on <a href="https://youtu.be/auIupgKGNTg">YouTube </a>covering everything from storage fundamentals and pipeline architecture to a complete interview framework for tackling any system design question with confidence.</p><p>If you’re interviewing at FAANG, a startup, or leveling up in your current role, this is the highest-leverage prep you can do right now.</p><p>Share this with a data engineer in your network who’s still grinding LeetCode. The game has changed.</p><p>If you enjoyed this breakdown and want deeper, real-world case studies, tradeoffs, and architecture patterns, my System Design Guide for Data Engineers goes far beyond the basics.</p><p>Check it out here — <a href="https://topmate.io/manjinder_brar">FAANG System Design</a></p><p><em>How are system design rounds showing up in your interview experience? Drop a comment — I’d love to hear it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87698c3a2e6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda vs Kappa Architecture]]></title>
            <link>https://medium.com/@manjindersingh_10145/lambda-vs-kappa-architecture-7d628d5c8cf2?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d628d5c8cf2</guid>
            <category><![CDATA[lambda-architecture]]></category>
            <category><![CDATA[kappa-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 19:22:20 GMT</pubDate>
            <atom:updated>2025-12-29T19:22:20.662Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Choose Your Stream Processing Blueprint Without Losing Your Mind</h3><p>If you spend enough time around data engineers, you will eventually run into the classic debate:</p><p><strong>Lambda Architecture or Kappa Architecture?</strong></p><p>This is the streaming world’s version of “tabs vs spaces.”<br>Everyone has an opinion, but not everyone has a clear explanation.</p><p>So let’s break it down the way a senior engineer would explain it to a newer teammate.<br>Simple language. Clear mental models. No jargon that requires a PhD.</p><p>By the end of this, you will know exactly when to pick which one and why.</p><h3>What Problem Are These Architectures Solving?</h3><p>Real-time systems have two basic needs:</p><ol><li>The ability to process events as they come in</li><li>The ability to reprocess historical data correctly</li></ol><p>Some companies only need one.<br>Most large companies need both.</p><p>Lambda and Kappa try to answer the same question with two different philosophies.</p><p><strong>Lambda Architecture: Two Paths, One Answer</strong></p><p>Lambda Architecture is the older, battle-tested model.<br>It splits your pipeline into two parallel worlds:</p><p><strong><em>1. The Batch Layer (The “truth” layer)</em></strong></p><p>This is your source of accuracy.<br>It processes large historical datasets, usually in daily or hourly batches.</p><p>Think:</p><p>• Spark jobs that rebuild your gold tables<br>• Historical recompute of metrics<br>• Heavy lifting that does not care about latency</p><p><strong><em>2. The Speed Layer (The “freshness” layer)</em></strong></p><p>This is your real-time stream.</p><p>Think:</p><p>• Fraud alerts<br>• Live metrics<br>• Sub minute updates</p><p>It produces fast but temporary results.</p><p><strong><em>3. The Serving Layer (The “final view”)</em></strong></p><p>Here you merge the two:</p><p>Speed layer gives freshness<br>Batch layer gives correctness</p><p>Together they create a single accurate output table.</p><p><strong><em>Why to Choose Lambda</em></strong></p><p><em>Strengths</em></p><p>• You can always reconstruct the truth from your batch layer<br>• Real-time layer can be fast and lightweight<br>• Works well when late and messy data is common<br>• Great for financial reporting, compliance, auditability</p><p><em>Weaknesses</em></p><p>• Two code paths<br>• Two transformation logics<br>• Two testing ecosystems<br>• Two places where bugs can hide<br>• Higher cognitive load for engineers<br>• More expensive to maintain</p><p>Lambda is powerful but not simple.<br>It is the “Swiss Army Knife with 42 tools” approach to data systems.</p><p><strong>Kappa Architecture: One Path To Rule Them All</strong></p><p>Kappa Architecture came later with a much simpler idea:</p><blockquote>Why maintain two pipelines when one can do everything?</blockquote><p>Here, everything is a stream.</p><p>The idea is simple</p><p>• All data goes through a log (usually Kafka)<br>• Real-time processing system handles both new and old data<br>• If you need to reprocess history, you replay the log</p><p>Instead of two worlds (batch and stream), you only have one.</p><p><strong>Result</strong></p><p>Same code<br>Same transformations<br>Same mental model<br>Same operational tools</p><p>The log becomes your “truth layer” and your “history.”</p><p><strong>Why Engineers Love Kappa</strong></p><p><em>Strengths</em></p><p>• A single codebase<br>• Simpler operational model<br>• Easy reprocessing by replaying topics<br>• Works beautifully with modern stream processors like Flink<br>• Perfect for constant high-volume event streams<br>• Naturally resilient to schema evolution</p><p><em>Weaknesses</em></p><p>• Requires strong log infrastructure<br>• Replay costs can be high if data is huge<br>• Not ideal for large historical batches<br>• Overkill for teams that do not need real-time processing</p><p>Kappa is elegant, but it assumes your world revolves around streaming.<br>Not every company is built like Netflix or Uber.</p><p><strong>Lambda vs Kappa: The Real Trade-Off</strong></p><p>When you strip everything down, the comparison is actually pretty straightforward.</p><p><strong>Lambda </strong>gives you a very safe and very correct system. It is great when you need reliable backfills and the confidence that you can always rebuild history exactly the way it should be.</p><p>The downside is that it creates more code, more moving parts, and more operational work. You are essentially maintaining two pipelines, which naturally increases complexity.</p><p><strong>Kappa</strong>, on the other hand, takes the opposite approach. You have one path, one codebase, and one mental model to maintain. It feels modern and clean, especially for systems that live and breathe real-time data.</p><p>But the simplicity comes with a caveat. You depend heavily on your log infrastructure and replays can become expensive if your workload is more batch-focused than streaming-focused.</p><p>So this is not about which architecture is “better.”<br>It is about which set of trade-offs you and your team are comfortable with.</p><p><strong>How Modern Teams Are Thinking Today</strong></p><p>A few years ago, Lambda was the default because that was the safest way to guarantee correctness at scale. But things have changed, and the industry is slowly shifting toward more stream-first thinking.</p><p>There are a few reasons for this.</p><p><em>1. Flink has changed the game</em></p><p>Flink has matured into a very capable engine. Stateful streaming, event time processing, watermarking, checkpointing.</p><p>It handles tasks that once required a separate batch layer, which naturally makes Kappa more appealing.</p><p><em>2. Logs have become the center of many systems</em></p><p>Kafka, Kinesis, Pulsar.<br>These are no longer exotic tools. Companies now treat logs as the backbone of their data platform. With long retention periods, the log essentially becomes your history store, which fits perfectly with the Kappa philosophy.</p><p><em>3. More workloads genuinely benefit from streaming</em></p><p>Recommendation systems, clickstream analytics, fraud detection, personalization. These systems rely on fresh data, not day-old aggregates, so a unified streaming model makes sense.</p><p><em>4. Infrastructure is cheaper and easier to manage</em></p><p>Cloud managed services have removed a lot of heavy lifting. You no longer need a dedicated team just to keep Kafka or Flink alive.</p><p>That said, Lambda is far from obsolete. There are situations where it is still the safer or more practical choice, especially when:</p><p>• The business prioritizes accuracy over freshness<br>• Backfills happen often<br>• Data volume is huge, and historical recompute is essential<br>• Compliance requires traceable and reproducible transformations<br>• The organization already thinks in warehouse-first patterns</p><p>Banks, enterprise analytics teams, and regulated industries still lean heavily on Lambda for these reasons.</p><p><strong>So, Which One Should You Pick?</strong></p><p>If your world revolves around real-time behavior and event-driven systems<br>things like streaming analytics, Kafka replays, ML features, or personalization then <strong><em>Kappa </em></strong>is probably the more natural fit.</p><p>If your world is dominated by batch workloads, lots of historical adjustments, financial accuracy, or strict governance then <strong><em>Lambda </em></strong>will feel more reliable and predictable.</p><p>And if you live somewhere in the middle, which is honestly where most companies end up, you might choose a hybrid: a streaming-forward design with a small batch layer for the edge cases where correctness absolutely matters.</p><p>It is important to say this clearly.<br>Most production systems are not purely Lambda or purely Kappa.<br>They borrow ideas from both, depending on the problem at hand.</p><p>If you enjoyed this breakdown and want deeper, real-world case studies, tradeoffs, and architecture patterns, my System Design Guide for Data Engineers goes far beyond the basics.</p><p>Check it out here —<a href="https://topmate.io/manjinder_brar"> FAANG System Design</a></p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Data Engineering, MLOps, and AWS/Azure Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d628d5c8cf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Myth of “Exactly-Once”: A Conversation on Why Your Pipeline Is Doubling Data]]></title>
            <link>https://medium.com/@manjindersingh_10145/the-myth-of-exactly-once-a-conversation-on-why-your-pipeline-is-doubling-data-7ee9d33b24f7?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee9d33b24f7</guid>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[upsert]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 06:16:47 GMT</pubDate>
            <atom:updated>2025-12-13T06:16:47.756Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Format: A transcript of a Code Review session between Sam (Junior Data Engineer) and Elena (Staff Data Engineer).</em></p><p><strong>Sam</strong>: “Hey Elena, can you approve this PR? I enabled processing.guarantee = exactly_once in the Spark config. Now we won’t have any duplicate payments in the warehouse!&quot;</p><p><strong>Elena</strong>: <em>Sighs and puts down her coffee.</em> “Sam, come sit down. We need to talk about the most dangerous lie in distributed systems.”</p><p><strong>Sam</strong>: “What lie?”</p><p><strong>Elena</strong>: “That ‘Exactly-Once’ actually exists.”</p><h3>The Trap: Delivery vs. Processing</h3><p><strong>Elena</strong>: “You turned on a setting in Spark Structured Streaming. What do you think that actually does?”</p><p><strong>Sam</strong>: “It guarantees that every record is processed one time. No duplicates.”</p><p><strong>Elena</strong>: “No. It guarantees that Spark will not <em>commit the offset</em> to Kafka until the batch is processed. It handles the Delivery mechanism. It does not handle the <strong>Side Effects.</strong>”</p><p><strong>Sam</strong>: “I’m lost. What is the difference?”</p><p><strong>Elena</strong>: “Imagine you are a pizza delivery guy. ‘Exactly-Once Delivery’ means you promise to ring my doorbell exactly one time. But what if I don’t answer? You ring again. (At-Least-Once). What if you ring, I open the door, take the pizza, but then the wind slams the door shut before you can get me to sign the receipt?”</p><p><strong>Sam</strong>: “I guess… you assume I didn’t get the pizza, so you go back to the store, get another one, and come back?”</p><p><strong>Elena</strong>: “Exactly. And now I have <strong>two pizzas</strong>. That is what happens to our database. If Spark writes the data to Postgres, but the network cuts out before Spark gets the ‘Success’ ACK from Postgres, Spark crashes. When it restarts, it replays the batch. It delivers the pizza again. Now we have double payments.”</p><h3>The Solution: Idempotency Keys</h3><p><strong>Sam</strong>: “Okay, that sounds bad. So how do we stop it? Do we use distributed transactions? Two-Phase Commit (2PC)?”</p><p><strong>Elena</strong>: “Please don’t. 2PC is the easiest way to make our system slow and brittle. If one node locks, everything locks. We want to solve this at the <strong>Application Layer</strong>, not the Network Layer. We need <strong>Idempotency</strong>.”</p><p><strong>Sam</strong>: “I’ve heard that word. Ideally, $f(f(x)) = f(x)$.”</p><p><strong>Elena</strong>: “Mathematically, yes. In Data Engineering, it means: <strong>We need a unique ID for every event.</strong>”</p><p><strong>Elena</strong>: “Look at your source data. When the payment event is generated, does it have a UUID?”</p><p><strong>Sam</strong>: “Yes, transaction_id.&quot;</p><p><strong>Elena</strong>: “Perfect. That is your <strong>Idempotency Key</strong>. Instead of blindly inserting data, we use that key to check if we have seen this pizza before.”</p><h3>The Implementation: The “Upsert” Pattern</h3><p><strong>Sam</strong>: “So I should do a SELECT to check if the ID exists, and if not, INSERT?&quot;</p><p><strong>Elena</strong>: “No! That creates a <strong>Race Condition.</strong> If two threads pick up the same event at the same time, they both SELECT, see nothing, and both INSERT. You still get duplicates.&quot;</p><p><strong>Elena</strong>: “You need the database to enforce it atomically. In SQL, we call this the <strong>Upsert </strong>(Update/Insert) or MERGE. Here, let me rewrite your code snippet.&quot;</p><p><em>Elena takes the keyboard.</em></p><p><em>The Anti-Pattern (What Sam wrote):</em></p><pre># ❌ This relies on Spark configuration magic<br>df.write \<br>  .format(&quot;jdbc&quot;) \<br>  .mode(&quot;append&quot;) \ # DANGER: This will create duplicates on retry<br>  .save()</pre><p><em>The Senior Pattern (What Elena wrote):</em></p><pre># ✅ This relies on Database Physics (Idempotency)<br>query = &quot;&quot;&quot;<br>INSERT INTO payments_warehouse (transaction_id, user_id, amount, timestamp)<br>VALUES (?, ?, ?, ?)<br>ON CONFLICT (transaction_id) <br>DO UPDATE SET <br>  amount = EXCLUDED.amount,<br>  timestamp = EXCLUDED.timestamp;<br>&quot;&quot;&quot;<br># Even if Spark retries this batch 50 times, the database state remains identical.</pre><h3>The “Zombie” Scenario</h3><p><strong>Sam</strong>: “Okay, I get the database part. But what about when we write to S3? We can’t do an ‘Upsert’ on a file in S3. It’s immutable.”</p><p><strong>Elena</strong>: “Sharp observation. This is the hardest part of the interview. If you are writing to a Data Lake (S3/Parquet), you have two options:”</p><ol><li>The Staging/Compaction Pattern: You write duplicates to a ‘Raw’ folder (At-Least-Once). Then, a separate scheduled job (Delta Lake or Hudi) reads the raw files, creates a distinct set based on IDs, and writes to the ‘Curated’ layer.</li><li>Write-Ahead-Log (WAL): You use a format like Delta Lake or Iceberg. They bring ACID transaction logs to S3. They handle the optimistic concurrency control for you.</li></ol><p><strong>Sam</strong>: “So, using Delta Lake is basically buying ‘Idempotency as a Service’?”</p><p><strong>Elena</strong>: “Pretty much. It shifts the complexity from your code to the storage format.”</p><h3>Summary: The Senior Engineer’s Checklist</h3><p><strong>Elena</strong>: “So, Sam, before you merge this PR, I want you to answer three questions:”</p><ol><li><strong><em>Identity</em></strong>: What column is the unique Idempotency Key?</li><li><strong><em>Destination</em></strong>: Does the destination support atomic Upserts (Postgres/Snowflake) or do we need a Delta/Hudi layer (S3)?</li><li><strong><em>Failure Mode</em></strong>: If the worker pulls the plug right after writing but before committing, what happens when the job restarts?</li></ol><p><strong>Sam</strong>: “If the job restarts, it tries to write the same transaction_id again. The database catches it, updates the existing row to the same value, and moves on. No duplicates.&quot;</p><p><strong>Elena</strong>: “Approved. Ship it.”</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>If you enjoyed this breakdown and want deeper, real-world case studies, tradeoffs, and architecture patterns, my System Design Guide for Data Engineers goes far beyond the basics.</p><p>Check it out here — <a href="https://topmate.io/manjinder_brar/1818102">FAANG System Design</a></p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Data Engineering, MLOps, and AWS/Azure Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee9d33b24f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Data Engineering System Design Interviews Feel Hard And 7 Concepts That Make Them 10x Easier]]></title>
            <link>https://medium.com/@manjindersingh_10145/why-data-engineering-system-design-interviews-feel-hard-and-7-concepts-that-make-them-10x-easier-d1081c98ff2d?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1081c98ff2d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 02:06:01 GMT</pubDate>
            <atom:updated>2025-12-29T19:09:27.125Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever walked into a D.E System Design interview, you know the feeling.</p><p>The interviewer looks at you, hands you a marker (or opens a shared doc), and asks a question so vague it feels like a trap: <em>“Design a data platform for a streaming service like Netflix.”</em></p><p>Suddenly, your mind goes blank. You start worrying about specific tools. Should I use Spark? Or Flink? Is Snowflake better here or BigQuery? What about Kafka?</p><p>Stop. ✋</p><p>The reason these interviews feel hard isn’t that you don’t know enough tools. It feels hard because you are trying to pick <em>solutions</em> before you understand the <em>problems</em>.</p><p>Junior engineers memorize tools. Senior engineers memorize trade-offs.</p><p>The secret to cracking the System Design interview isn’t memorizing the documentation for AWS or Azure. It is understanding the fundamental “physics” of data. Once you master a few core mental models, 70% of the interview questions answer themselves.</p><p>Here are the 7 core concepts that will take you from “guessing tools” to “designing architecture.”</p><h3>1. The Physics of Data: Volume &amp; Velocity</h3><p>Before you draw a single box on the whiteboard, you need to ask about the physics of the data. This is where Volume and Velocity come into play.</p><ul><li>Volume dictates your storage strategy. Are we talking Gigabytes (a standard Postgres DB is fine) or Petabytes (you need distributed storage like HDFS or S3)?</li><li>Velocity dictates your ingestion strategy.</li></ul><p><em>If data comes in as a gentle stream, a nightly batch job is sufficient.</em></p><p><em>If it comes in like a firehose (millions of events per second), you need a buffer. This is where you introduce the concept of Backpressure.</em></p><p><strong><em>Insight</em></strong>: Never design a system that assumes data flows at a constant rate. Always design for the spike. When velocity exceeds your compute power, you need a mechanism (like a message queue) to hold the data until your system can catch up. That is <strong>backpressure</strong>.</p><h3>2. Access Patterns: Read vs. Write</h3><p>A database optimized for writing data quickly is rarely the same database optimized for reading data quickly. This is the classic OLTP (Online Transaction Processing) vs. OLAP (Online Analytical Processing) debate, but let’s go deeper.</p><p>Ask your interviewer: <em>“Is this system write-heavy or read-heavy?”</em></p><ul><li><strong><em>Write-Heavy:</em></strong> Think IoT sensors or clickstream data. You need a storage engine optimized for high throughput append-only operations (like LSM trees found in Cassandra or RocksDB).</li><li><strong><em>Read-Heavy:</em></strong> Think of a user dashboard. You need heavy indexing and caching (like Redis or Elasticsearch).</li></ul><p><strong><em>Insight:</em></strong> Don’t try to find one tool to do both perfectly. It is often better to separate them using CQRS (Command Query Responsibility Segregation) — have one optimized path for writing and another optimized path for reading.</p><h3>3. The Truth Spectrum: ACID vs. BASE</h3><p>In university, we are taught that databases must be ACID (Atomicity, Consistency, Isolation, Durability). In the world of distributed data engineering, ACID is expensive. It is slow.</p><p>Sometimes, you need <strong>BASE </strong>(Basically Available, Soft state, Eventual consistency).</p><ul><li>Financial Data: Needs ACID. If I transfer money, the balance must update immediately.</li><li>Social Media Likes / Recommendation Feeds: Needs BASE. If I “like” a video, it is okay if my friend in another country doesn’t see that count update for 5 seconds.</li></ul><p><strong><em>Insight</em></strong>: The interview trick is recognizing that consistency is a spectrum, not a binary switch. Clarifying “how fresh” the data needs to be (Data Freshness Windows) allows you to choose the right architecture. Real-time is expensive; “near real-time” is manageable.</p><h3>4. The Evolution of Data: SCD vs. CDC</h3><p>Data rarely stays static. A user changes their address. A product changes its price. How do you capture that?</p><ul><li>SCD (Slowly Changing Dimensions): This is the classic warehousing approach. You track history by adding rows with start and end dates (Type 2). It is great for reporting but heavy to compute.</li><li>CDC (Change Data Capture): This is the modern, event-driven approach. instead of scanning a database to see what changed, you read the database transaction logs (binlogs) and stream every change as an event.</li></ul><p><strong><em>Insight</em></strong>: For modern system design, lean towards CDC. It decouples your operational database from your analytics warehouse and lowers the latency of your data pipelines.</p><h3>5. Traffic Management: Fan-In vs. Fan-Out</h3><p>How does data move between producers and consumers?</p><ul><li>Fan-In: Imagine thousands of IoT devices (producers) sending data to a single central processor. The risk here is a bottleneck. You need a “funnel” that can aggregate these connections efficiently.</li><li>Fan-Out: Imagine one event occurs (a user uploads a video), and five different services need to know about it (transcoding, notification, copyright check, recommendation update).</li></ul><p><strong><em>Insight</em></strong>: This is where Pub/Sub (Publish/Subscribe) systems like Kafka or Pulsar shine. They allow you to decouple the Fan-in from the Fan-out, ensuring that adding a new consumer doesn’t impact the producer.</p><h3>6. Reliability Killers: Hot Keys &amp; Skew</h3><p>This is the concept that separates the mid-level engineers from the staff engineers.</p><p>Distributed systems work by splitting data across “partitions.” Ideally, data is spread evenly. But what if you are processing tweets, and you partition by user_id?</p><p>Justin Bieber’s partition will explode, while the partition for “User_123” sits idle. This is a Hot Key problem (or Data Skew). It causes one node in your cluster to crash while others are bored, bringing down the whole system.</p><p><strong><em>Insight</em></strong>: Always ask, <em>“Is the data distribution uniform?”</em> If not, propose strategies like “salting” keys (adding a random suffix to spread the hot key across multiple partitions) to smooth out the load.</p><h3>7. Architecture Anatomy: Control Plane vs. Data Plane</h3><p>Finally, you must distinguish between the brain and the muscle.</p><ul><li>Control Plane: The system that decides <em>what</em> to do. (e.g., The Airflow Scheduler, the Kubernetes Master node).</li><li>Data Plane: The system that actually <em>does</em> the heavy lifting. (e.g., The Spark Worker, the EC2 instance).</li></ul><p><strong><em>Insight</em></strong>: Never mix these. If your Control Plane goes down, your existing jobs should ideally keep running (or at least, the failure of a heavy data job shouldn’t crash your scheduler). Designing for isolation between these two planes ensures your platform is robust.</p><h3>Summary</h3><p>When you look at a system design question through the lens of tools (Spark, Kafka, Redis), the possibilities are overwhelming.</p><p>But when you look at it through these mental models, the picture clears up:</p><ol><li>Volume/Velocity: Tells you if you need batch or streaming.</li><li>Read/Write: Tells you your database type.</li><li>ACID/BASE: Tells you your consistency model.</li><li>SCD/CDC: Tells you how to handle updates.</li><li>Fan-in/Out: Tells you your messaging architecture.</li><li>Hot Keys: Tells you your partitioning strategy.</li><li>Control/Data Plane: Tells you your reliability structure.</li></ol><p>Master these 7 concepts, and you won’t just pass the interview, you will actually enjoy the conversation</p><p>If you enjoyed this breakdown and want deeper, real-world case studies, tradeoffs, and architecture patterns, my System Design Guide for Data Engineers goes far beyond the basics.</p><p>Check it out here — <a href="https://topmate.io/manjinder_brar">FAANG System Design</a></p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Data Engineering, MLOps, and AWS/Azure Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1081c98ff2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Robust Data Pipelines: Idempotency, Replays & Backfills Explained]]></title>
            <link>https://medium.com/@manjindersingh_10145/designing-robust-data-pipelines-idempotency-replays-backfills-explained-640c9920f7b9?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/640c9920f7b9</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 13:42:06 GMT</pubDate>
            <atom:updated>2025-11-25T13:42:06.123Z</atom:updated>
            <content:encoded><![CDATA[<p>If you work in data engineering long enough, you learn a simple truth:</p><p><strong>Pipelines don’t break when everything is normal.<br>They break when you need them the most.</strong></p><p>A surge in traffic.<br>A silent schema change.<br>A late-arriving file.<br>A job that stalls at 2 AM.</p><p>This is where the difference between a “working pipeline” and a <strong>resilient pipeline</strong> becomes painfully obvious.</p><p>Let’s talk about the reliability patterns every senior data engineer leans on but very few people explain clearly:</p><p>• Idempotent writes<br>• Replay-safe designs<br>• Backfills that don’t destroy dashboards<br>• Watermarking and controlled recovery<br>• Observability that lets you sleep at night</p><p>No jargon. No fluff. Just the patterns that actually keep systems alive.</p><p>𝟭. 𝗜𝗱𝗲𝗺𝗽𝗼𝘁𝗲𝗻𝗰𝘆: 𝗬𝗼𝘂𝗿 𝗦𝗮𝗳𝗲𝘁𝘆 𝗡𝗲𝘁 𝗳𝗼𝗿 𝗪𝗵𝗲𝗻 𝗧𝗵𝗶𝗻𝗴𝘀 𝗚𝗼 𝗪𝗿𝗼𝗻𝗴</p><p>Retries happen. Jobs fail. Clusters restart.<br>A pipeline without idempotency is one bad run away from a corrupted table.</p><p>Idempotency simply means:</p><blockquote>Running the same job multiple times gives the same final result.</blockquote><p>The easiest way to achieve this?</p><p><strong>Partition → Replace → Move On</strong></p><p>Store data in time-based partitions:</p><pre>/silver/events/event_date=2025-01-03/</pre><p>Then, whenever you process a partition:</p><p>• Wipe it<br> • Recompute it<br> • Write it again</p><p>Simple. Predictable. Safe.</p><p>No duplicates. No partial writes.<br>Even if the job retries 5 times, the table stays clean.</p><p><strong>MERGE-based idempotency</strong></p><p>Whenever you have keys:</p><pre>order_id  <br>trip_id  <br>transaction_id</pre><p>Use an UPSERT/MERGE:</p><pre>MERGE INTO silver.orders AS t<br>USING staging.orders AS s<br>ON s.order_id = t.order_id<br>WHEN MATCHED THEN UPDATE ...<br>WHEN NOT MATCHED THEN INSERT ...</pre><p>If an upstream system sends the same event twice?<br>You update once. You insert once. Done.</p><p>This is how modern lakehouse formats (Delta, Iceberg, Hudi) keep pipelines consistent despite chaos.</p><p><strong>2. Delivery Semantics: Understanding What You’re Actually Promising</strong></p><p>Everyone says they want <em>exactly-once processing.</em><br>Almost nobody actually needs it.</p><p>Here’s the real breakdown:</p><p><strong>At-Least-Once</strong></p><p>• You may see duplicates<br> • But you never lose data<br> • Perfectly fine if downstream is idempotent</p><p>This is the default for almost every streaming system on earth.</p><p><strong>At-Most-Once</strong></p><p>• No retries<br>• No duplicates<br>• BUT you may lose data</p><p>Usable for non-critical logs. Nothing else.</p><p><strong>Exactly-Once</strong></p><p>• Hard<br>• Expensive<br>• Often misunderstood<br>• Requires carefully designed sinks and state management</p><p>If your business is not running payment systems or compliance pipelines? You probably don’t need this level of pain.</p><p>Senior engineers focus on<em> designing idempotent downstream systems</em>, not magical “exactly-once” guarantees.</p><p><strong>3. Replays: The Real Test of Pipeline Design</strong></p><p>A healthy pipeline isn’t the one that never fails; it’s the one you can re-run safely.</p><p><strong>Replay by Partition</strong></p><p>If your raw layer is structured like:</p><pre>/bronze/events/year=2025/month=01/day=02/</pre><p>Then reprocessing becomes trivial:</p><blockquote>“Recompute Jan 2. Leave everything else untouched.”</blockquote><p>This is why time partitioning exists.<br>Not for performance.<br>For 𝘳𝘦𝘤𝘰𝘷𝘦𝘳𝘢𝘣𝘪𝘭𝘪𝘵𝘺.</p><p><strong>Incremental + Snapshot Hybrid</strong></p><p>A useful trick for high-traffic systems:</p><p>• Keep daily snapshots for correctness<br>• Keep incremental deltas for efficiency</p><p>Snapshots give you truth.<br>Deltas give you speed.<br>Combined, they give you the ability to rebuild any table at any point in time.</p><p><strong>Watermarking: Don’t Reprocess Forever</strong></p><p>Events can arrive late.<br>Some events arrive 𝘷𝘦𝘳𝘺 late.</p><p>A watermark defines a window:</p><blockquote>“I will process data up to 48 hours old.<br> After that, treat it as too late.”</blockquote><p>This prevents runaway reprocessing and unpredictable downstream metrics.</p><p><strong>4. Backfills: The Part That Terrifies Most Teams</strong></p><p>Backfills look innocent:</p><blockquote>“We found a bug in the transformation logic.<br> Can you reprocess last month?”</blockquote><p>And suddenly dashboards break, metrics double, and analysts panic.</p><p>Here’s how to do it safely.</p><p><strong>a) Version your tables</strong></p><p>Never backfill directly into a production table:</p><pre>events</pre><p>Instead, generate:</p><pre>events_v2</pre><p>Then validate:</p><p>• Row counts<br>• Key counts<br>• Aggregated metrics<br>• Schema alignment</p><p>Only after validation do you 𝘴𝘸𝘪𝘵𝘤𝘩 𝘤𝘰𝘯𝘴𝘶𝘮𝘦𝘳𝘴.</p><p><strong>b) Use views as the interface</strong></p><p>BI tools point to:</p><pre>analytics.events</pre><p>And the view points to the correct version:</p><pre>CREATE OR REPLACE VIEW analytics.events AS<br>SELECT * FROM events_v2;</pre><p>Instant swap. Zero downtime.<br>If something goes wrong? Roll back the view.</p><p><strong>c) Rebuild bottom-up</strong></p><p>Backfills should always follow the data flow:</p><p><em>raw → bronze → silver → gold</em></p><p>Never edit gold directly.<br>You’ll break lineage, tracking, and trust.</p><p><strong>d) Backfill in batches</strong></p><p>Trying to rebuild a year’s worth of data in one shot is a great way to ruin your weekend.</p><p>Instead:</p><p>• Backfill 3 days<br>• Validate<br>• Backfill a week<br>• Validate<br>• Backfill a month<br>• Validate</p><p>Controlled. Predictable. Safe.</p><p><strong>5. Observability: The Difference Between “It Works” and “We Trust It”</strong></p><p>A pipeline doesn’t just need to run.<br>It needs to <em>prove </em>it’s running correctly.</p><p>Here’s what real observability looks like:</p><p><strong>Row count checks</strong></p><p>Is your input count off by 5%?<br>Something’s wrong.</p><p><strong>Null ratio checks</strong></p><p>If a field has been 0.2% null for 18 months<br>and today it’s 7%</p><p>→ Alert.</p><p><strong>Freshness checks</strong></p><p>If today’s data hasn’t landed yet<br>you should know before the CFO does.</p><p><strong>Schema evolution alerts</strong></p><p>Silent upstream changes are one of the most common causes of bad data.</p><p><strong>DLQs (Dead Letter Queues)</strong></p><p>Invalid records shouldn’t break your pipeline.<br>But they also shouldn’t disappear quietly.</p><p><strong>SLA dashboards</strong></p><p>Monitor:</p><p>• Lag<br>• Processing time<br>• Backlog<br>• Throughput</p><p>When something drifts, you want to know <em>before </em>an incident.</p><p><strong>6. A Real Example: “We Can Reprocess the Last 7 Days Anytime”</strong></p><p>A pattern used by many high-scale teams:</p><p><strong>• Raw Layer (immutable)</strong><br> Nothing is ever modified. Perfect for replays.</p><p>•<strong> Bronze Layer (overwrite by date)</strong><br> Every re-run wipes the date partition and rewrites it.</p><p><strong>• Silver Layer (idempotent merges)</strong><br> MERGE handles duplicates and late data safely.</p><p><strong>• Gold Layer (pure transformations)</strong><br> Always derived from silver. Never manually edited.</p><p><strong>• Replay logic</strong><br> Drop silver for the last 7 days<br> Rebuild from bronze<br> Recompute gold<br> Swap view to new version<br> Validate<br> Done</p><p>This is how you build pipelines that are reliable, repeatable, and boring in the best way possible.</p><p><strong>Final Thoughts</strong></p><p>Most data engineering problems are not about designing the <em>perfect </em>pipeline.</p><p>They’re about designing a pipeline that:</p><p>• Can fail safely<br>• Can be re-run safely<br>• Can be debugged easily<br>• Can be trusted by the business<br>• Can survive schema changes<br>• Can handle late data<br>• Can backfill history without panic</p><p>Reliability is a skill.<br>Idempotency, replays, and backfills: these are your tools.</p><p>And once you master these, system design interviews stop being a maze and start becoming a conversation.</p><p>If you enjoyed this breakdown and want deeper, real-world case studies, tradeoffs, and architecture patterns, my System Design Guide for Data Engineers goes far beyond the basics.</p><p>Check it out here — <a href="https://topmate.io/manjinder_brar/1818102">FAANG System Design</a></p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Data Engineering, MLOps, and AWS/Azure Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640c9920f7b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Model Reliability in the Real World: A Guide to TensorFlow Data Validation (TFDV)]]></title>
            <link>https://medium.com/@manjindersingh_10145/ensuring-model-reliability-in-the-real-world-a-guide-to-tensorflow-data-validation-tfdv-262a388f898b?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/262a388f898b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tfx]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 18:36:05 GMT</pubDate>
            <atom:updated>2023-12-27T18:36:05.657Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a machine-learning solution in a Jupyter Notebook is one thing, but deploying it in the real world is another. In real-time applications, after you’ve trained your model with a specific dataset, it’s essential to ensure that the new data streaming in for evaluation matches the schema of your training data. This means monitoring data types, ensuring numerical values are within the expected range, and handling new categories in your data that weren’t in the training set. TensorFlow Data Validation <strong><em>(</em></strong><a href="https://www.tensorflow.org/tfx/tutorials/data_validation/tfdv_basic"><strong><em>TFDV</em></strong></a><strong><em>)</em></strong> offers a robust solution to these challenges. As an open-source Python package from <a href="https://www.tensorflow.org/tfx"><strong><em>TensorFlow Extended (TFX)</em></strong></a>, TFDV simplifies the task of making sure your evaluation data stays consistent with your training set, ensuring your model works effectively in real-world scenarios</p><p>Let us first look at its Workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_0r-9vMJry3FrAr--W3OQ.png" /><figcaption>Credits — DeepLearning.AI</figcaption></figure><p>As you can see, TFDV enables you to calculate descriptive statistics for your training data and create a schema. This schema can be used to check new datasets (like the serving dataset received from your customers) for discrepancies, allowing you to identify and correct anomalies. By doing this, you can safeguard against various types of data skew. Consequently, you can be assured that your model is either training on or making predictions with, data that aligns with the anticipated feature types and distributions.</p><p>Let us understand it using a Healthcare Dataset available on <a href="https://www.kaggle.com/datasets/prasad22/healthcare-dataset/data">Kaggle</a>.</p><p><strong>Step 1: Let us first import the required libraries</strong></p><pre>import tensorflow as tf<br>import tensorflow_data_validation as tfdv<br>import pandas as pd<br><br>from sklearn.model_selection import train_test_split<br>from tensorflow_metadata.proto.v0 import schema_pb2</pre><blockquote>Note: If you don’t have tfx package installed, you can install it using</blockquote><pre>pip install -U tfx</pre><p><strong>Step 2: Loading and Splitting the Dataset</strong></p><pre>df = pd.read_csv(&quot;healthcare_dataset.csv&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJ_xv3gtVS_Ksl-PJuv9Mg.png" /></figure><pre>train_df, eval_df = train_test_split(df, test_size=0.2, shuffle=False)</pre><p>Our chosen dataset is free from anomalies and data type inconsistencies. However, in the real world, a Data Professional often spends about 90% of their time addressing these issues. To better understand how to manage such irregularities, let’s intentionally introduce some inconsistent data at the end of our Evaluation Dataset. We’re focusing on the Evaluation data because our schema will be built using the training set. It’s important to ensure that any new data, in this case, the evaluation data, matches the schema of the dataset that our model was originally trained on. This exercise will help us learn how to maintain consistency in real-world scenarios.</p><p><strong>Step 3: Adding Inconsistent Rows</strong></p><pre># Function to add extra rows<br>def add_extra_rows(df):<br>    rows = [<br>        {<br>            &#39;Name&#39;:&#39;Money Brar&#39;,<br>            &#39;Age&#39;:103, # Unrealistic Age value<br>            &#39;Gender&#39;:&#39;Male&#39;,<br>            &#39;Blood Type&#39;:&#39;A+&#39;,<br>            &#39;Medical Condition&#39;:&#39;Cancer&#39;,<br>            &#39;Date of Admission&#39;:&#39;2023-06-23&#39;,<br>            &#39;Doctor&#39;:&#39;Ethan Anderson&#39;,<br>            &#39;Hospital&#39;:&#39;Evans-Bennett&#39;,<br>            &#39;Insurance Provider&#39;:&#39;Cigna&#39;,<br>            &#39;Billing Amount&#39;:44610.623562,<br>            &#39;Room Number&#39;:404,<br>            &#39;Admission Type&#39;:&#39;Urgent&#39;,<br>            &#39;Discharge Date&#39;:&#39;2023-07-03&#39;,<br>            &#39;Medication&#39;:&#39;Lipitor&#39;,<br>            &#39;Test Results&#39;:&#39;Abnormal&#39;<br>        },<br><br>        {<br>            &#39;Name&#39;:&#39;Chris K.&#39;,<br>            &#39;Age&#39;:69,<br>            &#39;Gender&#39;:&#39;Male&#39;,<br>            &#39;Blood Type&#39;:&#39;P&#39;, # Unrealistic Blood Type<br>            &#39;Medical Condition&#39;:&#39;Cancer&#39;,<br>            &#39;Date of Admission&#39;:&#39;2023-06-23&#39;,<br>            &#39;Doctor&#39;:&#39;Ethan Anderson&#39;,<br>            &#39;Hospital&#39;:&#39;Evans-Bennett&#39;,<br>            &#39;Insurance Provider&#39;:&#39;Cigna&#39;,<br>            &#39;Billing Amount&#39;:42640.6235,<br>            &#39;Room Number&#39;:147,<br>            &#39;Admission Type&#39;:&#39;Urgent&#39;,<br>            &#39;Discharge Date&#39;:&#39;2023-07-03&#39;,<br>            &#39;Medication&#39;:&#39;Lipitor&#39;,<br>            &#39;Test Results&#39;:&#39;Abnormal&#39;<br>        },<br><br>        {<br>            &#39;Name&#39;:&#39;Lucas Brown&#39;,<br>            &#39;Age&#39;:73, <br>            &#39;Gender&#39;:&#39;Male&#39;,<br>            &#39;Blood Type&#39;:&#39;A+&#39;,<br>            &#39;Medical Condition&#39;:&#39;Cancer&#39;,<br>            &#39;Date of Admission&#39;:&#39;2023-06-23&#39;,<br>            &#39;Doctor&#39;:&#39;Ethan Anderson&#39;,<br>            &#39;Hospital&#39;:&#39;Evans-Bennett&#39;,<br>            &#39;Insurance Provider&#39;:&#39;Cigna&#39;,<br>            &#39;Billing Amount&#39;:12.34, # Exceptionally small Billing amount <br>            &#39;Room Number&#39;:404,<br>            &#39;Admission Type&#39;:&#39;Urgent&#39;,<br>            &#39;Discharge Date&#39;:&#39;2023-07-03&#39;,<br>            &#39;Medication&#39;:&#39;Lipitor&#39;,<br>            &#39;Test Results&#39;:&#39;Normal&#39;<br>        }<br>    ]<br>    <br>    df = df.append(rows, ignore_index=True)<br>    <br>    return df<br><br>eval_df = add_extra_rows(eval_df)</pre><p>As you can see we are adding three kinds of consistencies in our data:</p><ol><li>Adding a patient with age = 103 seems unrealistic.</li><li>Adding a patient with a Blood Type ‘P’ which scientifically does not exist.</li><li>Adding a Billing amount of a patient as 12.34 which is much less than other data.</li></ol><p><strong>Step 4: Generating Training Dataset Statistics</strong></p><p>We will now compute and visualize the statistics of our training dataset. TFDV accepts three input formats: TensorFlow’s TFRecord, Pandas Dataframe, and CSV file. In this article, we will feed in the Pandas Dataframes we generated from the train-test split.</p><p>We can compute our dataset statistics by using the <a href="https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/generate_statistics_from_dataframe">generate_statistics_from_dataframe()</a> method. Under the hood, it distributes the analysis via <a href="https://beam.apache.org/">Apache Beam</a> which allows it to scale over large datasets.</p><p>The results returned by this step for numerical and categorical data are summarized in this table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*4sGIQ2FSH0jz8ekPk8xvig.png" /></figure><pre># Generate training dataset statistics<br>train_stats = tfdv.generate_statistics_from_dataframe(train_df)</pre><p><strong>Step 5: Visualizing the Statistics</strong></p><p>Once we’ve generated the statistics, we can easily visualize our results with the <a href="https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/visualize_statistics">visualize_statistics()</a> method. This shows a <a href="https://pair-code.github.io/facets/">Facets interface</a> and is very useful to spot if you have a high amount of missing data or a high standard deviation.</p><pre># Visualize training dataset statistics<br>tfdv.visualize_statistics(train_stats)</pre><p>Let us look at the numerical feature statistics</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK888qCilpS2JFa8DgeVRw.png" /></figure><p>We can see that:</p><ol><li>There is no missing value</li><li>Descriptive Measures of different numerical features.</li><li>Almost Equal Distribution of data</li></ol><p>Let us now look at the Categorical Features of Statistics</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*XIym5mPFr58-n6s5-2f0fQ.png" /></figure><p>We can see</p><ol><li>There is no missing value present.</li><li>Number of unique categories for every feature eg- Gender has 2</li></ol><p>I would say play around with these facets and explore different dimensions of it. In the real world, spending a good amount of time on understanding this can show significant improvement in model building.</p><p><strong>Step 6: Inferring Data Schema</strong></p><p>This step involves creating a schema for your training dataset. Essentially, a schema defines the basic attributes of your data, like the types of data in each column and the expected range of values. This schema, built on a reference dataset, can then be applied to validate other incoming datasets.</p><p>Using the statistics you’ve computed, TensorFlow Data Validation (TFDV) helps you automatically generate a preliminary schema through its <a href="https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/infer_schema">infer_schema()</a> function. This function produces a Schema protocol buffer that encapsulates the results. As outlined in Section 3.3 of the <a href="http://stevenwhang.com/tfx_paper.pdf">TFX paper</a> , the schema inference results include:</p><ul><li>The anticipated type for each feature.</li><li>The required presence of each feature is defined by a minimum count and the fraction of examples that need to include the feature.</li><li>The expected number of times a feature appears in each example, specifying the minimum and maximum count.</li><li>The expected range or set of values for each feature, whether it’s a specific set of values for a string feature or a value range for an integer feature.</li></ul><pre># Infer schema from the computed statistics.<br>schema = tfdv.infer_schema(statistics=train_stats)<br><br># Display the inferred schema<br>tfdv.display_schema(schema)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*FzjzL-LiUuBE4fvtDKSyQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVQZmB_1lyxqC2EcmLkWfw.png" /></figure><p><strong>Step 7: Generate Evaluation Dataset Statistic</strong></p><p>Now let us similarly create a Dataset Statistic for Evaluation data. We will then compare this with Training Statistics to see if there is any inconsistency/anomaly.</p><pre># Generate evaluation dataset statistics<br>eval_stats = tfdv.generate_statistics_from_dataframe(eval_df)</pre><p><strong>Step 8: Visualize evaluation dataset statistics</strong></p><p>TFDV allows you to generate both the training and evaluation dataset statistics side-by-side. You can use the <a href="https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/visualize_statistics">visualize_statistics()</a> function and pass additional parameters to overlay the statistics from both datasets (referenced as left-hand side and right-hand side statistics). Let&#39;s see what these parameters are:</p><ul><li>lhs_statistics: Required parameter. Expects an instance of DatasetFeatureStatisticsList.</li><li>rhs_statistics: Expects an instance of DatasetFeatureStatisticsList to compare with lhs_statistics.</li><li>lhs_name: Name of the lhs_statistics dataset.</li><li>rhs_name: Name of the rhs_statistics dataset.</li></ul><pre># Compare training with evaluation<br>tfdv.visualize_statistics(<br>    lhs_statistics=eval_stats, <br>    rhs_statistics=train_stats, <br>    lhs_name=&#39;EVAL_DATASET&#39;, <br>    rhs_name=&#39;TRAIN_DATASET&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVZ6sJQlyoQlSfI1a7B14Q.png" /></figure><p>As you can see, the max-age in the training dataset was 85, but for evaluation, it is 103. Similarly, the minimum billing amount in the Training an Evaluation dataset is significantly different.</p><p>You can now drop this data to make it clean. (In the real world, since we have to build pipelines, we will be dealing with these anomalies differently which I will discuss in some other article).</p><pre># filter the age range<br>eval_df = eval_df[eval_df[&#39;Age&#39;] &lt; 85]<br>eval_df = eval_df[eval_df[&#39;Billing Amount&#39;] &gt; 1000]<br><br># drop missing values<br>eval_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*DdP2O5ePdwbogtmCkuBC0A.png" /></figure><p>Similarly in Blood Type, we can see that the Train set has 8 categories whereas the Eval set has 9. We can see that this is an anomaly. Let us more clearly see which is that 9th category.</p><pre># Check evaluation data for errors by validating the evaluation dataset statistics using the reference schema<br>anomalies =  tfdv.validate_statistics(statistics=eval_stats, schema=schema)<br><br># Visualize anomalies<br>tfdv.display_anomalies(anomalies)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*GZsUzILGy6iaPdPTNQRm3Q.png" /></figure><p>Oh right. We added a new Blood type “P” which does not exist. The schema tells us that there is one category “P” which is present in less than 1% of the observations.</p><blockquote>NOTE: What you decide to do about the anomalies depend on your domain knowledge of the data. If an anomaly indicates a data error, then the underlying data should be fixed. Otherwise, you can update the schema to include the values in the evaluation dataset.</blockquote><p><strong>Step 9: Fixing Anomalies in the Schema</strong></p><p>What if there actually existed a category “P” but was somehow not present in your train dataset and you don’t want it to be an anomaly? What if you want to manually add it into your training schema? You can do this simply using the below command:</p><pre>blood_type_domain = tfdv.get_domain(schema, &#39;Blood Type&#39;)<br>race_domain.value.append(&#39;P&#39;)</pre><p>In addition, you can also restrict the range of a numerical feature. This will let you know of invalid values without having to inspect it visually (e.g. the invalid age values earlier).</p><pre># Restrict the range of the `age` feature<br>tfdv.set_domain(schema, &#39;Age&#39;, schema_pb2.IntDomain(name=&#39;Age&#39;, min=17, max=90))</pre><blockquote>Note: The below command is not suitable for our use cases , but just so you know.</blockquote><pre># Relax the minimum fraction of values that must come from the domain for the feature `native-country`<br>country_feature = tfdv.get_feature(schema, &#39;native-country&#39;)<br>country_feature.distribution_constraints.min_domain_mass = 0.9</pre><p><strong>Step 10: Let us check for anomalies</strong></p><p>With these revisions, running the validation should now show no anomalies.</p><pre># Validate eval stats after updating the schema <br>updated_anomalies = tfdv.validate_statistics(eval_stats, schema)<br>tfdv.display_anomalies(updated_anomalies)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*6u5IrJ8SC4FySkqE8-BAlw.png" /></figure><p>I hope this article has illuminated the impressive capabilities of TensorFlow Data Validation (TFDV) for you. Through our exercise, we’ve explored how TFDV can be effectively utilized in a machine learning project, offering an invaluable tool for handling data. Its ability to scale the computation of statistics across datasets is a significant advantage. With TFDV, not only can you infer the schema of a dataset, but you also have the flexibility to refine it using your own domain knowledge. Moreover, TFDV empowers you to identify and understand discrepancies between training and evaluation datasets by providing tools for visual statistics comparison and anomaly detection. Additionally, it offers the capability to delve into specific segments of your dataset for a more targeted analysis. TFDV is truly an essential asset in ensuring the integrity and effectiveness of your machine learning models.</p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Machine Learning, MLOps, and AWS Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262a388f898b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis with BERT using Huggingface]]></title>
            <link>https://medium.com/@manjindersingh_10145/sentiment-analysis-with-bert-using-huggingface-88e99deeec9a?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e99deeec9a</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 10:55:02 GMT</pubDate>
            <atom:updated>2023-11-19T10:55:02.630Z</atom:updated>
            <content:encoded><![CDATA[<p>Sentiment Analysis, a pivotal aspect of natural language processing (NLP), has revolutionized the way we interpret and analyze human emotions in textual data. This article delves into the intricate world of Sentiment Analysis through the lens of BERT (Bidirectional Encoder Representations from Transformers), a state-of-the-art model introduced by Google. Leveraging the power of HuggingFace, a popular library in the NLP community, we will explore how BERT can be effectively utilized to decode the nuances of sentiment in various texts.</p><p>In this article, my main emphasis will be on implementation, so I won’t delve deeply into BERT’s architecture. For those curious about the finer details, I recommend checking out this excellent <a href="https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270">article</a> for more information.</p><p>Hugging Face provides two main libraries, <a href="https://github.com/huggingface/transformers">transformers</a> for models and <a href="https://github.com/huggingface/datasets">datasets</a> for datasets. You can install them using <a href="https://pypi.org/project/pip/"><em>pip</em></a> as usual.</p><p><strong>Step 1: Installing the Hugging Face Libraries</strong></p><pre>!pip install transformers datasets</pre><p><strong>Step 2: Importing the necessary Libraries</strong></p><pre>import tensorflow as tf### models<br>import numpy as np### math computations<br>import matplotlib.pyplot as plt### plotting bar chart<br>import sklearn### machine learning library<br>import cv2## image processing<br>from sklearn.metrics import confusion_matrix, roc_curve### metrics<br>import seaborn as sns### visualizations<br>import datetime # For Datetime Functions<br>import pathlib # handling files and paths on your operating system<br>import io # dealing with various types of I/O<br>import os <br>import re # for Regular Expressions<br>import string<br>import time<br>from numpy import random<br>import gensim.downloader as api # to download pre-trained model datasets and word embeddings from Gensim&#39;s repository<br>from PIL import Image # manipulating images, resizing, cropping, adding text<br>import tensorflow_datasets as tfds # Tf Datasets<br>import tensorflow_probability as tfp<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.layers import Layer<br>from tensorflow.keras.layers import (Dense,Flatten,InputLayer,BatchNormalization,<br>                                     Dropout,Input,LayerNormalization)<br>from tensorflow.keras.losses import BinaryCrossentropy,CategoricalCrossentropy,<br>                                    SparseCategoricalCrossentropy)<br>from tensorflow.keras.metrics import Accuracy,TopKCategoricalAccuracy,<br>                                 CategoricalAccuracy, SparseCategoricalAccuracy)<br>from tensorflow.keras.optimizers import Adam<br>from google.colab import drive<br>from google.colab import files<br>from datasets import load_dataset<br>from transformers import (BertTokenizerFast,TFBertTokenizer,BertTokenizer,RobertaTokenizerFast,<br>                          DataCollatorWithPadding,TFRobertaForSequenceClassification,TFBertForSequenceClassification,<br>                          TFBertModel,create_optimizer)</pre><p>Let’s define a Batch Size. It determines how many data samples are processed in each iteration (or batch) during training. It is a hyperparameter that you can adjust based on your specific problem</p><pre>BATCH_SIZE=8</pre><p><strong>Step 3: Data Preparation</strong></p><pre>dataset_id=&#39;imdb&#39;<br>dataset = load_dataset(dataset_id) # load_dataset is a function of datasets library of HuggingFace</pre><p>Let us now look at our dataset.</p><pre>dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*XcttNYXiUu6GVT6EORrxHQ.png" /></figure><p>We can see that train_dataset, test_dataset, and validation_dataset are dictionaries containing the respective dataset splits. We can access individual data samples and their associated features using these splits.</p><p>Let us look at one sample row.</p><pre>import pandas as pd<br>pd.DataFrame({&#39;text&#39;:dataset[&#39;train&#39;][:5][&#39;text&#39;],&#39;label&#39;:dataset[&#39;train&#39;][:5][&#39;label&#39;]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*xYuHq7siMhd1IdDKwyQCXg.png" /></figure><ul><li>Label 0: Indicates a negative sentiment. It means that the movie review expresses a negative opinion or review about the movie.</li><li>Label 1: Indicates a positive sentiment. It means that the movie review expresses a positive opinion or review about the movie.</li></ul><p><strong>Step 4: Loading a pre-trained BERT Model</strong></p><pre>model_id=&quot;bert-base-uncased&quot;<br>tokenizer = BertTokenizerFast.from_pretrained(model_id)</pre><p>model_id=&quot;bert-base-uncased&quot;: &quot;bert-base-uncased&quot; refers to a specific pre-trained BERT model that has been trained on a large corpus of text. The &quot;uncased&quot; part indicates that this model is case-insensitive, meaning it treats uppercase and lowercase letters as the same.</p><p>tokenizer = BertTokenizerFast.from_pretrained(model_id): This line creates a tokenizer object for the specified pre-trained BERT model. tokenizer object is ready to tokenize text using the rules and vocabulary of the &quot;bert-base-uncased&quot;</p><p>Let’s try checking our “tokenizer” object on some random text and analyze the tokenized output.</p><pre>test_input_1=&#39;The Weather of Today is Gréat! zwp&#39;<br>test_input_2=&#39;How are you doing?&#39;<br>inputs=[test_input_1,test_input_2]<br><br>tokenizer.tokenize(inputs)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*OSYzOgU2SqPoaUrvYzCdbw.png" /></figure><blockquote>Note: The zwp word was broken into alphabets and a double hash(##) was added in front of w and p. This technique used by BERT is known as S<strong>ubword tokenization . </strong>The “##” symbol is used to indicate that a token is part of a larger word.</blockquote><p>Let us now see how the tokenizer tokenizes the inputs into a vector representation.</p><pre>output=tokenizer(inputs,padding=True,truncation=True,max_length=128)<br>print(output)</pre><pre>{&#39;input_ids&#39;: [[101, 1996, 4633, 1997, 2651, 2003, 2307, 999, 1062, 2860, 2361, 102], [101, 2129, 2024, 2017, 2725, 1029, 102, 0, 0, 0, 0, 0]], &#39;token_type_ids&#39;: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], &#39;attention_mask&#39;: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]]}</pre><p>We can also cross-check by decoding the tokenized object to check if it holds the correct information as was provided by us.</p><pre>tokenizer.decode(output[&#39;input_ids&#39;][0])</pre><p>Let’s check the output.</p><pre>[CLS] the weather of today is great! zwp [SEP]</pre><p>The [CLS] token marks the beginning of the input sequence, and the [SEP] token marks the end of the input sequence. The text &quot;the weather of today is great! zwp&quot; is the actual content of the sequence.</p><pre>tokenizer.decode(output[&#39;input_ids&#39;][1])</pre><pre>[CLS] how are you doing? [SEP] [PAD] [PAD] [PAD] [PAD] [PAD]</pre><p>[PAD] tokens are added to the end of the sequence to make it reach a specific maximum length. The [PAD] tokens ensure that this sequence has the same length as other sequences in the batch.</p><p>Let’s write a function which preprocesses the text into tokens</p><pre>def preprocess_function(examples):<br>  return tokenizer(examples[&quot;text&quot;],padding=True,truncation=True,)</pre><pre>tokenized_dataset = dataset.map(preprocess_function, batched=True)<br>tokenized_dataset</pre><p>Let’s see what the tokenized dataset looks like now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*s83D12j5z8Dhwf3NiQNGDQ.png" /></figure><p>Let’s see the first few observations.</p><pre>pd.DataFrame({<br>    &#39;text&#39;:tokenized_dataset[&#39;train&#39;][:5][&#39;text&#39;],<br>    &#39;label&#39;:tokenized_dataset[&#39;train&#39;][:5][&#39;label&#39;],<br>    &#39;input_ids&#39;:tokenized_dataset[&#39;train&#39;][:5][&#39;input_ids&#39;],<br>    &#39;token_type_ids&#39;:tokenized_dataset[&#39;train&#39;][:5][&#39;token_type_ids&#39;],<br>    &#39;attention_mask&#39;:tokenized_dataset[&#39;train&#39;][:5][&#39;attention_mask&#39;]<br>    })</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLj1rDTB5gNOUDvmmdJkbw.png" /></figure><ul><li>input_ids is a list of integers where each integer corresponds to a token in the tokenized input sequence.</li><li>token_type_ids is used in models like BERT that can accept multiple input sequences, such as tasks involving question-answering or natural language inference. In a single-sequence task, all values in token_type_ids are typically set to 0, indicating that all tokens belong to the same input sequence. A two-sequence task (e.g., question-answering), token_type_ids helps the model distinguish between tokens from the first sequence and tokens from the second sequence. For the first sequence, token type IDs are set to 0, and for the second sequence, they are set to 1.</li><li>attention_mask is used to indicate which tokens in the input sequence should be attended to (given attention) by the model and which should be ignored. Typically, [PAD] tokens are masked with a value of 0 attention_mask to prevent the model from attending to padding tokens. This ensures that the model focuses its attention on the actual content of the sequence.</li></ul><p>Let’s now create a TensorFlow (TF) dataset from a tokenized dataset, and prepare this dataset for training a machine learning model, using TensorFlow.</p><pre># Train Dataset<br><br>tf_train_dataset = tokenized_dataset[&quot;train&quot;].to_tf_dataset(<br>    columns=[&#39;input_ids&#39;, &#39;token_type_ids&#39;, &#39;attention_mask&#39;, &#39;label&#39;],<br>    shuffle=True,<br>    batch_size=BATCH_SIZE,<br>)</pre><pre># Test Dataset<br><br>tf_val_dataset = tokenized_dataset[&quot;test&quot;].to_tf_dataset(<br>    columns=[&#39;input_ids&#39;, &#39;token_type_ids&#39;, &#39;attention_mask&#39;, &#39;label&#39;],<br>    shuffle=True,<br>    batch_size=BATCH_SIZE,<br>    #collate_fn=data_collator<br>)</pre><p>Let’s write a function to transform a dataset from one format to another. It retains the same data but restructures it by grouping the input-related components (&#39;input_ids&#39;, &#39;token_type_ids&#39;, and &#39;attention_mask&#39;) into a single dictionary and the labels (&#39;label&#39;) into a separate value.</p><pre>def swap_positions(dataset):<br>  return {&#39;input_ids&#39;:dataset[&#39;input_ids&#39;],<br>          &#39;token_type_ids&#39;:dataset[&#39;token_type_ids&#39;],<br>          &#39;attention_mask&#39;:dataset[&#39;attention_mask&#39;],},dataset[&#39;label&#39;]</pre><p>Let’s transform our Train and Validation dataset using the above function.</p><pre>tf_train_dataset=tf_train_dataset.map(swap_positions).prefetch(tf.data.AUTOTUNE)<br>tf_val_dataset=tf_val_dataset.map(swap_positions).prefetch(tf.data.AUTOTUNE)</pre><ul><li>The .prefetch() method is used to asynchronously fetch batches of data from the dataset while the model is training on the current batch. This can help reduce data loading times and keep the GPU or CPU more utilized.</li><li>tf.data.AUTOTUNE is a constant that indicates TensorFlow should automatically choose the number of batches to prefetch based on available resources and the execution context. This ensures optimal performance without manual tuning.</li></ul><p>Let’s check our Tensorflow-ready dataset which is ready for model creation.</p><pre>for i in tf_train_dataset.take(1):<br>  print(i)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VlaiIL-wxTKX8UvG0AReg.png" /></figure><p><strong>Step 5: Modelling using TFBertForSequenceClassification</strong></p><pre>model=TFBertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;,num_labels=1)<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71tAQ8uKUTEBS1YHkStD6g.png" /></figure><p><strong>Step 6: Training</strong></p><pre>num_epochs = 3<br>batches_per_epoch = len(tokenized_dataset[&quot;train&quot;]) // BATCH_SIZE<br>total_train_steps = int(batches_per_epoch * num_epochs)</pre><pre># Optimizer<br>optimizer, schedule = create_optimizer(init_lr=2e-5,num_warmup_steps=0, num_train_steps=total_train_steps)</pre><ul><li>init_lr=2e-5: This is the initial learning rate for training. It&#39;s set to 2e-5, which is a common starting point for fine-tuning pre-trained transformer models like BERT.</li><li>num_warmup_steps=0: This parameter controls how many initial training steps are used for &quot;warm-up.&quot; Warm-up is a technique that gradually increases the learning rate at the beginning of training to help the model converge faster. Setting it to 0 means there is no warm-up phase.</li><li>num_train_steps=total_train_steps: This parameter likely specifies the total number of training steps. It could represent the number of batches or examples you plan to use during training</li><li>schedule: This is likely the learning rate schedule, which specifies how the learning rate should change over time during training. Learning rate schedules can be step-wise, exponential, or follow other patterns.</li></ul><p><strong>Step 7: Compiling the Model</strong></p><pre>model.compile(loss=tf.keras.losses.BinaryCrossentropy(),<br>    optimizer=optimizer,<br>    metrics=[&#39;accuracy&#39;],)<br>    #run_eagerly=True)</pre><p><strong>Step 8: Fitting the Model</strong></p><pre>history=model.fit(<br>    tf_train_dataset.take(1000),<br>    validation_data=tf_val_dataset,<br>    epochs=3)</pre><blockquote>Note: The Model will take time to fit. I would recommend using GPU for this case. (When changing your runtime to GPU, don’t forget to run the above code cells again.)</blockquote><p><strong>Step 9: Plotting the Loss</strong></p><pre>plt.plot(history.history[&#39;loss&#39;])<br>plt.plot(history.history[&#39;val_loss&#39;])<br>plt.title(&#39;model_loss&#39;)<br>plt.ylabel(&#39;loss&#39;)<br>plt.xlabel(&#39;epoch&#39;)<br>plt.legend([&#39;train&#39;, &#39;val&#39;], loc=&#39;upper left&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*sF-laX52EJjOnxS-qbE8lA.png" /></figure><p><strong>Training Loss (Blue Line)</strong>: This line represents the loss on the training dataset. As the number of epochs increases, the training loss decreases significantly, which suggests that the model is learning and improving its predictions on the training data over time.</p><p><strong>Validation Loss (Orange Line):</strong> This line represents the loss on the validation dataset, which is not used for training but for evaluating the model’s performance. The validation loss decreases initially but then starts to increase after around 0.75 epochs.</p><p><strong>Overfitting</strong>: The fact that the training loss continues to decrease while the validation loss begins to increase after a certain point suggests that the model may be overfitting.</p><p><strong>Early Stopping Point</strong>: Based on this graph, we can implement early stopping to prevent overfitting. Early stopping would mean you stop training when the validation loss starts to increase, which would be just after 0.75 epochs in this case.</p><p>To improve the model’s performance and mitigate overfitting, you might consider techniques like adding dropout, using regularization, collecting more data, or simplifying the model. Since this is out of the scope of this article, I would talk about these issues in some other articles.</p><p><strong>Step 10: Plotting the Accuracy</strong></p><pre>plt.plot(history.history[&#39;accuracy&#39;])<br>plt.plot(history.history[&#39;val_accuracy&#39;])<br><br>plt.title(&#39;model_accuracy&#39;)<br>plt.ylabel(&#39;accuracy&#39;)<br>plt.xlabel(&#39;epoch&#39;)<br>plt.legend([&#39;train&#39;, &#39;val&#39;], loc=&#39;upper left&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*PnPtLEe2haIBArAH52pnBQ.png" /></figure><p>This chart indicates that while the model is performing increasingly well on the training data (as evidenced by the rising blue line), it is not showing significant improvement on new, unseen data (as evidenced by the flat orange line). This could be a sign of overfitting, where the model learns the training data very well, including its noise and outliers, but does not generalize well to new data. I would like to challenge you to improve the accuracy by dealing with Overfitting.</p><p><strong>Step 11: Testing</strong></p><pre>inputs = tokenizer([&quot;this movie looks very interesting, i love the fact that the actors do a great job in showing how people lived in the 18th century, which wasn&#39;t very good at all. But atleast this movie recreates this scenes! &quot;,<br>                    &quot;very good start, but movie started becoming uninteresting at some point though initially i thought it would have been much more fun. There was too much background noise, but later on towards the middle of the movie, my favorite character got in and he did a great job, so over &quot;], padding=True,return_tensors=&quot;tf&quot;)<br><br>logits = model(**inputs).logits<br>print(logits)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*0eqpCpC4uB6KOZbJydt0XA.png" /></figure><ol><li>For the first text input (“this movie looks very interesting…”), the logits are [-2.2396984, 1.9407922]. These values would need to be passed through a softmax function to interpret them as probabilities. The higher logit corresponds to the predicted class. In this case, since the second logit is higher, the model is likely predicting the sentiment of this input as positive.</li><li>For the second input (“very good start, but movie started becoming uninteresting…”), the logits are [3.3462846, -3.3634923]. Again, after applying softmax, the model appears to predict this input as having a negative sentiment due to the higher value being associated with the first logit.</li></ol><pre># Apply softmax to logits to get probabilities<br>probabilities = tf.nn.softmax(logits, axis=-1)<br><br># Print the probabilities<br>print(probabilities)</pre><p><strong>Conclusion</strong></p><p>Utilizing TFBertForSequenceClassification has led to notable accuracy achievements in our sequence classification endeavors. Continuous improvement is key, and there are several strategies to explore for enhancing model performance:</p><p>1. Implementing dropout layers to prevent overfitting.</p><p>2. Employing regularization techniques for better generalization.</p><p>3. Experimenting with advanced models such as RoBERTa and XtremeDistil for potentially superior results.</p><p>4. Converting models into the ONNX format to leverage cross-platform flexibility and optimize deployment for various use cases.</p><p>Each of these steps is a stride towards creating more robust, efficient, and adaptable machine learning models, pushing the boundaries of what’s possible in natural language processing.</p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Machine Learning, MLOps, and AWS Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e99deeec9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sampling Methods For Imbalanced Dataset Classification along with Python Code]]></title>
            <link>https://medium.com/@manjindersingh_10145/sampling-methods-for-imbalanced-classification-along-with-python-code-fa1832b5aaca?source=rss-357a921631be------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1832b5aaca</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sampling-technique]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Manjinder Singh]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 16:32:25 GMT</pubDate>
            <atom:updated>2023-11-16T16:54:51.092Z</atom:updated>
            <content:encoded><![CDATA[<p>In machine learning, dealing with imbalanced data is crucial. This occurs when there are unequal observations for different classes in a classification dataset. Known as imbalance classification or rare event modeling, this scenario arises when the dataset’s target label is unevenly distributed, making the less frequent class a ‘rare event.’ Such imbalances are common in real-world scenarios, where the minority class often holds greater significance, necessitating techniques to enhance its detection rate. This imbalance presents a significant challenge for predictive modeling, as algorithms favor the more prevalent class.</p><p>In everyday situations, such as thwarting cyber attacks, identifying critical illnesses, or managing exceptional cases in surveillance systems, we often encounter severe class imbalances, with ratios from 1:1000 to 1:5000. Addressing this requires the development of smart systems capable of adapting to and counteracting this substantial skew.</p><p>Let’s begin our exploration of this topic!</p><p>We will be discussing 4 commonly used Sampling Methods here :</p><ol><li>Random Sampling</li><li>SMOTE (Synthetic Minority Oversampling Technique)</li><li>Random Under-Sampling</li><li>Near Miss Under-Sampling</li></ol><blockquote><strong>NOTE: </strong>We will be using the <strong><em>make_classification</em></strong><em> </em>package from Scikit Learn which allows users to create datasets that they can use for classification models.</blockquote><p><strong>Step 1: Install And Import Libraries</strong></p><pre># Imbalanced-Learn is a Python module that helps in balancing the datasets <br># which are highly skewed or biased towards some classes.<br><br>pip install -U imbalanced-learn</pre><pre># Creating the modeling dataset<br>from sklearn.datasets import make_classification<br><br># Data processing<br>import pandas as pd<br>import numpy as np<br><br># Data visualization<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Model and performance<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report<br><br># Over sampling and under sampling<br>from imblearn.over_sampling import RandomOverSampler, SMOTE<br>from imblearn.under_sampling import RandomUnderSampler, NearMiss<br>from collections import Counter</pre><p><strong>Step 2: Create Imbalanced Dataset</strong></p><p>Let us now create the imbalanced dataset using the make_classification function.</p><pre># Create an imbalanced dataset<br>X, y = make_classification(n_samples=100000, n_features=2, n_informative=2,<br>                           n_redundant=0, n_repeated=0, n_classes=2,<br>                           n_clusters_per_class=1,<br>                           weights=[0.995, 0.005],<br>                           class_sep=0.5, random_state=0)<br><br># Convert the data from numpy array to a pandas dataframe<br>df = pd.DataFrame({&#39;feature1&#39;: X[:, 0], &#39;feature2&#39;: X[:, 1], &#39;target&#39;: y})<br><br># Check the target distribution<br>df[&#39;target&#39;].value_counts(normalize = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*Lo5T5rdTCsxtsyjxdHz7yA.png" /><figcaption>Imbalanced Dataset</figcaption></figure><p>We can see that we have a highly skewed dataset where 98.9% of the data belongs to Class 0 and 1.01% belongs to Class 1.</p><p><strong>Step 3: Let’s Visualize this using Scatter Plot</strong></p><pre># Visualize the data<br>plt.figure(figsize=(12, 8))<br>sns.scatterplot(x = &#39;feature1&#39;, y = &#39;feature2&#39;, hue = &#39;target&#39;, data = df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*uEwLvejc3FkS7wQpG9OCgQ.png" /></figure><p>We can see how disproportionate the data is.</p><p><strong>Step 3: Train Test Split</strong></p><p>In this step, we split the dataset into 80% training data and 20% validation data. random_state ensures that we have the same train test split every time. The seed number for random_state does not have to be 101, and it can be any number.</p><pre># Train test split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=101)<br>print(&#39;The number of records in the training dataset is&#39;, X_train.shape[0])<br>print(&#39;The number of records in the test dataset is&#39;, X_test.shape[0])</pre><pre>The number of records in the training dataset is 80000<br>The number of records in the test dataset is 20000</pre><p><strong>Step 4: Deciding the Performance Metric</strong></p><p>Prior to model development, it’s essential to select the performance metric that will guide our optimization efforts.</p><p>In modeling rare events, the key performance indicator often revolves around the recall or precision of the minority class. Take fraud detection as an instance: our goal is to enhance the true positive rate to detect as many fraud instances as feasible, making the minority class’s recall the focal metric for optimization.</p><p>Conversely, in situations like spam email filtering, the aim is to reduce the false positive rate to avoid incorrectly flagging crucial emails as spam. Here, precision for the minority class becomes the primary metric for refinement.</p><p>In this tutorial, we focus on fraud detection, hence we’ll prioritize optimizing the recall for the minority class.</p><p>Now we will be moving ahead with the Model Building. We will start with a Baseline Model and then progress towards improved models using Sampling Techniques.</p><blockquote><strong>Note</strong>: I am using here Random Forest Classifier. You can use any model of your choice.</blockquote><p><strong>Step 5: Creating a Baseline Model</strong></p><pre># Train the random forest model<br>rf = RandomForestClassifier()<br>baseline_model = rf.fit(X_train, y_train)<br>baseline_prediction = baseline_model.predict(X_test)<br><br># Check the model performance<br>print(classification_report(y_test, baseline_prediction))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*z9-Gy_0dqSn4Ub4aKq0bWw.png" /></figure><p>The recall value ranges from 0 to 1, 0 represents a 0% true positive rate, and 1 represents a 100% true positive rate. The output shows that the minority class has a recall of 0.04, which is very low.</p><p><strong>Step 6: Method 1 — Random Over Sampling</strong></p><p>It is a simple oversampling method that works on the basis of generating new samples for the minority class by <em>sampling with replacement</em>. The RandomOverSampler from the imblearn library provides such functionality.</p><blockquote><strong>Note</strong> that we apply the oversampling technique to the training dataset only. The testing dataset needs to keep untouched.</blockquote><pre># Randomly over sample the minority class<br>ros = RandomOverSampler(random_state=101)<br>X_train_ros, y_train_ros= ros.fit_resample(X_train, y_train)<br><br># Check the number of records after over sampling<br>print(sorted(Counter(y_train_ros).items()))</pre><pre>[(0, 79156), (1, 79156)]</pre><p>After random oversampling, the minority category increased from 817 to 79156, which is the same as the majority category.</p><p>From the visualization, we can see more orange minority data points after random oversampling.</p><p>Note: It is a good practice to visualize the change using a Scatter Plot. To keep the article short, I will skip that for now.</p><p>Now let’s run the same random forest model and check the performance after random oversampling.</p><pre># Train the random forest model<br># rf = RandomForestClassifier()<br>ros_model = rf.fit(X_train_ros, y_train_ros)<br>ros_prediction = ros_model.predict(X_test)<br><br># Check the model performance<br>print(classification_report(y_test, ros_prediction))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6r49G2o-Hg8yCapN5TmITA.png" /></figure><p>We can see that random oversampling did not provide a better result. We got a similar recall and a similar f1-score, and the precision decreased. Thus, the random oversampling has worse performance than the baseline model with no class ratio adjustment.</p><p><strong>Step 7: SMOTE Oversampling</strong></p><p>Let’s experiment with SMOTE (Synthetic Minority Oversampling Technique), a method introduced in 2002 by Chawla, Bowyer, Hall, and Kegelmeyer. Differing from random oversampling with replacement, SMOTE generates synthetic data points. It does this by linking each minority sample with its closest neighbors. For each minority sample, neighbors are randomly selected from their k nearest neighbors.</p><pre># Randomly over sample the minority class<br>smote = SMOTE(random_state=42)<br>X_train_smote, y_train_smote= smote.fit_resample(X_train, y_train)<br><br># Check the number of records after over sampling<br>print(sorted(Counter(y_train_smote).items()))</pre><pre>[(0, 79156), (1, 79156)]</pre><blockquote><strong>Note</strong>: By default K=3, you can define a value of your choice or use K as an Hyperparamter as well .</blockquote><p>Similar to random oversampling, the minority category increased from 817 to 79156 after SMOTE oversampling.</p><p>Note: When you visualize the new dataset after SMOTE analysis, you will see that the minority category is scattered around in zig-zag lines.</p><p>Let’s do the modeling part now.</p><pre># Train the random forest model<br># rf = RandomForestClassifier()<br>smote_model = rf.fit(X_train_smote, y_train_smote)<br>smote_prediction = smote_model.predict(X_test)<br><br># Check the model performance<br>print(classification_report(y_test, smote_prediction))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*95gUYc3OA37Jxr2qwD06FA.png" /></figure><p>We can see that the model using SMOTE increased recall to 0.27. Thus, it significantly improved the model’s ability to capture the minority class.</p><p>From the Over Sampling Techniques we have seen that Random Oversampling did not give us with desired results whereas SMOTE improved the performance significantly.</p><p>Let us now try out the Undersampling Methods. As the name implies, this time we will be reducing the majority class to the size of the minority class.</p><blockquote><strong>Note</strong>: You should be careful while practicing this technique because we are purposely reducing our data which would not be a good practice in real case scenarios especially when the difference between the two classes is really high.</blockquote><p><strong>Step 8: Random Under Sampling</strong></p><p>Random under-sampling randomly picks data points from the majority class. After the sampling, the majority class has the same number of data points as the minority class.</p><pre># Randomly under sample the majority class<br>rus = RandomUnderSampler(random_state=101)<br>X_train_rus, y_train_rus= rus.fit_resample(X_train, y_train)<br><br># Check the number of records after under sampling<br>print(sorted(Counter(y_train_rus).items()))</pre><pre>[(0, 844), (1, 844)]</pre><p>After random under-sampling, the majority category decreased from 844, which is the same as the minority category.</p><p>Let’s run the random forest classification model.</p><pre># Train the random forest model<br># rf = RandomForestClassifier()<br>rus_model = rf.fit(X_train_rus, y_train_rus)<br>rus_prediction = rus_model.predict(X_test)<br><br># Check the model performance<br>print(classification_report(y_test, rus_prediction))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*QdE3I3k_qVbuhvqKXckJTA.png" /></figure><p>After random undersampling, the recall increased to 0.54, it’s better than the over-sampling results.</p><p><strong>Step 9: Under Sampling using NearMiss</strong></p><p>NearMiss from the imblearn library uses the KNN (K Nearest Neighbors) to do under-sampling.</p><p>There are three versions of NearMiss algorithms. Based on the documentation of the imblearn library, here are the differences of the three versions:</p><ul><li>“NearMiss-1 selects the positive samples for which the average distance to the N closest samples of the negative class is the smallest.”</li><li>“NearMiss-2 selects the positive samples for which the average distance to the N farthest samples of the negative class is the smallest.”</li><li>“NearMiss-3 is a 2-step algorithm. First, for each negative sample, their M nearest neighbors will be kept. Then, the positive samples selected are the ones for which the average distance to the N nearest-neighbors is the largest.”</li></ul><p>This tutorial uses version 3, but you are encouraged to try other versions and compare the performances.</p><pre># Under sample the majority class<br>nearmiss = NearMiss(version=3)<br>X_train_nearmiss, y_train_nearmiss= nearmiss.fit_resample(X_train, y_train)<br><br># Check the number of records after over sampling<br>print(sorted(Counter(y_train_nearmiss).items()))</pre><pre>[(0, 844), (1, 844)]</pre><p>Let’s run the Model.</p><pre># Train the random forest model<br># rf = RandomForestClassifier()<br>nearmiss_model = rf.fit(X_train_nearmiss, y_train_nearmiss)<br>nearmiss_prediction = nearmiss_model.predict(X_test)<br><br># Check the model performance<br>print(classification_report(y_test, nearmiss_prediction))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*eFJZhuuJe0_vp1fluOJx_g.png" /></figure><p>NearMiss gives us the recall value of 0.65, which is the highest among the four methods.</p><p><strong>Conclusion</strong></p><p>Keep in mind that the performance metric that we are trying to improve depends on the use cases. There will be scenarios where precision is more important than recall as mentioned above. It is likely that in those cases other sampling techniques will be best to use. So Machine Learning is a game of experiments. There is no one generalized answer. It is a good practice to always try out different techniques and models and figure out what would work best for your use case.</p><h3>Enjoyed this Article?</h3><p><em>If you found this article helpful, make sure to </em><a href="https://medium.com/@manjindersingh_10145"><em>follow me</em></a><em> to stay up-to-date with my latest articles on Machine Learning, MLOps, and AWS Cloud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1832b5aaca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>