<?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 Suraj Bansal on Medium]]></title>
        <description><![CDATA[Stories by Suraj Bansal on Medium]]></description>
        <link>https://medium.com/@suraj_bansal?source=rss-c40d0f7a4cee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tK-EaPKqxB9ATK5Ri7UB6Q.jpeg</url>
            <title>Stories by Suraj Bansal on Medium</title>
            <link>https://medium.com/@suraj_bansal?source=rss-c40d0f7a4cee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:05:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suraj_bansal/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[Deep Neural Networks for Quantile Regression (Part 3b): Regularizing for Monotonicity]]></title>
            <link>https://medium.com/@suraj_bansal/deep-neural-networks-for-quantile-regression-part-3b-regularizing-for-monotonicity-c4b4b32754e1?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4b4b32754e1</guid>
            <category><![CDATA[quantile-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 11:39:27 GMT</pubDate>
            <atom:updated>2025-12-19T11:39:27.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction — From Crossing to Control</h3><p>If you’ve been following this quantile regression series, you’ve seen how we’ve gradually levelled up:</p><ul><li>In <a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053"><strong>Part 1</strong></a>, we used <strong>LightGBM</strong> to train separate models for different quantiles.</li><li>In <a href="https://medium.com/@suraj_bansal/part-2-quantile-regression-with-deep-learning-one-dnn-many-quantiles-78298c976104"><strong>Part 2</strong>,</a> we moved to a <strong>multi-headed Deep Neural Network (DNN)</strong> to predict multiple quantiles jointly.</li><li>In <a href="https://medium.com/@suraj_bansal/quantile-regression-part-3-a-one-model-many-quantiles-how-quantile-forests-get-it-right-930ab95bf888"><strong>Part 3-a</strong></a>, we explored <strong>Quantile Forests</strong>, which naturally produce well-ordered quantiles due to their sorting mechanism — and rarely exhibit quantile crossing.</li></ul><p>Each approach gave us more power and flexibility — but also introduced new challenges.</p><h4>🤨 The Problem</h4><p>In this post, we’re returning to our DNN setup — but pushing it a bit harder.</p><p>Instead of predicting far-apart quantiles like 10, 50, and 90 (where the model has plenty of room to space out predictions), we’ll predict <strong>closely spaced percentiles</strong>:</p><blockquote><strong><em>65th, 70th, and 75th</em></strong></blockquote><p>This might seem like a small change — but it makes a big difference.</p><p>When quantiles are that close together, the model needs to work harder to keep them ordered. And since standard DNNs don’t <em>know</em> anything about quantile ordering, they occasionally slip up.</p><p>When I tried this setup (with a fixed random seed), I observed:</p><blockquote><em>🔎 </em><strong><em>Quantile crossing in ~0.34% of test samples</em></strong><em><br> i.e., predicted 65th &gt; 70th or 70th &gt; 75th</em></blockquote><p>This is known as <strong>quantile crossing</strong>, and while it’s rare, it undermines interpretability, calibration, and any decision-making that assumes ordered uncertainty estimates.</p><p>We discussed the nature and causes of quantile crossing more deeply in <strong>Part 3-a</strong>, so we won’t repeat all of that here. Instead, this post is about something practical:</p><h4>👉 <strong>How do we reduce or eliminate quantile crossing when using deep models like DNNs?</strong></h4><p>Broadly, there are two families of solutions:</p><h4>1. Regularisation-based approaches (soft constraints)</h4><p>Add a loss penalty during training whenever the predicted quantiles violate their expected order. This doesn’t <em>guarantee</em> monotonicity, but it strongly encourages it. That’s the approach we’ll take in this post.</p><h4>2. Architectural constraints (hard constraints)</h4><p>These enforce monotonicity by design — e.g., using <a href="https://www.tensorflow.org/lattice"><strong>TensorFlow Lattice</strong></a> layers with explicit ordering constraints. They’re powerful, but more complex to implement and tune.</p><p>In this post, we’ll keep it simple — and effective — by adding a <strong>small regularisation term</strong> to our loss function.</p><h4>What’s Ahead</h4><p>Here’s what we’ll cover:</p><ul><li>How much quantile crossing do we actually observe in practice</li><li>How to modify the loss function to add a <strong>pairwise crossing penalty</strong></li><li>Results comparing unconstrained vs regularized DNNs</li><li>A brief discussion of other techniques, like lattice models</li></ul><p>Let’s begin by quantifying just how much crossing we’re dealing with…</p><h3>2. How Much Quantile Crossing Happens — and Why?</h3><p>As mentioned earlier, in <a href="https://medium.com/@suraj_bansal/part-2-quantile-regression-with-deep-learning-one-dnn-many-quantiles-78298c976104"><strong>Part 2</strong></a><strong>,</strong> we predicted the 10th, 50th, and 90th percentiles using a DNN, and crossing wasn’t really a concern there. Those quantiles are far enough apart that the model typically keeps them well-ordered, even without constraints.</p><p>But what happens when we <strong>tighten the spacing</strong> and ask the model to predict the 65th, 70th, and 75th percentiles instead?</p><p>That’s where things get interesting.</p><p>In this blog, I retrained the same multi-headed DNN architecture, but this time with <strong>p65, p70, and p75</strong> as targets. To evaluate how often the model violated monotonicity on the test set, I used the following simple check:</p><pre>model.eval()<br>with torch.no_grad():<br>    preds = model(Xte_num, Xte_lat, Xte_lon)<br><br>monotonicity_df = pd.DataFrame({<br>    &quot;actual&quot;: y_test.values,<br>    &quot;pred_65&quot;: preds[&quot;q_65&quot;].numpy(),<br>    &quot;pred_70&quot;: preds[&quot;q_70&quot;].numpy(),<br>    &quot;pred_75&quot;: preds[&quot;q_75&quot;].numpy()<br>})<br>monotonicity_df[&quot;violation_65_70&quot;] = monotonicity_df[&quot;pred_65&quot;] &gt; monotonicity_df[&quot;pred_70&quot;]<br>monotonicity_df[&quot;violation_70_75&quot;] = monotonicity_df[&quot;pred_70&quot;] &gt; monotonicity_df[&quot;pred_75&quot;]<br>monotonicity_df[&quot;any_violation&quot;] = monotonicity_df[&quot;violation_65_70&quot;] | monotonicity_df[&quot;violation_70_75&quot;]<br>total_samples = len(monotonicity_df)<br><br>violations_65_70 = monotonicity_df[&quot;violation_65_70&quot;].sum()<br>violations_70_75 = monotonicity_df[&quot;violation_70_75&quot;].sum()<br>total_violations = monotonicity_df[&quot;any_violation&quot;].sum()<br><br>print(&quot;=&quot; * 60)<br>print(&quot;MONOTONICITY CHECK SUMMARY&quot;)<br>print(&quot;=&quot; * 60)<br>print(f&quot;Total samples: {total_samples}&quot;)<br>print(f&quot;Violations (65th &gt; 70th percentile): {violations_65_70} ({100*violations_65_70/total_samples:.2f}%)&quot;)<br>print(f&quot;Violations (70th &gt; 75th percentile): {violations_70_75} ({100*violations_70_75/total_samples:.2f}%)&quot;)<br>print(f&quot;Total samples with any violation: {total_violations} ({100*total_violations/total_samples:.2f}%)&quot;)<br>print(&quot;=&quot; * 60)<br><br>if total_violations &gt; 0:<br>    print(f&quot;\nFirst 10 cases with monotonicity violations:&quot;)<br>    print(monotonicity_df[monotonicity_df[&quot;any_violation&quot;]].head(10))<br>else:<br>    print(&quot;No monotonicity violations found!&quot;)<br><br>print(f&quot;\n\nOverall prediction statistics:&quot;)<br>print(monotonicity_df[[&quot;pred_65&quot;, &quot;pred_70&quot;, &quot;pred_75&quot;]].describe())</pre><p>With my setup — including fixed random seed and standard hyperparameters — I observed:</p><blockquote><em>🔍 </em><strong><em>Monotonicity violations in 0.34% of test samples</em></strong></blockquote><p>That means roughly 1 in every 300 predictions had the 65th percentile exceed the 70th, or the 70th exceed the 75th, which technically breaks the definition of a valid quantile function.</p><p>Depending on your model, data, and training conditions, this number may vary. But the key takeaway is this:</p><blockquote><em>❗ </em><strong><em>When quantiles are tightly spaced, even well-trained DNNs can cross their wires.</em></strong></blockquote><p>In the next section, we’ll look at how to gently guide the model to respect quantile order — without changing the architecture — using a little trick in the loss function.</p><h3>3. From Standard DNN to Monotonic DNN</h3><p>We’re still using the same deep learning setup from Part 2 — a <strong>multi-headed neural network</strong>, where each output head is trained to predict a specific quantile using quantile loss.</p><p>In that earlier post, we predicted the 10th, 50th, and 90th percentiles — and we let each head train independently. That worked surprisingly well, because:</p><ul><li>The quantiles were far apart</li><li>The DNN had enough flexibility to capture their differences</li><li>And most importantly: <strong>we weren’t expecting perfect monotonicity</strong></li></ul><p>But as we saw in the last section, <strong>that freedom starts to backfire when the quantiles get closer</strong>.</p><h4>Why Do Quantiles Cross?</h4><p>Quantile loss (also called <em>pinball loss</em>) only cares about minimizing error for a single quantile — it has no clue what the <em>other</em> quantile heads are doing. That means:</p><ul><li>The 70th percentile head might drift too close to the 65th</li><li>Or the 75th might even dip <em>below</em> the 70th</li><li>And the model would never know it did anything wrong</li></ul><p>This independence between output heads is powerful, but it’s also risky — especially when <strong>the natural ordering of quantiles matters</strong>, as it almost always does.</p><h4>The Fix: Add a Crossing Penalty</h4><p>What if we could gently nudge the model during training to keep its quantiles in order?</p><p>That’s where <strong>regularisation</strong> comes in. Instead of redesigning the whole architecture, we simply <strong>add a small penalty</strong> to the loss function during training — one that <strong>activates only when the order is violated</strong>.</p><p>Think of it as a “soft constraint”:</p><ul><li>If the model behaves, we leave it alone</li><li>But if it crosses the lines, we nudge it back on track</li></ul><p>This approach doesn’t guarantee perfect monotonicity (that would require architectural constraints, which we’ll briefly discuss later), but it usually gets us <strong>most of the way there</strong> with <strong>minimal effort</strong>.</p><h4>Why This Works</h4><p>This regularisation technique has a few key benefits:</p><ul><li>It’s simple to implement — just one term added to your loss</li><li>It works well with any optimiser, batch size, or architecture</li><li>It still allows the model to focus on minimizing standard quantile loss</li><li>And it dramatically reduces quantile crossing, especially with close quantiles</li></ul><p>In the next section, we’ll walk through the exact loss function I used, show you how it’s computed, and why it’s so effective in practice.</p><h3>4. The Key Change — Modified Loss Function</h3><p>As we saw earlier, quantile crossing happens when the model predicts out-of-order values for percentiles — like the 65th being higher than the 70th. To fix this, we don’t need to redesign our model. We just need to <strong>modify the loss function</strong> during training to include a small <strong>penalty for crossing</strong>.</p><p>Let’s walk through exactly how that’s done — and how easy it is to integrate.</p><h4>Step 1: The Crossing Penalty Function</h4><p>We define a function that penalises quantile predictions <strong>only when they violate the expected order</strong> (i.e., q_65 &lt;= q_70 &lt;= q_75). Here&#39;s the complete function:</p><pre>def crossing_penalty_pairwise(pred_65, pred_70, pred_75):<br>    &quot;&quot;&quot;<br>    PAIRWISE crossing penalty to enforce monotonicity: pred_65 &lt;= pred_70 &lt;= pred_75Uses ReLU to only penalize violations:<br>    - If pred_65 &gt; pred_70: adds (pred_65 - pred_70)^2<br>    - If pred_70 &gt; pred_75: adds (pred_70 - pred_75)^2<br>    - Otherwise: no penalty (zero)<br>    &quot;&quot;&quot;<br><br>    violation_65_70 = torch.relu(pred_65 - pred_70)<br>    violation_70_75 = torch.relu(pred_70 - pred_75)<br>    crossing_loss = torch.mean(violation_65_70 ** 2) + torch.mean(violation_70_75 ** 2)<br>    return crossing_loss<br></pre><p>This function checks every prediction in the batch. If any quantile is out of order, it adds a <strong>squared penalty</strong>. That squared term makes the penalty grow quickly as the violation gets worse — encouraging the model to fix it.</p><h4>Step 2: The Training Loop</h4><p>Here’s the exact training loop with the crossing penalty added. Note how we:</p><ul><li>Compute the standard quantile loss (q_loss) across all three output heads</li><li>Compute the crossing penalty (c_loss) using the function above</li><li>Combine both into a total loss</li><li>Weight the penalty using a tunable hyperparameter: crossing_penalty_weight = 5.0</li></ul><pre>batch = 256<br>epochs = 500<br>crossing_penalty_weight = 5.0  <br><br>print(f&quot;Training with crossing penalty weight: {crossing_penalty_weight}&quot;)<br>print(&quot;=&quot; * 70)<br>for epoch in range(epochs):<br>    model.train()<br>    idx = torch.randperm(Xtr_num.size(0))<br>    <br>    epoch_quantile_loss = 0.0<br>    epoch_crossing_loss = 0.0<br>    n_batches = 0<br>    <br>    for i in range(0, Xtr_num.size(0), batch):<br>        b = idx[i:i+batch]<br>        xb_num, xb_lat, xb_lon, yb = Xtr_num[b], Xtr_lat[b], Xtr_lon[b], ytr[b]<br>        opt.zero_grad()<br>        out = model(xb_num, xb_lat, xb_lon)<br>        <br>        # Quantile losses (pinball loss)<br>        q_loss = (quantile_loss(out[&quot;q_65&quot;], yb, 0.65) +<br>                  quantile_loss(out[&quot;q_70&quot;], yb, 0.70) +<br>                  quantile_loss(out[&quot;q_75&quot;], yb, 0.75)) / 3.0<br>        <br>        # Monotonicity penalty<br>        c_loss = crossing_penalty_pairwise(out[&quot;q_65&quot;], out[&quot;q_70&quot;], out[&quot;q_75&quot;])<br>        <br>        # Total loss: quantile + regularization<br>        total_loss = q_loss + crossing_penalty_weight * c_loss<br>        <br>        total_loss.backward()<br>        opt.step()<br>        <br>        epoch_quantile_loss += q_loss.item()<br>        epoch_crossing_loss += c_loss.item()<br>        n_batches += 1<br>    <br>    # Log every 20 epochs<br>    if epoch % 20 == 0:<br>        model.eval()<br>        with torch.no_grad():<br>            out_val = model(Xte_num, Xte_lat, Xte_lon)<br>            q70_pred = out_val[&quot;q_70&quot;]<br>            under_rate_70 = (yte &gt; q70_pred).float().mean().item()<br>            <br>            # Check quantile violations<br>            violations = ((out_val[&quot;q_65&quot;] &gt; out_val[&quot;q_70&quot;]) |<br>                          (out_val[&quot;q_70&quot;] &gt; out_val[&quot;q_75&quot;])).float().mean().item()<br>        <br>        avg_q_loss = epoch_quantile_loss / n_batches<br>        avg_c_loss = epoch_crossing_loss / n_batches<br>        <br>        print(f&quot;Epoch {epoch:03d} | Q-Loss: {avg_q_loss:.4f} | C-Loss: {avg_c_loss:.5f} | &quot;<br>              f&quot;Under@q70: {under_rate_70:.3f} | Violations: {violations*100:.2f}%&quot;)<br>print(&quot;=&quot;*70)<br>print(&quot;Training complete!&quot;)</pre><h4>About crossing_penalty_weight</h4><p>This hyperparameter controls <strong>how strongly</strong> we enforce monotonicity:</p><ul><li>0.0 → no regularisation (i.e., the original unconstrained model)</li><li>1.0 → light penalty</li><li>5.0 (used here) → stronger push toward ordered predictions</li></ul><p>In my experiments, 10.0 was enough to bring <strong>quantile crossing down to ~0%</strong> without hurting validation accuracy.</p><p>You can tune this like any regularization parameter — start small and scale up if crossing persists.</p><h4>Summary</h4><p>With just:</p><ul><li>a few extra lines of code,</li><li>one small function, and</li><li>a single regularization weight,</li></ul><p>we’ve made our DNN <strong>quantile-aware</strong> — softly guiding it to keep its percentiles in line.</p><p>And the best part? No changes to architecture, output heads, or data needed.</p><h3>5: Results and Comparison</h3><p>So, how much of a difference did our small loss function tweak actually make?</p><p>To recap:</p><ul><li>In the unconstrained model, we predicted the 65th, 70th, and 75th percentiles using a standard multi-headed DNN.</li><li>With that setup, we observed:</li></ul><blockquote><em>❌ </em><strong><em>Quantile crossing in ~0.34% of test samples</em></strong><em><br> (i.e., predicted 65th &gt; 70th or 70th &gt; 75th)</em></blockquote><p>Then we trained the same model again — this time adding the crossing_penalty_pairwise() function to the loss, with a regularisation weight of 5<strong>.0</strong>.</p><p>Here’s what changed:</p><blockquote><strong><em>Quantile crossing reduced to just ~0.05%</em></strong><em><br> That’s a ~</em><strong><em>7x improvement</em></strong><em> — with almost perfectly ordered quantiles.</em></blockquote><h4>What About Accuracy?</h4><p>Since we’ve added a new term to the loss function, it’s important to note:</p><blockquote><em>🎯 </em><strong><em>Final accuracy metrics (like MSE, MAE, and under-prediction rate) may change slightly.</em></strong></blockquote><p>That’s expected — and even desirable. The model is now optimizing for both <strong>fit</strong> and <strong>structure</strong>. It’s learning not just to predict well, but to predict <strong>quantiles that make sense</strong>.</p><p>In practice, I observed that:</p><ul><li>Overall calibration (e.g., under-prediction rate at p70) and accuract metrics remained stable</li></ul><h4>Before vs After: Snapshot</h4><p>Here’s a side-by-side comparison of key metrics with and without regularization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*OsWE5kfpwihDSsHRKEFf5g.png" /><figcaption>Before integrating quantile crossing loss</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*K-v5i8CrDAXRP3sp2WwTGA.png" /><figcaption>After integrating the quantile crossing loss</figcaption></figure><h4>Summary</h4><p>With just a simple penalty term in the loss function:</p><ul><li>We reduced quantile crossing by <strong>&gt;7x</strong></li><li>Retained solid accuracy and calibration</li><li>Made our DNN more interpretable and reliable</li></ul><p>Not bad for a two-line change.</p><h3>6: Takeaways and Alternatives</h3><p>Quantile crossing is one of those problems that feels minor — until it isn’t.</p><p>Even if your model is 99.66% well-behaved, those 0.34% of crossed predictions can break assumptions, confuse stakeholders, and make downstream decisions riskier than they need to be.</p><p>In this post, we showed that a <strong>simple regularization term</strong> added to the loss function can dramatically reduce — and almost eliminate — quantile crossing in DNNs.</p><p>With just:</p><ul><li>One small loss function (crossing_penalty_pairwise)</li><li>A tunable weight (crossing_penalty_weight)</li><li>Zero changes to the model architecture</li></ul><p>… we brought quantile crossing down.</p><h4>When to Use Regularization</h4><p>This approach is ideal when:</p><ul><li>You’re already using deep models (like PyTorch or TensorFlow)</li><li>You need to predict multiple quantiles with minimal crossing</li><li>You care about preserving model flexibility</li><li>You want a lightweight, plug-and-play solution</li></ul><p>It’s especially helpful when you’re working with:</p><ul><li><strong>Tightly spaced quantiles</strong> (like p65/p70/p75)</li><li><strong>High-variance targets</strong></li><li><strong>Production models</strong> where interpretability matters</li></ul><h4>What About Hard Constraints?</h4><p>If your use case absolutely cannot tolerate any quantile crossing — ever — then you may want to explore <strong>monotonic architectures</strong>. One of the most popular options is:</p><ul><li><a href="https://www.tensorflow.org/lattice"><strong>TensorFlow Lattice</strong></a>: lets you define piecewise linear models with explicit monotonic constraints across inputs and outputs.</li></ul><p>These approaches <strong>guarantee monotonicity</strong>, but they come with trade-offs:</p><ul><li>More complex to implement and scale</li><li>Less flexible than vanilla DNNs</li><li>May require significant tuning</li></ul><h4>Final Thoughts</h4><p>This post wraps up our 4-part deep dive into <strong>quantile regression</strong>:</p><ol><li><strong>Part 1</strong>: LightGBM with separate models for each quantile</li><li><strong>Part 2</strong>: Multi-headed DNN with quantile loss</li><li><strong>Part 3-a</strong>: Quantile Forests (with natural monotonicity)</li><li><strong>Part 3-b (this post)</strong>: DNN + loss-based regularization for monotonicity</li></ol><p>Hopefully, you now have a toolkit of methods to try — from forests to deep nets — and the judgment to know <strong>when quantiles are behaving… and when they need a nudge.</strong></p><h4>Stay Connected!</h4><p>If you enjoyed this blog and want more content like this — data science, machine learning, model debugging, practical intuition — consider following me:</p><p>🔗 <a href="https://www.linkedin.com/in/surajbansal28/"><strong>Connect with me on LinkedIn</strong></a></p><p>Thanks for reading — and see you in the next one! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4b4b32754e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantile Regression Part 3-a: One Model, Many Quantiles — How Quantile Forests Get It Right ]]></title>
            <link>https://medium.com/@suraj_bansal/quantile-regression-part-3-a-one-model-many-quantiles-how-quantile-forests-get-it-right-930ab95bf888?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/930ab95bf888</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantile-regression]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 06:47:28 GMT</pubDate>
            <atom:updated>2025-10-13T06:47:28.375Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quantile Regression Part 3-a: One Model, Many Quantiles — How Quantile Forests Get It Right 🌲</h3><h3>1. Introduction &amp; Quick Refresher</h3><p>Welcome back to the <em>Quantile Regression</em> series! If you’ve been following along, we’ve already explored two powerful approaches to predicting quantiles:</p><ul><li><a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053">🔍 <strong>Blog 1: Quantile Regression with LightGBM</strong></a> — where we trained separate models for different quantiles (10th, 50th, and 90th) using the California housing dataset.</li><li><a href="https://medium.com/@suraj_bansal/part-2-quantile-regression-with-deep-learning-one-dnn-many-quantiles-78298c976104">🤖 <strong>Blog 2: Deep Quantile Networks</strong> </a>— where we built a DNN with multiple output heads to simultaneously predict multiple quantiles.</li></ul><p>In this blog (3-a), we’ll take a slightly different path — by leveraging <strong>Quantile Forests</strong>, a variant of Random Forests designed to estimate conditional quantiles directly.</p><p>Think of it as:</p><blockquote>“What if we could get multiple quantiles from a single model with no changes to loss functions or architecture tweaks?”</blockquote><p>🎯 That’s exactly what <strong>Quantile Forest</strong> lets us do — straight out of the box.</p><p>We’ll:</p><ul><li>Dive into <strong>how quantile forests work</strong></li><li>Use them to predict multiple quantiles with <strong>just a few lines of code</strong>, and</li><li>Show how they naturally handle <strong>quantile crossing</strong> — a common pitfall in quantile regression.</li></ul><h3>🌳 2. How Quantile Forest Works (Intuition First!)</h3><p>Imagine walking through a dense forest of decision trees. Now, instead of each tree giving you a single number (like in traditional regression), what if each tree whispered:</p><blockquote><em>“Hey, here’s a list of similar training points I’ve seen before. Want to see their target values?”</em></blockquote><p>That’s the <strong>core idea</strong> behind Quantile Forest.</p><h4>Step 1: Build a Forest of Trees (Just Like Random Forest)</h4><ul><li>Quantile Forest is based on the <strong>Random Forest</strong> algorithm.</li><li>Each tree is trained on a random subset of the data.</li><li>It splits the data using standard regression criteria (like minimizing MSE).</li></ul><blockquote><em>✅ Up to this point, it’s identical to a regular random forest regressor.</em></blockquote><h4>🔎 Step 2: Collect Leaf-Level Target Distributions</h4><p>When you input a new test point into the forest:</p><ul><li>It “falls” into a leaf node in each tree.</li><li>Instead of producing a single prediction, the tree gives you the <strong>target values of all training samples in that leaf</strong>.</li><li>Each Tree Returns a Backpack of Targets — Let’s say your test point lands in the following leaf nodes across 3 trees:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmvawehOuhSn3CHOmXETjg.png" /></figure><p>This gives you:</p><blockquote><em>A total of 6 target values across all trees: </em><strong><em>[23, 25, 22, 27, 24, 28]</em></strong></blockquote><p>These values form a <strong>sample from the conditional distribution</strong> of the target given your test features — <strong>without any distributional assumptions or learned weights</strong>.</p><blockquote><em>🧠 </em>This is the heart of quantile forest: instead of estimating the mean or variance, it gives you an entire empirical distribution.</blockquote><h4>📊 Step 3: Pool and Sort for Quantiles</h4><p>Once all those target values are collected from all trees:</p><ol><li><strong>Combine</strong> them into one big list.</li><li><strong>Sort</strong> them in ascending order.</li><li><strong>Pick the quantile(s)</strong> you’re interested in:</li></ol><p>— 10th percentile → lower bound estimate</p><p>— 50th percentile → median</p><p>— 90th percentile → upper bound</p><p>Let’s walk through it using the example above:</p><blockquote><em>📦 Pooled Targets: [23, 25, 22, 27, 24, 28]<br> 🔀 Sorted: [22, 23, 24, 25, 27, 28]</em></blockquote><p>Now:</p><ul><li><strong>10th percentile</strong> ≈ between 22 and 23 → ~22.5</li><li><strong>50th percentile</strong> ≈ middle of the list → ~24.5</li><li><strong>90th percentile</strong> ≈ between 27 and 28 → ~27.5</li></ul><p>You now have <strong>multiple quantile predictions from a single model</strong> — no retraining required, no different loss functions, no multi-headed networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Vsv61xctMRq2bUJ8dM4Zw.png" /></figure><h4>🧠 Why This Works Well</h4><ul><li>Because trees <strong>implicitly capture nonlinear interactions</strong>, the set of values from each leaf is already a context-specific sample — no parametric assumptions required.</li><li>It’s non-parametric and fully data-driven.</li></ul><h4>🧁 Bonus: You Can Ask for Any Quantile</h4><p>Even if you only used quantiles [0.1, 0.5, 0.9] during training, you can ask the model to predict for any arbitrary quantile at inference time — say 0.2 or 0.95.</p><p>That’s because the model is not learning to target specific quantiles — it’s simply learning to <strong>partition the space and remember what target values fall into each partition.</strong></p><p>It’s like having a “quantile oracle” that can give you any slice of the distribution you need, after training.</p><h3>3. Code Walkthrough: Plug-and-Play Quantile Forest</h3><p>Now that we understand how Quantile Forest works, let’s put it to use!</p><p>Below is the <strong>entire code snippet</strong> that trains and evaluates a quantile regression model using quantile_forest. This example uses the <strong>California housing dataset</strong>, preprocessed the same way we did in<a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053"> Blog 1</a>, where we used LightGBM to predict quantiles.</p><p>The beauty of this approach? <strong>Minimal code changes</strong>. You just plug in the quantile forest model in a few lines — and it works like magic.</p><h4>Code Block</h4><pre><br># imports<br>import pandas as pd<br>import numpy as np<br>from plotnine import *<br>from sklearn.model_selection import train_test_split<br>from quantile_forest import RandomForestQuantileRegressor<br>from sklearn.metrics import mean_absolute_error, mean_squared_error<br><br># load california housing dataset<br>data = pd.read_parquet(&quot;housing_dataset.parquet&quot;)<br>data[&quot;Latitude&quot;] = data[&quot;Latitude&quot;].round(1)<br>data[&quot;Longitude&quot;] = data[&quot;Longitude&quot;].round(1)<br><br># split data<br>x = data.drop(columns=[&quot;target&quot;])<br>y = data[&quot;target&quot;]<br>x[&quot;Latitude&quot;] = x[&quot;Latitude&quot;].astype(&quot;category&quot;)<br>x[&quot;Longitude&quot;] = x[&quot;Longitude&quot;].astype(&quot;category&quot;)<br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)<br>x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)<br><br># train quantile regression forest model<br>quantiles = [0.1, 0.5, 0.9]<br>model = RandomForestQuantileRegressor(<br>    n_estimators=100,<br>    random_state=42,<br>    n_jobs=-1,<br>    default_quantiles=quantiles<br>)<br>model.fit(x_train, y_train)<br><br># make predictions<br>pred_df = pd.DataFrame({<br>    &quot;actual&quot;: y_test,<br>    &quot;pred_10&quot;: model.predict(x_test)[:, 0],<br>    &quot;pred_50&quot;: model.predict(x_test)[:, 1],<br>    &quot;pred_90&quot;: model.predict(x_test)[:, 2]<br>})<br><br># evaluation metrics<br>def get_metrics(actual, predicted):<br>    metrics = {}<br>    mae = mean_absolute_error(actual, predicted)<br>    mse = mean_squared_error(actual, predicted)<br>    rmse = np.sqrt(mse)<br>    underpreds = (actual &gt; predicted).mean()<br>    overpreds = (predicted &gt;= actual).mean()<br>    metrics[&quot;mae&quot;] = mae<br>    metrics[&quot;mse&quot;] = mse<br>    metrics[&quot;rmse&quot;] = rmse<br>    metrics[&quot;underpreds&quot;] = underpreds<br>    metrics[&quot;overpreds&quot;] = overpreds<br>    return metrics<br><br>results = {}<br>for col in [&quot;pred_10&quot;, &quot;pred_50&quot;, &quot;pred_90&quot;]:<br>    results[col] = get_metrics(pred_df[&quot;actual&quot;], pred_df[col])<br>metrics_df = pd.DataFrame(results).T <br>print(metrics_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*VUnlvaf9Z7yvCWkeKLJplQ.png" /></figure><h4>Code Change Summary</h4><p>If you’ve already gone through <a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053">Blog 1: XGBoost Quantile Regression</a>, you’ll notice that:<em> The </em><strong><em>only real change</em></strong><em> is where we define and train the model — we’ve replaced the XGBoost model with:</em></p><pre>from quantile_forest import RandomForestQuantileRegressor<br><br>model = RandomForestQuantileRegressor(<br>    n_estimators=100,<br>    random_state=42,<br>    n_jobs=-1,<br>    default_quantiles=[0.1, 0.5, 0.9]<br>)<br>model.fit(x_train, y_train)</pre><p>That’s it! Everything else — data prep, evaluation, and plotting — stays the same.</p><p>Just install the library via:</p><pre>pip install quantile-forest</pre><p>…and you’re good to go!</p><h4>📉 Quick Note on Results</h4><p>The results might differ slightly from LGBM or DNN-based quantile regression in terms of accuracy or sharpness. That’s <strong>okay</strong>. The point of this blog isn’t to optimise metrics — it’s to showcase the power and simplicity of Quantile Forest.</p><h3>4. How Quantile Forest Naturally Avoids Quantile Crossing</h3><h4>What Is Quantile Crossing?</h4><p>Quantile crossing happens when predicted quantiles violate their natural ordering. For example:</p><pre>Q10 (10th percentile):  $120,000  <br>Q50 (50th percentile):  $115,000 ❌  <br>Q90 (90th percentile):  $130,000</pre><p>This is <strong>statistically invalid</strong> — we expect quantiles to follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*MrycYMVeYNuX99v4K0FsVQ.png" /></figure><p>This issue often shows up when:</p><ul><li>Training <strong>separate models</strong> per quantile</li><li>Using <strong>multi-output models</strong> without constraints</li></ul><h4>Why Quantile Forest Avoids It By Design</h4><p>Quantile Forest does something smarter:</p><ol><li><strong>Collects training target values</strong> from all the leaves your test point falls into</li><li><strong>Pools and sorts</strong> them into an empirical distribution</li><li><strong>Extracts all requested quantiles</strong> (e.g. 10th, 50th, 90th) from the <em>same</em> sorted list</li></ol><p>Because all quantiles are derived from the same sorted distribution, <strong>they are inherently monotonic</strong>.</p><p>In other words:</p><blockquote><em>The way Quantile Forest works makes quantile crossing essentially almost </em><strong><em>impossible under normal conditions</em></strong><em>.</em></blockquote><h4>Empirical Check — Just to Be Sure</h4><p>We still ran a quick check to confirm that all quantile predictions follow the correct order:</p><pre>quantiles_to_check = [0.5, 0.7, 0.9]<br>preds = model.predict(x_test, quantiles=quantiles_to_check)<br><br><br>monotonicity_df = pd.DataFrame({<br>    &quot;actual&quot;: y_test,<br>    &quot;pred_50&quot;: preds[:, 0],<br>    &quot;pred_70&quot;: preds[:, 1],<br>    &quot;pred_90&quot;: preds[:, 2]<br>})<br><br>monotonicity_df[&quot;violation_50_70&quot;] = monotonicity_df[&quot;pred_50&quot;] &gt; monotonicity_df[&quot;pred_70&quot;]<br>monotonicity_df[&quot;violation_70_90&quot;] = monotonicity_df[&quot;pred_70&quot;] &gt; monotonicity_df[&quot;pred_90&quot;]<br>monotonicity_df[&quot;any_violation&quot;] = monotonicity_df[&quot;violation_50_70&quot;] | monotonicity_df[&quot;violation_70_90&quot;]<br><br>total_samples = len(monotonicity_df)<br>violations_50_70 = monotonicity_df[&quot;violation_50_70&quot;].sum()<br>violations_70_90 = monotonicity_df[&quot;violation_70_90&quot;].sum()<br>total_violations = monotonicity_df[&quot;any_violation&quot;].sum()<br><br>print(&quot;=&quot; * 60)<br>print(&quot;MONOTONICITY CHECK SUMMARY&quot;)<br>print(&quot;=&quot; * 60)<br>print(f&quot;Total samples: {total_samples}&quot;)<br>print(f&quot;Violations (50th &gt; 70th percentile): {violations_50_70} ({100*violations_50_70/total_samples:.2f}%)&quot;)<br>print(f&quot;Violations (70th &gt; 90th percentile): {violations_70_90} ({100*violations_70_90/total_samples:.2f}%)&quot;)<br>print(f&quot;Total samples with any violation: {total_violations} ({100*total_violations/total_samples:.2f}%)&quot;)<br>print(&quot;=&quot; * 60)<br><br>if total_violations &gt; 0:<br>    print(f&quot;\nFirst 10 cases with monotonicity violations:&quot;)<br>    print(monotonicity_df[monotonicity_df[&quot;any_violation&quot;]].head(10))<br>else:<br>    print(&quot;\n✓ No monotonicity violations found!&quot;)<br><br>print(f&quot;\n\nOverall prediction statistics:&quot;)<br>print(monotonicity_df[[&quot;pred_50&quot;, &quot;pred_70&quot;, &quot;pred_90&quot;]].describe())</pre><h4>Result: Zero violations.</h4><p>Even across thousands of test samples, the predicted quantiles followed the correct order in every case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*ze-oe11zUpm_6Eh_bIymcA.png" /></figure><h4>So, Can Quantile Crossing Ever Happen?</h4><p>In theory — <strong>very, very rarely</strong> — numerical edge cases <em>could</em> cause tiny inconsistencies:</p><ul><li>Extremely small sample sizes</li><li>Rounding or floating-point interpolation quirks</li></ul><p>…but in practical usage, and especially in this example, <strong>no quantile crossing occurred</strong>.</p><h3>5. Wrapping Up: When Simplicity Wins</h3><p>In this post, we explored how <strong>Quantile Forests</strong> allow you to predict <strong>multiple quantiles from a single model</strong> — effortlessly and intuitively.</p><p>Here’s what we covered:</p><p>✅ A quick refresher of the problem and past approaches<br> ✅ An intuitive (and deep) dive into how Quantile Forests work<br> ✅ A simple code walkthrough with minimal changes from Blog 1<br> ✅ Why <strong>quantile crossing is practically avoided</strong> in this approach<br> ✅ A hands-on check that showed <strong>no violations in practice</strong></p><blockquote><em>🔍 Sometimes, simpler tools like Quantile Forests can offer robust and interpretable solutions — without the overhead of custom loss functions or architecture tweaks.</em></blockquote><h4>🔮 What’s Next?</h4><p>In the <strong>next part of this series (Blog 3-b)</strong>, we’ll return to the <strong>multi-headed DNN model from </strong><a href="https://medium.com/@suraj_bansal/part-2-quantile-regression-with-deep-learning-one-dnn-many-quantiles-78298c976104"><strong>Blog 2</strong></a> and explore:</p><blockquote><em>🧠 </em><strong><em>How to reduce quantile crossing in deep models by customising the loss function to enforce monotonicity.</em></strong></blockquote><h4>🙌 Stay Connected!</h4><p>If you enjoyed this blog and want more content like this — data science, machine learning, model debugging, practical intuition — consider following me:</p><p>🔗 <a href="https://www.linkedin.com/in/surajbansal28/"><strong>Connect with me on LinkedIn</strong></a><br> 📬 <strong>Subscribe to get notified when Blog 3-b drops!</strong></p><p>Thanks for reading — and see you in the next one! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=930ab95bf888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Quantile Regression with Deep Learning: One DNN, Many Quantiles]]></title>
            <link>https://medium.com/@suraj_bansal/part-2-quantile-regression-with-deep-learning-one-dnn-many-quantiles-78298c976104?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/78298c976104</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantile-regression]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 06:06:25 GMT</pubDate>
            <atom:updated>2025-08-27T06:06:25.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Quick Refresher (a.k.a. Where We Left Off)</h3><p>In <a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053">Part 1</a>, we had some fun with <strong>LightGBM</strong> and learned how to predict quantiles like the 10th, 50th, and 90th percentiles of California housing prices. But there was a catch: we had to train <strong>three separate models</strong> — one for each quantile. That worked fine, but it feels a little clunky, doesn’t it?</p><p>Imagine if you had to carry around three phones, one for calls, one for texts, and one for taking photos. 🤯 Sure, it gets the job done, but it’s definitely not efficient.</p><p>That’s where <strong>deep learning</strong> comes in. Instead of juggling multiple models, we can build a single <strong>neural network with multiple heads</strong>, where each head is responsible for predicting a different quantile. This not only makes training and deployment easier but also lets the model share useful information across quantiles.</p><p>👉 In this blog, we’re not chasing the highest possible accuracy (so don’t expect Kaggle gold medals here 🏅). Instead, the focus is on <strong>understanding how to build and train a DNN that outputs multiple quantiles in one go</strong>.</p><h3>Why Neural Networks for Quantile Regression? 🤖</h3><p>So why even bother with neural networks for quantile regression when LightGBM(or other tree-based models) already does a decent job?</p><p>Here are some reasons neural nets are worth exploring:</p><ul><li><strong>Shared learning across quantiles</strong>: A DNN can capture common patterns in the data once, then branch out into multiple “heads” for each quantile. This is especially useful when quantiles aren’t totally independent.</li><li><strong>Flexibility with inputs</strong>: Neural networks handle not just tabular data, but also images, text, and sequences. Imagine predicting quantiles of <strong>demand spikes from time series</strong>, or <strong>house prices using both text descriptions and images</strong> — DNNs make that possible.</li><li><strong>Unified deployment</strong>: Instead of packaging three separate models, you get one neat model that outputs multiple quantiles in a single call. Simpler, faster, cleaner.</li><li><strong>Research-friendly</strong>: Neural nets are highly customizable. You can easily extend them with attention layers, embeddings, or monotonic constraints (👀 sneak peek at Part 3!).</li></ul><p>👉 In short, neural networks give us <strong>a playground of flexibility</strong> while keeping things efficient.</p><h3>Architecture Walkthrough — One Model, Many Heads</h3><p>At a high level, here’s what we’re building:</p><ul><li>A set of <strong>shared layers</strong> that learn a common representation of the input features (think of this as the “brain”).</li><li>Multiple <strong>heads</strong> branching out, one per quantile (e.g., 10th, 50th, 90th percentile). Each head is just a small, dense layer that makes its own prediction.</li><li>Each head uses its own <strong>pinball loss function</strong> to learn the right quantile.</li></ul><p>This looks something like:</p><pre>Input Features  <br>      │  <br>   Shared Layer1 (Dense + Activation)  <br>      │ <br>   Shared Layer2  (Dense + Activation)  <br>      │ <br> ┌────┼────┐<br> │    │    │<br>Q10 Head  Q50 Head  Q90 Head<br> │         │         │<br>Loss10   Loss50   Loss90</pre><p>👉 Each head is independent in terms of loss, but they all benefit from the same shared representation. That’s what makes this approach both <strong>efficient</strong> and <strong>scalable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2HChSsLYY1J_YESH3qw1w.png" /><figcaption>High-Level Architecture for Multi-Head DNN for Quantile Regression</figcaption></figure><h3>The Code: Building a Multi-Head DNN</h3><p>Now that we understand the architecture, let’s roll up our sleeves and code it out. We’ll stick with the <strong>California Housing dataset</strong> (same as in <a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053">Part 1</a>) so you can compare results directly.</p><h4>Step 1: Load the data</h4><p>We start by loading the California housing dataset.</p><pre>&quot;&quot;&quot;<br>Imports<br>&quot;&quot;&quot; <br><br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import pandas as pd<br>import numpy as np<br>from plotnine import *<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.pipeline import make_pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import LabelEncoder<br>from lightgbm import LGBMRegressor, early_stopping, log_evaluation<br>from sklearn.metrics import mean_absolute_error, mean_squared_error<br><br># Load dataset<br>data = pd.read_parquet(&quot;housing_dataset.parquet&quot;)<br>print(data.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wtMT7SdSkgMGRd8q.png" /></figure><h4>Step 2: Preprocess categorical &amp; numeric features, then convert to tensors</h4><p>We’ll create <strong>categorical grid IDs</strong> from latitude/longitude by rounding to 1 decimal place, then <strong>enumerate</strong> them to <strong>integer indices</strong>. Why enumerate first? Because a PyTorch nn.Embedding is a <strong>lookup table</strong> keyed by integer IDs — it can’t consume raw floats or strings. So we (1) bin/round -&gt; (2) map each unique bin to an integer ID -&gt; (3) feed IDs to the <a href="https://docs.pytorch.org/docs/stable/generated/torch.nn.Embedding.html">embedding layer.</a></p><pre>&quot;&quot;&quot;<br>proprocessing <br>&quot;&quot;&quot;<br><br># split into train and test<br>X = data.drop(columns=[&quot;target&quot;])<br>y = data[&quot;target&quot;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># enumerate (map) categories to integer IDs <br>def build_cat_map(series):<br>    cats = series.dropna().unique()<br>    return {v: i+1 for i, v in enumerate(np.sort(cats))}<br><br>lat2id = build_cat_map(X_train[&quot;Latitude&quot;])<br>lon2id = build_cat_map(X_train[&quot;Longitude&quot;])<br><br>def map_with_oov(series, mapping):<br>    return series.map(mapping).fillna(0).astype(int)<br><br>X_train[&quot;lat_id&quot;] = map_with_oov(X_train[&quot;Latitude&quot;], lat2id)<br>X_train[&quot;lon_id&quot;] = map_with_oov(X_train[&quot;Longitude&quot;], lon2id)<br>X_test[&quot;lat_id&quot;]  = map_with_oov(X_test[&quot;Latitude&quot;],  lat2id)<br>X_test[&quot;lon_id&quot;]  = map_with_oov(X_test[&quot;Longitude&quot;],  lon2id)<br><br><br># imputing missing values and scaling numerical columns<br>imputer = SimpleImputer(strategy=&quot;median&quot;)<br>scaler = StandardScaler()<br><br>numeric_cols = [c for c in X_train.columns if c not in [&quot;Latitude&quot;,&quot;Longitude&quot;,&quot;lat_id&quot;,&quot;lon_id&quot;]]<br>preprocess = make_pipeline(imputer, scaler)<br>X_train_scaled = preprocess.fit_transform(X_train[numeric_cols])<br>X_test_scaled  = preprocess.transform(X_test[numeric_cols])<br><br># convert to tensors<br>Xtr_num = torch.tensor(X_train_scaled, dtype=torch.float32)<br>Xte_num = torch.tensor(X_test_scaled,  dtype=torch.float32)<br>ytr = torch.tensor(y_train.values, dtype=torch.float32)<br>yte = torch.tensor(y_test.values,  dtype=torch.float32)<br><br>Xtr_lat = torch.tensor(X_train[&quot;lat_id&quot;].values, dtype=torch.long)<br>Xtr_lon = torch.tensor(X_train[&quot;lon_id&quot;].values, dtype=torch.long)<br>Xte_lat = torch.tensor(X_test[&quot;lat_id&quot;].values,  dtype=torch.long)<br>Xte_lon = torch.tensor(X_test[&quot;lon_id&quot;].values,  dtype=torch.long)<br><br>n_lat = int(max(X_train[&quot;lat_id&quot;].max(), X_test[&quot;lat_id&quot;].max())) + 1<br>n_lon = int(max(X_train[&quot;lon_id&quot;].max(), X_test[&quot;lon_id&quot;].max())) + 1</pre><h4>Step 3: Define the pinball (quantile) loss</h4><p>Pinball loss (aka quantile loss) tilts residuals toward the desired quantile: positive vs. negative errors are penalised asymmetrically</p><pre><br>def pinball_loss(pred, target, q: float):<br>    e = target - pred<br>    return torch.maximum((q-1)*e, q*e).mean()</pre><p>Here:</p><ul><li>q = quantile (e.g., 0.1, 0.5, 0.9)</li><li>true = true value</li><li>pred = predicted value</li></ul><h4>Step 4: Create the model class &amp; instantiate</h4><p>Shared backbone -&gt; three heads (q10, q50, q90). We also <strong>bias-initialise</strong> heads to the empirical target quantiles for faster, better‑calibrated starts.</p><pre># model definition<br><br>class QuantileEmbeddingModel(nn.Module):<br>    def __init__(self, num_numeric, n_lat, n_lon, quantiles=(0.1,0.5,0.9), emb_lat_dim=8, emb_lon_dim=8, hidden=(64,32), y_train=None):<br>        super().__init__()<br>        self.quantiles = quantiles<br>        <br>        self.lat_emb = nn.Embedding(n_lat, emb_lat_dim)<br>        self.lon_emb = nn.Embedding(n_lon, emb_lon_dim)<br><br>        in_dim = num_numeric + emb_lat_dim + emb_lon_dim<br>        layers = []<br>        last = in_dim<br>        <br>        for h in hidden:<br>            layers += [nn.Linear(last, h), nn.ReLU()]<br>            last = h<br>        self.shared = nn.Sequential(*layers)<br>        <br>        # output heads<br>        self.heads = nn.ModuleDict({f&quot;q_{int(q*100)}&quot;: nn.Linear(last, 1) for q in quantiles})<br><br>        if y_train is not None:<br>            y_np = y_train.detach().cpu().numpy()<br>            for q in quantiles:<br>                b = np.quantile(y_np, q).astype(np.float32)<br>                self.heads[f&quot;q_{int(q*100)}&quot;].bias.data.fill_(b)<br><br>    def forward(self, X_num, lat_id, lon_id):<br>        lat_vec = self.lat_emb(lat_id)<br>        lon_vec = self.lon_emb(lon_id)<br>        h = torch.cat([X_num, lat_vec, lon_vec], dim=1)<br>        h = self.shared(h)<br>        return {name: head(h).squeeze(-1) for name, head in self.heads.items()}<br><br>quantiles = (0.1, 0.5, 0.9)<br>model = QuantileEmbeddingModel(<br>    num_numeric=Xtr_num.shape[1],<br>    n_lat=n_lat, n_lon=n_lon,<br>    quantiles=quantiles,<br>    emb_lat_dim=8, emb_lon_dim=8,<br>    hidden=(64,32),<br>    y_train=ytr<br>)<br>opt = optim.Adam(model.parameters(), lr=1e-3)<br>print(model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*BRjHHHl4hM3ENoi7Pqpbsg.png" /><figcaption>high-level model architecture</figcaption></figure><h3>Step 5: Train the model (multi‑head = multi‑loss -&gt; averaged)</h3><p>Keras averages multi‑output losses by default; we’ll mirror that idea and <strong>average</strong> the three pinball losses for backprop. (Shared layers get gradients from all heads; each head gets its own loss gradients.)</p><pre>batch = 256<br>epochs = 200<br>for epoch in range(epochs):<br>    model.train()<br>    idx = torch.randperm(Xtr_num.size(0))<br>    for i in range(0, Xtr_num.size(0), batch):<br>        b = idx[i:i+batch]<br>        xb_num, xb_lat, xb_lon, yb = Xtr_num[b], Xtr_lat[b], Xtr_lon[b], ytr[b]<br>        opt.zero_grad()<br>        out = model(xb_num, xb_lat, xb_lon)<br>        L = (quantile_loss(out[&quot;q_10&quot;], yb, 0.1) +<br>             quantile_loss(out[&quot;q_50&quot;], yb, 0.5) +<br>             quantile_loss(out[&quot;q_90&quot;], yb, 0.9)) / 3.0<br>        L.backward()<br>        opt.step()<br>    <br>    if epoch % 10 == 0:<br>        model.eval()<br>        with torch.no_grad():<br>            out_val = model(Xte_num, Xte_lat, Xte_lon)<br>            q50_pred = out_val[&quot;q_50&quot;]<br>            under_rate = (yte &gt; q50_pred).float().mean().item()<br><br>        print(f&quot;Epoch {epoch:03d} | Loss: {L.item():.4f} | Under@q50: {under_rate:.3f}&quot;)</pre><h3>Step 6: Evaluate &amp; get predictions</h3><p>We train all three heads simultaneously.</p><pre>model.eval()<br>with torch.no_grad():<br>    preds =  model(Xte_num, Xte_lat, Xte_lon)<br>    pred_df = pd.DataFrame({<br>        &quot;actual&quot;: y_test,<br>        &quot;pred_10&quot;: preds[&quot;q_10&quot;].numpy(),<br>        &quot;pred_50&quot;: preds[&quot;q_50&quot;].numpy(),<br>        &quot;pred_90&quot;: preds[&quot;q_90&quot;].numpy()<br>    })<br><br>def underprediction_rate(y_true, y_pred):<br>    return np.mean(y_pred &lt; y_true)<br><br>def overprediction_rate(y_true, y_pred):<br>    return np.mean(y_pred &gt; y_true)<br><br>for q, pred in zip([0.1, 0.5, 0.9], [pred_df[&quot;pred_10&quot;], pred_df[&quot;pred_50&quot;], pred_df[&quot;pred_90&quot;]]):<br>    print(f&quot;Quantile: {q}&quot;)<br>    print(f&quot;MAE: {round(mean_absolute_error(y_test, pred), 2)}&quot;)<br>    print(f&quot;Underprediction Rate: {round(underprediction_rate(y_test, pred), 2)}&quot;)<br>    print(f&quot;Overprediction Rate: {round(overprediction_rate(y_test, pred), 2)}&quot;)<br>    print(&quot;-&quot; * 40)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*Mf4feQUJJKonb5-X-4PPfw.png" /><figcaption>sample output</figcaption></figure><p>🎉 <strong>Hurray!</strong> We’ve improved the accuracy of our model — and the best part is that <strong>one single model is giving us all three quantile predictions at once</strong>. The under-prediction and over-prediction rates also look much more reasonable, lining up with the quantiles we targeted.</p><h3>Step 7: Visualizing the Predicted Quantiles</h3><pre>df = pd.DataFrame({<br>    &quot;actual&quot;: y_test,<br>    &quot;pred_10&quot;: pred_10,<br>    &quot;pred_50&quot;: pred_50,<br>    &quot;pred_90&quot;: pred_90<br>})<br><br>sample = df.sample(min(10000, len(df)), random_state=42).sort_values(&quot;actual&quot;).reset_index(drop=True)<br><br>sample[&quot;index&quot;] = sample.index<br><br>plot_df = pd.melt(<br>    sample,<br>    id_vars=[&quot;index&quot;,&quot;actual&quot;],<br>    value_vars=[&quot;pred_10&quot;, &quot;pred_50&quot;, &quot;pred_90&quot;],<br>    var_name=&quot;quantile&quot;,<br>    value_name=&quot;prediction&quot;<br>)<br><br>plot = (<br>    ggplot(plot_df, aes(x=&quot;index&quot;, y=&quot;prediction&quot;, color=&quot;quantile&quot;)) +<br>    geom_point(alpha=0.5, size=1) +<br>    geom_smooth(se=False, method=&quot;loess&quot;, size=2, alpha=1) +<br>    geom_line(aes(y=&quot;actual&quot;), color=&quot;black&quot;, size=1.2, linetype=&quot;dashed&quot;) +<br>    labs(<br>        title=&quot;Quantile Predictions&quot;,<br>        x=&quot;Index&quot;,<br>        y=&quot;Prediction&quot;<br>    ) +<br>    theme_minimal()<br>)<br><br>plot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ru2IA4jRHJm5WwDm2r4bYw.png" /></figure><h3>Wrap-Up</h3><p>And there we have it — our <strong>multi-head PyTorch model</strong> that predicts multiple quantiles in one go!</p><p>Let’s recap what we did today:</p><p>We started with the <strong>California Housing dataset</strong> (same as in Part 1 for consistency).</p><ul><li>We <strong>preprocessed numeric and categorical variables</strong>, turning latitude/longitude into embeddings while scaling the rest.</li><li>We defined the <strong>pinball loss</strong> (quantile loss) and learned how each head gets its own version.</li><li>We built a <strong>shared backbone with multiple heads</strong> (q10, q50, q90), bias-initialized them smartly, and trained everything together.</li><li>Finally, we evaluated and saw that <strong>one single model now gives us all quantiles</strong>, with under/over-prediction rates that actually make sense for the quantiles we’re targeting. 🎉</li></ul><p>👉 <strong>Why is this powerful?</strong> Instead of juggling three different models like we did with XGBoost in <a href="https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053">Part 1</a>, we now have <strong>one unified model</strong> that’s efficient, scalable, and flexible.</p><p>But this is just the beginning. There’s still one problem lurking in quantile regression land: sometimes the quantiles <strong>cross over each other</strong> (e.g., your q90 prediction ends up lower than q50 😬). In Part 3, we’ll tackle this head-on with <strong>monotonic constraints and tricks to reduce quantile crossing</strong>.</p><p>💡 Curious to learn more? Try experimenting with:</p><ul><li>Different embedding sizes for latitude/longitude.</li><li>Adding dropout layers for regularization.</li><li>Training on your own datasets (demand spikes, trip times, delivery estimates).</li></ul><h3>Key Takeaways</h3><ul><li><strong>Quantile regression</strong> helps us model not just the “average” but the spread and uncertainty.</li><li><strong>Multi-head neural networks</strong> let us predict multiple quantiles from a single shared backbone.</li><li><strong>Embeddings</strong> turn categorical/binned variables (like lat/long grids) into learnable features.</li><li><strong>Bias initialisation</strong> of output heads can stabilise training and reduce persistent skew.</li><li><strong>One model &gt; many models</strong> when it comes to scalability and deployment simplicity.</li></ul><h3>Coming Up in Part 3</h3><p>Quantile regression has one sneaky issue: <strong>quantile crossing</strong> (imagine q90 dipping below q50 — yikes!). In the next article, we’ll explore <strong>monotonic constraints and regularisation tricks</strong> to keep quantiles in order and predictions more reliable. Stay tuned — things are about to get even more interesting!</p><p>Thanks for following along! If you enjoyed this, connect with me on <a href="https://www.linkedin.com/in/surajbansal28/">LinkedIn</a> — I post more about applied machine learning, experimentation, Causal inference and GenAI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78298c976104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantile Regression in Python with LightGBM: Predicting Percentiles (Part 1)]]></title>
            <link>https://medium.com/@suraj_bansal/quantile-regression-in-python-with-lightgbm-predicting-percentiles-part-1-460e6756a053?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/460e6756a053</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lightgbm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quantile-regression]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 07:30:03 GMT</pubDate>
            <atom:updated>2025-08-19T18:20:02.432Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Ever booked a ride and saw your ETA as 5 minutes… but it took 10? Or worse, the driver cancelled? That one number didn’t tell you how uncertain the situation really was.</em></blockquote><blockquote>Businesses that rely on predictions — ride times, delivery windows, housing prices — often just report <strong>the average</strong>. But what if you could know <strong>the best-case, worst-case, and most likely</strong> outcome instead of just one number?</blockquote><blockquote>That’s exactly what <strong>quantile regression</strong> does: it gives you a fuller view of your outcome by predicting multiple percentiles — like the 10th, 50th, and 90th — instead of just the mean</blockquote><h3>Why Quantile Regression (and Not Just Regular Regression)?</h3><p>Let’s face it — <strong>most models are overconfident</strong>.</p><p>Whether you’re predicting:</p><ul><li>🏠 House prices</li><li>🚗 Ride ETAs</li><li>📦 Delivery times</li><li>🏦 Loan default risks</li></ul><p>…standard regression models give you <strong>just one number</strong> — typically the <strong>mean</strong>. That works if you’re forecasting with a nice, clean bell-shaped curve.</p><p>But in real life? The data is often <strong>skewed</strong>, <strong>uncertain</strong>, or <strong>noisy</strong>.</p><h4>Let’s say you’re Uber (or Lyft)</h4><p>You show riders a predicted wait time of <strong>5 minutes</strong>.</p><p>But in reality:</p><ul><li>10% of riders are picked up in under <strong>3 minutes</strong>.</li><li>10% are stuck waiting <strong>over 10 minutes</strong>.</li><li>And most fall somewhere in the middle.</li></ul><p><strong>Just showing the average hides this variation.</strong></p><p>With <strong>quantile regression</strong>, you can predict:</p><ul><li>The <strong>10th percentile (optimistic case)</strong> ⏱️</li><li>The <strong>50th percentile (median)</strong> 🔁</li><li>The <strong>90th percentile (worst-case delay)</strong> 🐢</li></ul><p>This means you don’t just say “you’ll wait 5 minutes” — you can say:</p><blockquote>“Most riders wait between 3 to 10 minutes, but we expect 5 minutes on average.”</blockquote><h4>What Quantile Regression Actually Does</h4><p>Quantile regression estimates a <strong>conditional quantile</strong> of the target variable — meaning it can answer questions like:</p><ul><li><em>“What value will 90% of outcomes fall below?”</em></li><li><em>“What’s the best/worst-case scenario for this prediction?”</em></li></ul><p>That’s powerful in any domain where:</p><ul><li>You care about <strong>risk and uncertainty</strong></li><li>You want to offer <strong>prediction intervals</strong></li><li>You’re modelling <strong>non-symmetric</strong> or <strong>heteroskedastic</strong> data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgoV9eE6w25rLdSVi6Z-gA.png" /><figcaption>quantile regression bands — <a href="https://blog.dailydoseofds.com/p/introduction-to-quantile-regression">source</a></figcaption></figure><p>Look for the image above that shows a median line with bands for the 25th and 75th percentiles around it.</p><h3>What This Blog Series Covers</h3><h4>A Hands-On Guide to Quantile Regression (No PhD Required)</h4><p>This blog is Part 1 of a <strong>three-part, hands-on series</strong> where we’ll build quantile regression models from scratch — all in Python — using real-world examples and code you can run yourself.</p><p>But this isn’t just about code. We’ll build your <strong>intuition</strong> along the way so you don’t just <em>do</em> quantile regression — you actually <em>get</em> it.</p><p>Here’s what the full series looks like:</p><h4>Part 1 (This Post)</h4><p>🔨 <strong>Train separate LightGBM models</strong> to predict the 10th, 50th, and 90th percentiles of house prices using the California Housing dataset. Learn how to:</p><ul><li>Train separate models for each quantile</li><li>Evaluate under- and over-prediction rates</li><li>Understand how quantiles reveal distribution shape</li></ul><p>📌 <em>You’re here now!</em></p><h4>Part 2 (Coming Soon)</h4><p>⚡ <strong>Predict multiple quantiles with one DNN model</strong> using a <strong>multi-headed neural network</strong>. Why train three models when one can do it all?</p><h4>Part 3 (Finale)</h4><p>🧰 <strong>Fix quantile crossing issues</strong> using <strong>monotonic constraints</strong> — a must-have when your predicted lower quantiles are higher than the upper ones (yes, it happens 😅).</p><blockquote><em>🚨 </em><strong><em>Note</em></strong><em>: We’re not chasing model accuracy here.<br> The focus is on </em><strong><em>learning</em></strong><em>, not leaderboard scores — so we’ll skip steps like feature selection or hyperparameter tuning. That said, we’ll still explore real-world modelling concerns like </em><strong><em>under-/over-prediction</em></strong><em> and </em><strong><em>quantile interpretability</em></strong><em>.</em></blockquote><p>Next up: we’ll look at the dataset we’re using and get a feel for the problem we’re solving.</p><h3>Dataset Overview</h3><h4>Meet the California Housing Dataset</h4><p>To keep things simple, reproducible, and real estate relevant, we’re using the <strong>California Housing dataset</strong> — a classic tabular dataset that comes bundled with sklearn.</p><p>We’ve saved it as a <strong>Parquet file</strong> locally (no need to re-download each time), and it includes features like:</p><ul><li>Median income</li><li>House age</li><li>Average number of rooms</li><li>Latitude and longitude</li><li>Population per block</li></ul><p>And our <strong>target variable</strong>?<br> 📍 median_house_value — the median price of homes in a block.</p><h4>Why This Dataset?</h4><p>It’s:</p><ul><li>✅ Small enough to train quickly</li><li>✅ Real-world enough to reveal interesting patterns</li><li>✅ Perfect for quantile regression because <strong>home prices vary wildly</strong> across regions, income levels, and locations — making the distribution messy (read: not always normally distributed)</li></ul><p>That makes it an excellent candidate to demonstrate how quantile regression can uncover <strong>more than just the average price</strong>.</p><p>Next, we’ll jump into understanding what quantile loss is and how it works.</p><h3>How the &#39;quantile&#39; Objective Works in LightGBM</h3><p>Most regression models use <strong>mean squared error</strong> or <strong>mean absolute error</strong> as their objective. These are great for predicting the <strong>average</strong> — but not for capturing uncertainty or estimating distribution tails.</p><p>That’s where the <strong>quantile loss</strong> (also known as <strong>pinball loss</strong>) comes in.</p><p>In LightGBM, setting objective=&#39;quantile&#39; tells the model:</p><blockquote><em>“Don’t just minimise the average error — instead, minimise the asymmetric error based on a target quantile.”</em></blockquote><p>Let’s break it down.</p><h4>The Quantile Loss Function</h4><p>The quantile loss for a prediction (y’) and actual target y, with quantile q, is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*s5rcmo8C8VDpu0JXbHISrg.png" /><figcaption>quantile/pinball loss</figcaption></figure><p>In Python-style pseudocode:</p><pre>def quantile_loss(y_true, y_pred, tau):<br>    error = y_true - y_pred<br>    return np.where(error &gt;= 0, tau * error, (1 - tau) * -error)</pre><h4>Why This Asymmetry?</h4><ul><li>When predicting the <strong>10th percentile</strong> (q = 0.1), the model gets <strong>penalised more heavily for over-predicting</strong> (because it wants to stay below the actual value).</li><li>When predicting the <strong>90th percentile</strong> (q = 0.9), the model gets <strong>penalised more for under-predicting</strong> (because it wants to stay above most values).</li></ul><p>This asymmetric penalty <strong>shifts the model’s focus</strong> to hit the desired quantile, not the average.</p><h4>A Simple Example</h4><p>Let’s say you’re predicting delivery times.</p><p>You have the following actual times:<br> [3, 5, 7, 9, 11] (in days)</p><p>And your model predicts 5 days consistently.</p><h4>If you’re optimising for:</h4><ul><li><strong>Median (q = 0.5)</strong>: The model is happy if 50% of the actual values are below 5 and 50% above.</li><li><strong>10th percentile (q = 0.1)</strong>: The model wants only 10% of the values to fall below its prediction — so it will learn to <strong>underestimate</strong>.</li><li><strong>90th percentile (q = 0.9)</strong>: It wants 90% of the values to fall below its prediction — so it will <strong>overestimate</strong>.</li></ul><h4>The TL;DR:</h4><ul><li>Quantile loss lets you <strong>predict percentiles</strong>, not just averages.</li><li>LightGBM handles this internally when you set objective=&#39;quantile&#39; and specify alpha=0.1, 0.5, or 0.9.</li><li>It’s perfect for situations where <strong>uncertainty matters</strong> — like ride ETAs, stock prices, delivery SLAs, or house prices.</li></ul><p>Now that we understand what quantile loss is doing under the hood, let’s put it into action with real models in LightGBM.</p><h3>Modelling Quantiles with LightGBM</h3><h4>Predicting the 10th, 50th, and 90th Percentiles with LightGBM</h4><p>Instead of using custom loss functions, we’ll take advantage of <strong>LightGBM’s built-in support for quantile regression</strong> by setting the objective parameter to &#39;quantile&#39;.</p><p>We’ll train three separate models:</p><ul><li>The <strong>10th percentile model</strong> (alpha=0.1)</li><li>The <strong>median model</strong> (alpha=0.5)</li><li>The <strong>90th percentile model</strong> (alpha=0.9)</li></ul><h4>Step 1: Imports &amp; Setup</h4><pre>&quot;&quot;&quot;<br>Imports<br>&quot;&quot;&quot;<br><br>import pandas as pd<br>import numpy as np<br>from plotnine import *<br>from sklearn.model_selection import train_test_split<br>from lightgbm import LGBMRegressor, early_stopping, log_evaluation<br>from sklearn.metrics import mean_absolute_error, mean_squared_error</pre><h4>Step 2: Load the California Housing Data</h4><pre># load california housing dataset<br>data = pd.read_parquet(&quot;housing_dataset.parquet&quot;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0VaZOAdIrID5v60HAwLLw.png" /></figure><h4>Step 3: Geolocation Preprocessing</h4><p>To reduce feature granularity and sparsity, we round the latitude and longitude.</p><pre># round latitude and longitude to 1 decimal place<br>data[&quot;Latitude&quot;] = data[&quot;Latitude&quot;].round(1)<br>data[&quot;Longitude&quot;] = data[&quot;Longitude&quot;].round(1)</pre><h4>Step 4: Train/Test Split</h4><pre>X = data.drop(&quot;target&quot;, axis=1)<br>y = data[&quot;target&quot;]<br><br>X[&quot;Latitude&quot;] = X[&quot;Latitude&quot;].astype(&quot;category&quot;)<br>X[&quot;Longitude&quot;] = X[&quot;Longitude&quot;].astype(&quot;category&quot;)<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)</pre><h4>Step 5: Define and Train the LightGBM Models</h4><p>We define a helper function to train each model with a different quantile:</p><pre>def train_lgb_quantile_model(alpha):<br>    model = LGBMRegressor(objective=&quot;quantile&quot;, alpha=alpha, n_estimators=100)<br>    model.fit(<br>    X_train,<br>    y_train,<br>    eval_set=[(X_val, y_val)],<br>    callbacks=[<br>        early_stopping(stopping_rounds=10),<br>        log_evaluation(period=10)<br>    ],<br>    categorical_feature=[&quot;Latitude&quot;, &quot;Longitude&quot;]<br>    )<br>    return model<br><br>q10_model = train_lgb_quantile_model(0.1)<br>q50_model = train_lgb_quantile_model(0.5)<br>q90_model = train_lgb_quantile_model(0.9)</pre><h4>Step 6: Predict and Evaluate</h4><pre>pred_10 = q10_model.predict(X_test)<br>pred_50 = q50_model.predict(X_test)<br>pred_90 = q90_model.predict(X_test)</pre><p>We define helper functions to compute under- and over-prediction rates and evaluate for each quantile</p><pre>def underprediction_rate(y_true, y_pred):<br>    return np.mean(y_pred &lt; y_true)<br><br>def overprediction_rate(y_true, y_pred):<br>    return np.mean(y_pred &gt; y_true)<br><br>for q, model, pred in zip([0.1, 0.5, 0.9], [q10_model, q50_model, q90_model], [pred_10, pred_50, pred_90]):<br>    print(f&quot;Quantile: {q}&quot;)<br>    print(f&quot;MAE: {round(mean_absolute_error(y_test, pred), 2)}&quot;)<br>    print(f&quot;Underprediction Rate: {round(underprediction_rate(y_test, pred), 2)}&quot;)<br>    print(f&quot;Overprediction Rate: {round(overprediction_rate(y_test, pred), 2)}&quot;)<br>    print(&quot;-&quot; * 40)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*NlqPE0HOzAA_iMzVnbxvXQ.png" /><figcaption>sample output</figcaption></figure><h4>Step 7: Visualizing the Predicted Quantiles</h4><pre>df = pd.DataFrame({<br>    &quot;actual&quot;: y_test,<br>    &quot;pred_10&quot;: pred_10,<br>    &quot;pred_50&quot;: pred_50,<br>    &quot;pred_90&quot;: pred_90<br>})<br><br>sample = df.sample(min(10000, len(df)), random_state=42).sort_values(&quot;actual&quot;).reset_index(drop=True)<br><br>sample[&quot;index&quot;] = sample.index<br><br>plot_df = pd.melt(<br>    sample,<br>    id_vars=[&quot;index&quot;,&quot;actual&quot;],<br>    value_vars=[&quot;pred_10&quot;, &quot;pred_50&quot;, &quot;pred_90&quot;],<br>    var_name=&quot;quantile&quot;,<br>    value_name=&quot;prediction&quot;<br>)<br><br>plot = (<br>    ggplot(plot_df, aes(x=&quot;index&quot;, y=&quot;prediction&quot;, color=&quot;quantile&quot;)) +<br>    geom_point(alpha=0.5, size=1) +<br>    geom_smooth(se=False, method=&quot;loess&quot;, size=2, alpha=1) +<br>    geom_line(aes(y=&quot;actual&quot;), color=&quot;black&quot;, size=1.2, linetype=&quot;dashed&quot;) +<br>    labs(<br>        title=&quot;Quantile Predictions&quot;,<br>        x=&quot;Index&quot;,<br>        y=&quot;Prediction&quot;<br>    ) +<br>    theme_minimal()<br>)<br><br>plot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dYN_5gu3UHyBoc6Kbke0w.png" /></figure><h4>Insights from Evaluation</h4><p>Your actual evaluation results demonstrate exactly what we expect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*CImyBpuE-D-RLw_EEyqq1g.png" /></figure><p>This confirms:</p><ul><li><strong>Low quantiles</strong> play it safe and underestimate</li><li><strong>High quantiles</strong> hedge for risk and overestimate</li><li>The <strong>median model</strong> balances both</li></ul><h3>Wrapping Up &amp; What’s Next</h3><h4>🎉 What We Did</h4><p>In this post, you learned how to:</p><ul><li>Use <strong>quantile regression</strong> to capture more than just the average outcome</li><li>Leverage <strong>LightGBM’s built-in support</strong> for quantile objectives</li><li>Train separate models for the <strong>10th, 50th, and 90th percentiles</strong></li><li>Evaluate model performance using <strong>underprediction</strong> and <strong>overprediction</strong> rates</li><li>Visualize predicted quantile bands for a sample of real-world data</li></ul><p>You also learned how the <strong>quantile loss function</strong> works under the hood — giving you control over how the model penalises errors for different risk levels.</p><p>Even without fancy tuning or feature engineering, quantile regression gave us <strong>insight into the full distribution</strong> of house prices — not just a single number.</p><h4>What’s Coming in Part 2</h4><p>In the next post, we’ll level up our modeling game by:</p><blockquote><em>🔮 Building a </em><strong><em>multi-output deep neural network</em></strong><em> that predicts all three quantiles </em><strong><em>in one model</em></strong><em>!</em></blockquote><p>That means less training time, shared representation learning, and some neural network magic.</p><p>Stay tuned for:</p><ul><li>🧱 How to structure multi-head DNNs using PyTorch</li><li>⚙️ Custom loss functions for quantiles</li><li>🔬 Visualising the learned prediction bands</li></ul><h4>Final Words</h4><p>Quantile regression is one of those underrated tools that every applied data scientist should have in their toolbox. Whether you’re modeling ETAs, prices, risk scores, or delays — it’s a simple, powerful way to bring <strong>uncertainty awareness</strong> into your predictions.</p><p><strong>Enjoyed this post?</strong><br>Follow along for <strong>Parts 2 and 3</strong>, or try applying quantile regression to a dataset of your own. Curious how it performs on your <strong>delivery estimates</strong>, <strong>house prices</strong>, or <strong>time-to-match predictions</strong>? Go explore! 🚀</p><p>If you found this helpful, feel free to <a href="https://www.linkedin.com/in/surajbansal28/"><strong>follow me on LinkedIn</strong></a> for more hands-on tutorials, ML insights, and updates when the next post drops. Let’s connect and nerd out on cool stuff together! 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=460e6756a053" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Difference-in-Differences: Estimating Causal Effects from Observational Data]]></title>
            <link>https://medium.com/@suraj_bansal/unlocking-the-power-of-difference-in-differences-estimating-causal-effects-from-observational-data-0fff74eba3a3?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fff74eba3a3</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 06:00:46 GMT</pubDate>
            <atom:updated>2024-10-15T06:27:51.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re leading the launch of a new product feature — a redesigned checkout process that you believe will speed up purchase completion rates. You want to measure its impact on your users. The ideal scenario? You’d run a randomized controlled trial (RCT). But there’s a problem: You can’t randomly assign this new feature to users because it’s already been rolled out across specific regions, or perhaps you don’t have the infrastructure to conduct an A/B test.</p><p>So how do you determine whether your new feature is driving the improvement, or if it’s just a coincidence?</p><p>Welcome to the world of <strong>observational data</strong>, where things are far less controlled. In these scenarios, you’re left wondering if the observed effects are due to your intervention or other external factors. <strong>Difference-in-Differences (DiD)</strong> is a powerful tool that steps in when RCTs are off the table.</p><p><strong>Difference-in-Differences </strong>allows you to estimate the causal effect of a treatment or intervention by comparing the difference in outcomes over time between a group that is exposed to the treatment and a group that is not. In essence, it answers this question: “What would have happened to the treatment group had they not received the treatment?”</p><p>It’s a method that’s particularly useful for situations where you have <strong>pre- and post-treatment data</strong> for both treated and untreated groups, helping you isolate the effect of the intervention from other confounding factors.</p><p>This blog post is designed specifically for data scientists, product analysts, and product managers who want to go beyond traditional A/B testing or who are faced with real-world constraints where randomized trials aren’t feasible. Whether you’re looking to analyze the impact of a new feature rollout, measure the effectiveness of a marketing campaign, or evaluate policy changes, DiD offers a practical approach to estimate causal effects using observational data.</p><p>By the end of this article, you’ll understand:</p><ul><li>What DiD is and why it’s a valuable tool for causal inference.</li><li>When to use DiD, especially in scenarios where RCTs are not possible.</li><li>The assumptions that make DiD valid, and how to check those assumptions in your data.</li><li>How to calculate DiD, both manually and using a regression model.</li><li>Common pitfalls and drawbacks to watch out for when applying DiD in real-world situations.</li></ul><h3>What is Difference-in-Differences</h3><p><strong>Difference-in-Differences</strong> is a statistical method used to estimate the <strong>causal effect</strong> of an intervention using observational data. It is especially helpful when randomized controlled trials (RCTs) are not possible, but you still have data from both <strong>before</strong> and <strong>after</strong> the intervention for a group that received the treatment and a group that did not. DiD helps isolate the effect of an intervention by comparing the <strong>change</strong> in outcomes over time for a <strong>treated group </strong>(the one that receives the intervention) with a <strong>control group</strong> (one that doesn’t).</p><p>Let’s bring this to life with our earlier example about improving <strong>purchase completion rates</strong>. You’ve rolled out a <strong>redesigned checkout process</strong> to a subset of users and want to know if it increased purchase completions. You have two groups:</p><p>— A <strong>treated group</strong>: Users who experienced the new checkout design.</p><p>— A <strong>control group</strong>: Users who did not experience the redesign.</p><p>To measure the impact of the redesign, you collect data on purchase completion rates <strong>before</strong> and <strong>after</strong> the rollout for both groups. You notice that the treated group has a higher purchase completion rate after the redesign. But how do you know whether the increase is due to the redesign, or if it was just a coincidence?</p><p>This is where DiD comes in. Instead of just looking at the difference for the treated group, DiD compares the changes in both the treated and control groups over the same period, helping you account for any external factors (like seasonal trends or promotions) that may have influenced both groups.</p><p>The formula for DiD is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4VSHY22G8BEz1A6wGD1eg.png" /></figure><p>In our example:</p><ul><li><strong>Post-Treatment Outcome (Treated)</strong>: Purchase completion rate after the redesign for users who received it.</li><li><strong>Pre-Treatment Outcome (Treated)</strong>: Purchase completion rate before the redesign for those same users.</li><li><strong>Post-Treatment Outcome (Control)</strong>: Purchase completion rate for users who didn’t receive the redesign after the same time period.</li><li><strong>Pre-Treatment Outcome (Control)</strong>: Purchase completion rate for the control group before the redesign.</li></ul><p>By calculating these differences, DiD gives you a clearer estimate of the <strong>true causal effect</strong> of the checkout redesign, separating it from other external influences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBemDweIJ5iKKpK9vK0O2Q.png" /><figcaption>Fig1: Measuring treatment effect before after the intervention using DiD for survey at t1 and t2</figcaption></figure><h3>Why is Difference-in-Differences Important?</h3><p>When you’re trying to understand the impact of an intervention — whether it’s a new product feature, a marketing campaign, or a policy change — using <strong>before-and-after comparisons</strong> alone can lead to <strong>incorrect conclusions</strong>. This is because the world doesn’t stay still: trends, external events, and other factors can change your outcome variable over time, regardless of the intervention.</p><p>This is where Difference-in-Differences comes into play. DiD is important because it accounts for underlying trends and other factors affecting both the treated and control groups over time. By comparing the changes in both groups, DiD helps you isolate the <strong>true effect</strong> of your intervention.</p><h4>Why Simple Before-and-After Comparisons Can Mislead</h4><p>Let’s go back to our purchase completion rate example. You’ve redesigned the checkout process for a subset of users and observed a rise in purchase completions after the rollout. If you simply compared the <strong>before-and-after</strong> results for the treated group, it might look like the redesign is responsible for the increase. But what if there was already an <strong>upward trend </strong>in purchase completion rates for all users, even those who didn’t get the redesign?</p><p>Here’s how DID solves this problem:</p><ul><li><strong>Before-and-after comparisons</strong> don’t account for trends that affect both groups. If the overall market is improving, you could mistakenly credit the intervention for growth that would have happened anyway. If we had only conducted a before-and-after analysis in the plot below, attributing ΔT to the treatment effect would have been biased due to the existing upward trend, even though no actual treatment occurred.</li><li>DID, on the other hand, compares the <strong>difference</strong> in changes between the treated and control groups. If both groups were on a similar trajectory before the intervention, and only the treated group shows a larger change afterward, you can confidently attribute that additional change to your intervention.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*CJGESALlJ6WLxoru5-RniQ.png" /><figcaption>Fig 2: Biased treatment effect just by doing before and after analysis</figcaption></figure><h3>Key Assumptions for DiD to Work</h3><p>While <strong>Difference-in-Differences </strong>is a powerful tool, it relies on several key assumptions for the results to be valid. Ignoring these assumptions can lead to incorrect conclusions about the causal effect of your intervention. In this section, we’ll go through the most important assumptions.</p><ol><li><strong>Parallel Trends Assumption: </strong>The most critical assumption in DiD is that, in the absence of the intervention, the <strong>treated group</strong> and the <strong>control group</strong> would have followed <strong>parallel trends</strong> over time. In other words, both groups should have experienced similar changes in the outcome variable if the intervention had never occurred. <strong>Why does this matter?</strong> If the treated group was already improving faster than the control group before the intervention, then any additional improvement after the treatment could be due to that pre-existing trend rather than the treatment itself. The DiD method assumes that any differences between the treated and control groups before the intervention remain <strong>constant</strong> over time.</li><li><strong>No Simultaneous Shocks: </strong>Another assumption is that there are no <strong>external shocks</strong> or interventions affecting the control group that could influence the outcome during the study period. For example, if a major event or policy change happens that only affects the control group during the analysis period, this could skew the results, making it seem like the intervention had a larger effect than it actually did. In practice, this assumption means that you need to be aware of any other factors that might affect one group differently from the other during the observation period.</li><li><strong>Stable Composition of Group</strong>s: DiD assumes that the <strong>composition of the groups </strong>(both treated and control) remains stable throughout the study period. If there are significant changes in the makeup of either group during the analysis (e.g., a new wave of users joins one group but not the other), this can bias the results.</li><li><strong>No Anticipation of Treatment: </strong>Finally, DiD assumes that users (or participants) do not <strong>anticipate</strong> the treatment and change their behavior before the intervention is officially implemented. If users know that a change is coming and start altering their actions beforehand, it can bias the pre-treatment outcomes, making it harder to measure the true effect.</li></ol><p>Testing the assumptions behind Difference-in-Differences is a critical step for ensuring valid results. However, covering the details of how to rigorously test these assumptions is beyond the scope of this article. I will be writing a separate blog post that will dive into these methods, providing practical steps for verifying assumptions like parallel trends and model specification. Stay tuned for that!</p><h3>How to Calculate Difference-in-Differences</h3><p>Now that we’ve covered what DiD is, why it’s important, and how to check the assumptions, let’s get into the actual mechanics of calculating DiD. There are two main ways to calculate DiD: <strong>manually</strong> using the difference of differences formula, and through a <strong>regression model </strong>(discussed in the next section), which offers more flexibility and is widely used in practice.</p><p>The manual method is straightforward and helps to solidify the concept behind DiD. The goal is to compare the <strong>change</strong> in the outcome for the treated group (first difference) with the <strong>change</strong> in the outcome for the control group (second difference).</p><p>Let’s revisit our purchase completion rate example: You’ve introduced a new checkout design for the treated group, and now you want to measure its impact. You have data on purchase completion rates before and after the redesign for both the treated and control groups.</p><p>Here’s the step-by-step process:</p><p>1. <strong>Calculate the difference for the treated group</strong>: Find the <strong>change in purchase completion rate</strong> for users who experienced the checkout redesign (the treated group).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*q-KGAy5YVcNDlL0E51Xz8w.png" /></figure><p>Let’s say the pre-redesign purchase completion rate for the treated group was 10%, and after the redesign, it increased to 15%. The change is: 15% — 10% = 5%</p><p>2. <strong>Calculate the difference for the control group</strong>: Similarly, calculate the change in the control group (users who did not get the redesign).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*j_WRpDLYnUyzmL3o8KYN4w.png" /></figure><p>If the control group’s purchase completion rate increased from 8% to 9%, the change is: 9% — 8% = 1%</p><p>3. <strong>Apply the DID formula</strong>: Now, subtract the control group’s change from the treated group’s change to isolate the effect of the intervention: d1 — d2 (refer fig 1 for more visual explanation)</p><p>Plugging in the numbers: DiD = 5% — 1% = 4%</p><p>So, the <strong>causal effect</strong> of the checkout redesign on purchase completion rates is estimated to be a 4% increase. This manual calculation is simple and intuitive, but as you work with more complex datasets, using <strong>regression analysis</strong> becomes more practical and flexible.</p><h3>Regression Form of DiD</h3><p>The manual method of DiD is straightforward and works well for simple comparisons, but when you’re working with more complex datasets and scenarios, the regression form of DiD offers several advantages. This section will walk through how the regression approach works and why it’s superior to the basic method.</p><h4><strong>The Core Concept of DiD in Regression Form</strong></h4><p>The regression model for DiD is essentially a more flexible and powerful version of the manual method. It allows you to not only estimate the treatment effect but also control for other factors that may influence the outcome. This is critical when you’re working with real-world data that often involves <strong>multiple variables</strong> and <strong>potential confounders</strong>.</p><p>Let’s break down the regression equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*B1fquczY9sRu5D0PF-FiUw.png" /></figure><p>Where:</p><ul><li>Y{it} is the outcome variable for individual (or group) i at time t (e.g., purchase completion rate.</li><li>treated{i} is a dummy variable that equals 1 if the individual/group is in the treated group, 0 if in the control group.</li><li>post{t} is a dummy variable that equals 1 if it is the post-treatment period, 0 if it is the pre-treatment period.</li><li>treated{i}*post{t} is the <strong>interaction term</strong> that captures the effect of the treatment in the post-treatment period.</li><li>𝛽3 (the coefficient of the interaction term) is the DiD estimate — the causal effect of the treatment.</li><li>ϵ is the error term, accounting for variation not explained by the model.</li></ul><h4>How It Works: A Deeper Look at the Components</h4><p>Let’s break down the components of the regression:</p><ul><li>𝛽0: This is the <strong>baseline</strong> value of the outcome (e.g., purchase completion rate) for the control group <strong>before</strong> the treatment. It serves as a reference point for all comparisons.</li><li>𝛽1: This coefficient captures the <strong>difference</strong> between the treated and control groups <strong>before</strong> the treatment. For example, if the treated group had higher purchase completion rates before the checkout redesign, 𝛽1 will quantify that difference.</li><li>𝛽2: This term measures the <strong>overall change</strong> in the outcome variable over time (i.e., from the pre-treatment to post-treatment period), across both groups. This allows the model to account for changes that would have happened even without the intervention, such as seasonal trends or external factors.</li><li>𝛽3: This is the <strong>interaction term</strong> — the heart of the DiD approach. It measures how much more (or less) the outcome changed for the treated group after the treatment, relative to the control group. This is the key term we are interested in, as it isolates the causal effect of the treatment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*bbtt-0ycqYhYKmb-W1njZQ.png" /></figure><h4>Why the Regression Approach is Better</h4><p>There are several reasons why the regression approach is more powerful and flexible compared to the basic DID method:</p><p><strong>— Control for Other Variables</strong></p><p>In real-world datasets, there are often other factors that can influence the outcome variable. The manual DiD method doesn’t account for these other factors, which can lead to biased estimates. With the regression approach, you can easily add <strong>control variables</strong> to the model to account for other influences on the outcome. The extended regression model might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*ryk6EWeg9M7npUa73WIXFg.png" /></figure><p>Where x{it} represents other control variables (e.g., user demographics), and 𝛤 (gamma) captures their influence on the outcome.</p><p><strong>— Handles Imbalance and Complex Data</strong></p><p>In many situations, the treated and control groups may not be perfectly balanced in terms of size or characteristics. The regression approach allows you to handle <strong>unequal group sizes</strong> and <strong>complex data structures</strong> much better than the manual DiD method.</p><p><strong>— Works with Multiple Time Periods</strong></p><p>In some cases, you might have data from <strong>more than two time periods</strong> — for example, several months of pre- and post-treatment data. The basic DiD method only works with two time points (before and after), but the regression approach can easily handle <strong>multiple time periods</strong> by including more <strong>Post</strong> variables or interaction terms.</p><p>For example: If you have quarterly data for a year before and after the checkout redesign, you can include time as a continuous variable or create multiple dummy variables for each time period. This allows you to track how the treatment effect evolves over time.</p><p><strong>— Offers Statistical Significance</strong></p><p>One of the most significant advantages of the regression approach is that it provides <strong>statistical inference</strong>. With regression, you can get <strong>standard errors</strong> and perform hypothesis tests to determine whether the estimated treatment effect is statistically significant. This is crucial when making decisions based on the results.</p><h3>Drawbacks of DiD: When to Be Cautious</h3><p>While Difference-in-Differences is a powerful tool for estimating causal effects, especially in situations where randomized controlled trials are not feasible, it comes with several limitations.</p><p><strong>— The Parallel Trends Assumption Can Be Hard to Verif</strong>y</p><p>The DID method rests on a critical assumption: <strong>parallel trends</strong>. This assumption means that, in the absence of treatment, the treated and control groups would have followed the <strong>same trajectory over time</strong>. If this assumption doesn’t hold, the DiD estimate will be biased.</p><p>However, <strong>testing for parallel trends</strong> is challenging because we can’t observe what would have happened to the treated group if it hadn’t received the treatment. We can compare pre-treatment trends between the treated and control groups, but this doesn’t guarantee that those trends would have remained the same in the post-treatment period. For example, in the <strong>checkout redesign</strong> example, if the treated group consisted of users who were already showing signs of increasing purchase completion rates (perhaps due to different marketing strategies), the DiD estimate would overstate the effect of the redesign.</p><p><strong>— Difficulty in Finding a Suitable Control Group</strong></p><p>A good control group should be as similar as possible to the treated group, except for the treatment itself. In practice, finding a <strong>well-matched control group</strong> can be difficult. If the control group differs systematically from the treated group in ways that affect the outcome, the DiD estimate will be biased.</p><p><strong>— Susceptibility to Time-Varying Confounders</strong></p><p>The DiD method assumes that any changes in the outcome over time are either due to the treatment or due to general time trends that affect both groups equally. However, in the real world, there can be <strong>time-varying confounders</strong> — factors that change over time and affect the treated and control groups differently. For example, suppose a marketing campaign was launched simultaneously with the checkout redesign, but it only targeted users in the treated group. The effect of the campaign would be mixed with the effect of the redesign, making it impossible to disentangle the two. As a result, the DID estimate would be biased.</p><p><strong>— Handling Non-Linear Relationships and Heterogeneous Treatment Effects</strong></p><p>The basic DiD model assumes that the <strong>treatment effect is constant</strong> across all individuals in the treated group. In reality, treatment effects are often <strong>heterogeneous</strong> — some individuals may respond more strongly to the treatment than others. The basic DiD model doesn’t capture this variation and might provide an overly simplistic view of the treatment effect.</p><p>Additionally, DiD assumes a <strong>linear relationship</strong> between time and the outcome variable, which might not hold in all cases. If the relationship is <strong>non-linear</strong> (e.g., the outcome variable grows exponentially over time), the DID estimate might be misleading.</p><p><strong>— Sensitivity to the Timing of the Treatment</strong></p><p>DiD works best when there’s a <strong>clear and well-defined treatment period.</strong> If the treatment is staggered (e.g., introduced to different users at different times) or its effects take time to manifest, the basic DiD model might not be appropriate. For example, if the checkout redesign is gradually rolled out over several months, the users who received the redesign early might behave differently from those who received it later, due to factors like seasonality or changing market conditions. In such cases, you would need to use more advanced methods, like <strong>event study models</strong>, to account for the staggered treatment timing.</p><p>— <strong>Spillover Effects</strong></p><p>DiD assumes that the treatment affects only the treated group and doesn’t spill over into the control group. In practice, <strong>spillover effects</strong> are common, particularly in social or economic settings where people interact. For example, in the checkout redesign case, users in the control group might hear about the redesign from others or find workarounds to experience the new design themselves (e.g., by creating a new account). If this happens, the control group’s behavior could be influenced by the treatment, which would bias the DiD estimate.</p><h3>Conclusion</h3><p>Difference-in-Differences is a powerful technique for estimating causal effects from observational data, especially when randomized controlled trials aren’t possible. It’s widely used in fields ranging from <strong>economics</strong> to <strong>product analytics</strong> to assess the impact of interventions like policy changes, product launches, and process improvements. By comparing trends between treated and control groups before and after an intervention, DiD helps to isolate the true effect of the treatment.</p><p>However, like any method, DiD comes with certain assumptions and limitations. The <strong>parallel trends assumption</strong>, in particular, can be difficult to satisfy in practice. Additionally, DiD might not perform well if there are <strong>spillover effects</strong>, <strong>time-varying confounders</strong>, or <strong>non-linear relationships </strong>in the data. These limitations highlight the importance of carefully considering the context and structure of your data before relying on DiD results.</p><p>That said, the <strong>regression form of DiD</strong> provides a more flexible and robust approach to account for additional complexities in the data. It allows you to control for other variables, handle imbalanced datasets, and generate statistical inferences, which makes it a valuable tool in the hands of data scientists and product analysts.</p><p>If you enjoyed this blog and want to read more about data science, experimentation, and causal inference, feel free to follow my work here. You can also connect with me on <a href="https://www.linkedin.com/in/surajbansal28/">LinkedIn</a> to stay updated on the latest insights and discussions!</p><h3>References</h3><ul><li>Angrist and Pischke (2008). Mostly Harmless Econometrics: An Empiricist’s Companion. Princeton University Press.</li><li>How to Accurately Test Significance with Difference in Difference Models, <a href="https://engineering.atspotify.com/2023/09/how-to-accurately-test-significance-with-difference-in-difference-models/">Spotify</a></li><li>Causal Inference for the Brave and True, <a href="https://matheusfacure.github.io/python-causality-handbook/15-Synthetic-Control.html">Matheus Facure</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fff74eba3a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Synthetic Control and Causal Inference in A/B Testing]]></title>
            <link>https://medium.com/@suraj_bansal/understanding-synthetic-control-and-causal-inference-in-a-b-testing-e10e67d570a0?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/e10e67d570a0</guid>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[causal-data-science]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[synthetic-control]]></category>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 11:36:01 GMT</pubDate>
            <atom:updated>2024-10-02T15:05:16.491Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, companies are constantly running experiments to improve their products and services. Traditional A/B testing is widely used to measure the impact of changes, but it can fall short in complex environments where interventions spill over between groups or external factors skew results. This is where synthetic control comes into play.</p><p>Synthetic control is an advanced statistical technique that allows for the precise estimation of causal effects, even in the presence of confounding factors like trends or seasonality. It’s a powerful tool actively used by leading companies such as Google, Microsoft, Meta, Amazon to run experiments at scale. These tech giants leverage synthetic control to evaluate interventions when randomized controlled trials are either impractical or expensive, making it an essential strategy for optimizing product performance and making data-driven decisions.</p><p>This article will dive into what synthetic control is, why it’s needed, how it works, and the potential drawbacks to consider when applying it in real-world scenarios. Whether you’re a data scientist, product analyst, or product manager, understanding synthetic control can help you run more effective experiments and draw better insights from your data.</p><p>By the end, you’ll have a clear understanding of whether synthetic control is the right fit for your product experiments — and how it can elevate the quality of your insights.</p><h3>Why is Synthetic Control Needed in A/B Testing?</h3><p>A/B testing is widely used to measure the impact of a product change or intervention, but sometimes it falls short due to unintended consequences, especially when external factors affect the control group. A great example of this can be seen in ride-hailing companies like Uber, where an intervention in the driver app might not only affect the treatment group but also spill over into the control group — leading to biased results.</p><p>Imagine Uber wants to test whether “showing the destination of a ride request” to drivers before they accept the trip decreases post acceptance cancellation and increases revenue per driver (assuming long rides pay better). In this test, the treatment group sees the destination, while the control group does not. Drivers in the treatment group, knowing where the rider is headed, might be more likely to accept longer trips, which typically yield better earnings. As a result, drivers in the control group may end up with more short-distance trips, offering fewer earning opportunities.</p><p>Here’s where things get tricky: because the drivers in the treatment group are cherry-picking long-distance rides, the control group is left with a skewed set of trips — mostly short ones. These drivers would have earned more had there been no intervention at all, leading to biased estimates of the intervention’s true impact. What’s worse, this spillover effect distorts the control group’s earnings potential, making it difficult to measure the real difference between the two groups. As a result, the A/B test fails to capture the true impact of the intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bpfyNRU48ik8Z5P42aqUg.png" /><figcaption>Biased Results due to the Spillover Effect</figcaption></figure><h4>Why “Before and After” Analysis Falls Short</h4><p>One might be tempted to use a before and after analysis to measure the effect of showing ride destinations to drivers. However, this approach has its own set of pitfalls. In fast-moving markets like ride-hailing, external factors such as seasonality, market trends, or competitor actions can heavily influence driver behavior and rider demand. For instance, demand may naturally fluctuate depending on the time of year, ongoing promotions, or even traffic patterns. Because of this, comparing metrics from a period before the intervention to a period after won’t give an accurate measure of the effect — it’s impossible to know if the change is due to the intervention or these external factors.</p><h4>The Geo-Testing Approach</h4><p>One common solution to address these issues is geo-testing, where the treatment and control groups are divided geographically. For example, Uber might roll out the change in City A (treatment group) and leave City B (control group) untouched to measure the difference in average earning per driver. While this can avoid spillover effects, geo-testing introduces its own challenges.</p><p>For geo-testing to work, you need two cities that behave very similarly in terms of rider demand, trip lengths, and driver behavior — an extremely difficult task. Different cities have different traffic patterns, customer demographics, and economic conditions, making it challenging to find a true match. What works in City A might not apply to City B, and any differences in performance might be more about city characteristics than the intervention itself. This limits the accuracy of geo-testing as a reliable method.</p><h4>Why Randomization Across Cities Isn’t Always Feasible</h4><p>Another approach could be to randomize the intervention across multiple cities, spreading the treatment and control groups across diverse regions to minimize the risk of external influences. This method, while reducing bias, can be a costly and complex intervention to run, especially for large-scale tests. Randomizing across cities requires extensive planning, a higher level of operational complexity, and significant financial investment — making it impractical for many companies to implement right from the start.</p><p>Thus, the need for a better approach becomes clear. A method that can control for these external factors while avoiding costly and logistically challenging interventions is where synthetic control comes in, offering a more reliable, data-driven solution to many of the limitations mentioned above.</p><h3>How Does Synthetic Control Work?</h3><p>Building on the ride-hailing example, where Uber tests the impact of showing ride destinations to drivers in one city, synthetic control offers a method for constructing a reliable comparison group. Instead of relying on traditional A/B testing or geo-testing, a synthetic control is created for the city where the intervention occurs, allowing for a more accurate measurement of the intervention’s effect.</p><h4>The Core Concept of Synthetic Control</h4><p>In synthetic control, the objective is to build a synthetic version of the treated city using a weighted combination of other cities that did not receive the intervention. This synthetic control group is designed to closely mimic what would have happened in the treated city if the intervention had not taken place. By comparing the outcomes of the treated city with the synthetic control after the intervention, the effect of the intervention can be isolated more effectively.</p><h4>Step-by-Step Explanation</h4><p>Consider the intervention: Uber decides to show ride destinations to drivers in City A. Instead of comparing City A to just one control city, several cities are used to construct a synthetic control.</p><ol><li>Selecting the Donor Pool: A group of cities that did not receive the intervention is chosen, referred to as the donor pool. These cities (B, C, D, and others) serve as potential contributors to the synthetic control.</li><li>Time Series Data: Data is collected for each city in the donor pool during the same pre-intervention period. Each city is treated as a column, and the rows represent time periods (e.g., weeks or months) before the intervention. The same data is gathered for City A to ensure that pre-intervention trends are captured.</li><li>Constructing the Synthetic Control: The goal is to create a weighted combination of cities from the donor pool that closely matches City A’s behavior before the intervention. For example, the synthetic control might be: <em>Synthetic Control = 0.5* City B + 0.3 * City C + 0.2 * City D. </em>Each city in the donor pool is assigned a weight based on its similarity to City A during the pre-intervention period. The idea is to replicate the pre-intervention behavior of City A as closely as possible.</li><li>Post-Intervention Comparison: After constructing the synthetic control, the performance of City A after the intervention (e.g., average revenue per driver) is compared to that of the synthetic control. Any differences between the two are attributed to the intervention, as the synthetic control reflects what would have happened in City A without the treatment.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4kUnEujI4Liy5Ax3Jv8fA.png" /></figure><h4>Difference from Traditional Linear Regression</h4><p>While synthetic control may sound similar to traditional linear regression, there are key differences:</p><ul><li>In linear regression, cities are typically treated as rows, and various characteristics (such as population, weather, or trip length) are treated as columns. The model assigns a coefficient to each variable to predict an outcome.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Uw5gaOrANYpL2yQWnniH_g.png" /><figcaption>Traditional Linear Regression</figcaption></figure><ul><li>In synthetic control, the cities themselves are treated as columns, and the time periods before the intervention serve as rows. The aim is to assign weights to cities (columns) to express the treated city as a linear combination of other cities over time. Instead of predicting an outcome based on variables, the method builds a synthetic version of the treated city based on the trends of the donor cities.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*groRZCmvHb3VJxxRV6wT-A.png" /><figcaption>Regression for Synthetic Control</figcaption></figure><p>The goal of regression in this context is to create a combination of donor cities that closely matches the outcome metrics of the treated city before the intervention. This is done by finding the right weights for each city, similar to how regression finds coefficients for variables.</p><p>The objective is not just to combine cities but to minimize the loss function — the difference between the actual outcome in the treated city and the weighted combination of outcomes from the donor cities. Specifically, a loss function is used to measure how well the synthetic control replicates the treated city’s pre-intervention behavior. By minimizing this loss, the synthetic control becomes as close as possible to what the treated city would have looked like if there had been no intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nsy4NR6-elY6dJ9H0b-Aw.png" /><figcaption>Linear Regression for Synthetic Control</figcaption></figure><p>The above equation shows how to combine cities in the control group by taking a weighted average of their outcomes. Specifically, <em>Yt,pre</em> represents the outcome of the treated city during the pre-treatment period, <em>beta</em> refers to the coefficients (or weights) that need to be learned, and <em>Xc,pre</em> represents the outcomes of the control cities during the pre-treatment period. The goal is to minimize the loss function to create a synthetic control that closely resembles the treated city before the intervention. This process ensures that the synthetic control behaves similarly to the treated unit, forming a valid counterfactual for comparison post-intervention.</p><h4>Using Restricted Weights: Avoiding Overfitting</h4><p>One common variation of synthetic control involves the use of restricted weights. Without restrictions, the model may overfit the data by assigning disproportionately high weights to one or two cities, leading to unrealistic or biased synthetic controls. For example, the model might heavily weight City B while under weighting others, making the synthetic control less accurate and potentially biased.</p><p>To avoid overfitting, constraints are applied to the weights. These constraints ensure that the synthetic control remains balanced and interpretable. For instance, non-negative weights may be enforced to prevent any city from receiving a negative contribution, and the sum of weights across different cities (donor units) must be 1. This ensures that the synthetic control reflects a realistic blend of cities, rather than being overly influenced by a single location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AgCKbWwP1nnuMSFDyB4VA.png" /><figcaption>Linear Regression for Synthetic Control with Restricted Weights</figcaption></figure><p>Using restricted weights helps produce a synthetic control that is more robust and easier to interpret, reducing the risk of overfitting while providing clearer insights into how the cities in the donor pool contribute to the outcome.</p><p>This method offers a more accurate alternative to traditional A/B testing and geo-testing by creating a synthetic control that mimics the pre-intervention trends of the treated city, thus providing a clearer measure of the intervention’s effect.</p><h3>Statistical Significance in Synthetic Control</h3><p>After constructing the synthetic control and observing the difference between the treated unit (e.g., City A) and its synthetic counterpart post-intervention, it’s crucial to determine whether this difference is statistically significant. In other words, is the observed effect due to the intervention, or could it have occurred by chance? This is where randomization and p-value calculation come into play.</p><h4>Randomization and the Placebo Test</h4><p>To assess the statistical significance of the results in synthetic control, a common approach is the placebo test through randomization. The basic idea is to repeat the synthetic control process for other cities that did not receive the intervention, as if they had. This helps evaluate how often the observed effect could occur purely by chance.</p><p>Here’s how the process works:</p><ol><li>Synthetic Control for Non-Treated Units: After observing the difference between the treated city (City A) and its synthetic control, the same method is applied to other cities in the donor pool that didn’t receive the intervention. For each of these cities, a synthetic control is constructed using the remaining donor cities.</li><li>Simulating the Intervention for Control Units: For each of these non-treated cities, a placebo intervention is introduced at the same time that the real intervention occurred in City A. The difference between these cities and their respective synthetic controls after the placebo intervention is calculated in the same way it was done for City A.</li><li>Distribution of Placebo Effects: After calculating the post-intervention differences for the placebo cities, a distribution of these placebo effects is created. This distribution represents the range of differences that could have occurred by chance in cities that did not receive the actual intervention.</li><li>Calculating the p-value: The p-value is then calculated by comparing the real effect observed in the treated city (City A) to the placebo distribution. Specifically, the p-value represents the proportion of placebo effects that are equal to or larger than the observed effect in City A.</li></ol><p>p-value = Number of placebo effects greater than or equal to observed effect/Total number of placebo effects.</p><p>A small p-value (typically below 0.05) suggests that the observed difference is unlikely to have occurred by chance, meaning the intervention likely had a statistically significant impact. If the p-value is large, it indicates that the observed effect could easily have happened by chance, and the results are not statistically significant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*VpvFezRtjNlRemOHGjw1Bw.png" /></figure><h4>How Iterating Over Different Cities Helps Calculate p-values</h4><p>This process of iterating over different cities helps understand the p-value calculation. By repeating the synthetic control process for cities that did not receive the intervention, it’s possible to simulate what could have happened in a world where no intervention occurred. These placebo cities create a baseline for comparison, showing the natural variations in the outcome metric across cities without the treatment.</p><p>When the true effect for the treated city (City A) is compared against this baseline distribution, it becomes clear how exceptional or common the observed effect is. If the treated city’s effect stands out significantly from the placebo effects, it indicates that the intervention likely had a real impact. This method grounds the p-value calculation in a real-world context, making it easier to see whether the observed result is truly meaningful or could simply arise by chance.</p><h4>Interpreting the Results</h4><p>The randomization-based placebo test provides a robust way to assess whether the intervention truly caused the observed effect. By simulating the intervention across multiple non-treated cities, it becomes possible to account for natural variations in the data and establish a threshold for significance.</p><p>For example, if City A shows a large difference between its actual post-intervention metrics and the synthetic control, and only a few placebo cities exhibit differences of similar magnitude, the p-value will be low, supporting the hypothesis that the intervention was effective. Conversely, if many placebo cities show large differences similar to the treated city, the p-value will be high, indicating that the observed effect could easily have occurred by chance.</p><h4>Advantages of Randomization for Significance Testing</h4><p>The randomization-based approach offers several advantages:</p><ul><li>Non-parametric: This method doesn’t require strong assumptions about the distribution of the data, unlike many traditional statistical tests. It works directly with the observed data and provides an empirical measure of significance.</li><li>Flexibility: The placebo test can be applied in various contexts, regardless of the specific metrics being measured, making it a versatile tool for evaluating the significance of synthetic control results.</li><li>Intuitive Interpretation: The comparison between the treated city and the placebo cities makes it easier to understand whether the observed effect is truly exceptional or something that could occur by chance.</li></ul><h3>Potential Drawbacks of Synthetic Control</h3><p>While synthetic control is a powerful and innovative method for estimating causal effects in A/B testing, it comes with certain limitations that should be considered. These drawbacks can affect both the practicality and accuracy of the approach in real-world scenarios.</p><ul><li>Availability of Suitable Donor Units: One of the primary challenges with synthetic control is the need for a robust donor pool of control units (e.g., cities, regions, or other test groups). If the donor cities do not closely resemble the treated city in terms of pre-intervention trends and other relevant characteristics, it becomes difficult to construct an accurate synthetic control. This can result in biased or unreliable estimates. In cases where there are not enough similar cities to create a balanced synthetic control, the method may fail to produce meaningful results.</li><li>Overfitting: While synthetic control typically uses weights to combine cities from the donor pool, there is a risk of overfitting — especially if the algorithm assigns disproportionately high weights to a small subset of cities that happen to match the treated city’s pre-intervention behavior. This can lead to a synthetic control that is overly tailored to the pre-intervention data but does not generalize well to the post-intervention period. Although constraints on weights (such as limiting weights to be non-negative) can reduce overfitting, this issue still poses a challenge, particularly in complex cases where the number of control units is limited.</li><li>Sensitivity to Changes in the Donor Pool: Another limitation of synthetic control is its sensitivity to shifts or changes in the donor pool<strong> </strong>over time. The method relies on the assumption that the relationship between the treated city and the donor cities remains consistent from the pre-treatment to the post-treatment period. However, any significant changes in the donor cities — such as economic shifts, policy changes, or external shocks — can lead to incorrect estimates. If the donor cities start behaving differently compared to the pre-treatment period, the synthetic control constructed from their outcomes may no longer accurately represent the counterfactual scenario, resulting in biased or unreliable treatment effect estimates.</li><li>Inability to Capture Individual-Level Treatment Effects: Another limitation of synthetic control is that it provides only an average treatment effect across the treated unit (such as a city or region) rather than at the individual level. This means that while the method can estimate the overall impact of an intervention on a group (e.g., City A in the ride-hailing example), it cannot capture how different individual users or drivers are affected. For businesses that require granular insights — such as the effects on specific segments of users or regions within the treated city — this lack of individual-level data may limit the depth of analysis. This contrasts with randomized controlled trials, which can estimate treatment effects at both the group and individual level</li></ul><h3>Conclusion</h3><p>Synthetic control offers a sophisticated and reliable approach for estimating causal impacts in A/B testing, especially in scenarios where traditional methods like randomization are difficult or costly to implement. By constructing a weighted combination of control units, synthetic control provides a counterfactual that allows for accurate estimation of the treatment effect, even in complex environments with multiple confounding factors, such as trends and seasonality.</p><p>This method is particularly useful for cases where interventions might spill over between groups or when data from randomized trials are hard to obtain. It allows organizations to gain insights into the effects of interventions at a larger scale while addressing potential biases inherent in traditional A/B testing methods.</p><p>However, synthetic control has its limitations. Its effectiveness relies on the availability of high-quality data and similar control units. It also provides an average treatment effect across a population rather than individual-level insights, making it less suitable for granular user analysis. Additionally, computational complexity and susceptibility to overfitting are challenges that need to be managed carefully.</p><p>Despite these limitations, synthetic control remains a powerful tool in the data scientist’s toolkit, offering a way to derive meaningful, statistically significant insights in challenging experimental environments. With careful application and consideration of its drawbacks, it can significantly enhance decision-making in fields ranging from ride-hailing to online platforms and beyond.</p><p>If you enjoyed this blog and want to read more about data science, experimentation, and causal inference, feel free to follow my work here. You can also connect with me on <a href="https://www.linkedin.com/in/surajbansal28/">LinkedIn</a> to stay updated on the latest insights and discussions!</p><h4>References</h4><ul><li><a href="https://www.aeaweb.org/articles?id=10.1257%2Fjel.20191450">Synthetic Control Group Method for Comparative Case Studies</a></li><li><a href="https://www.youtube.com/watch?v=j5DoJV5S2Ao">Uber’s Synthetic Control — Case Study</a></li><li><a href="https://matheusfacure.github.io/python-causality-handbook/15-Synthetic-Control.html">Causal Inference for the Brave and True by Matheus Facure</a></li><li><a href="https://towardsdatascience.com/understanding-synthetic-control-methods-dd9a291885a1">Understanding synthetic control methods</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e10e67d570a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing Gone Wrong: How to Avoid Common Mistakes & Misinterpretations]]></title>
            <link>https://medium.com/@suraj_bansal/pitfalls-and-mistakes-in-a-b-tests-4d9073e17762?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9073e17762</guid>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[onlinetesting]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 04:15:04 GMT</pubDate>
            <atom:updated>2024-06-19T18:31:17.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A/B testing, also known as split testing, is a cornerstone of data-driven decision-making. It’s a powerful tool that enables businesses to compare two versions of a webpage, app feature, or marketing campaign to determine which one performs better. By randomly assigning users to either the control group (A) or the variant group (B), product managers, data scientists, and marketers can gain valuable insights into user behavior and optimize their products and services.</p><p>The allure of A/B testing lies in its potential to boost key metrics like click-through rates (CTR), conversion rates, user engagement, and ultimately, revenue. However, the path to A/B testing success is fraught with potential pitfalls. Even experienced teams can fall prey to common mistakes that can undermine the validity and reliability of their experiments.</p><p>If you’re looking to unlock the full potential of A/B testing and avoid costly missteps, you’ve come to the right place. In this blog post, we’ll delve into the hidden pitfalls that can sabotage your A/B tests and provide you with actionable strategies to overcome them. If you want to go deeper into the basics of A/B testing and experimental design, check out my <a href="https://medium.com/@suraj_bansal/a-b-testing-unleashed-the-ultimate-guide-to-making-data-driven-decisions-f9b998c43472">first blog</a> in this series.</p><p>Join us as we navigate the A/B testing landscape, identifying the common mistakes that can derail your experiments and equipping you with the knowledge to master this invaluable tool for data-driven optimization.</p><h3>Pitfalls and Mistakes to Avoid: Navigating the A/B Testing Minefield</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnlUhK2MhpVaQGd7jOeu9g.jpeg" /></figure><p>A/B testing isn’t foolproof. Even with the best intentions and meticulous planning, there are common pitfalls that can derail your experiments and lead to misleading results. Let’s explore some of these potential hazards and learn how to steer clear of them:</p><h4>1. The Peeking Problem: Resisting the Temptation of Early Results</h4><p>Imagine you’re baking a cake and keep opening the oven door to check on it. Each time you open the door, you release heat and disrupt the baking process. The same principle applies to A/B testing. Peeking at your results before the experiment has run its course can introduce bias and invalidate your findings.</p><p>Early in an A/B test, results are often unreliable due to small sample sizes and random fluctuations in user behavior. Making decisions based on this incomplete data can be like chasing a mirage in the desert — it appears real but is ultimately an illusion. This is why understanding A/B testing statistical significance is crucial for data-driven decision making.</p><p>For instance, imagine an e-commerce site testing a new exit-intent pop-up offering a discount. A few days into the test, the pop-up seems to be boosting conversions, prompting a site-wide rollout. But weeks later, conversions decline as users grow weary of the constant interruption. This is a classic example of the peeking problem leading to a misguided decision, highlighting the importance of avoiding A/B testing mistakes<strong> </strong>that can derail your optimization efforts.</p><p>Acting on misleading early data can have costly consequences. You might prematurely implement a change that initially seemed promising but ultimately fails to deliver, wasting valuable resources and potentially harming your product’s performance. Conversely, you might discard a potentially winning variation based on a temporary dip in performance, missing out on significant optimization opportunities.</p><p>To avoid falling prey to the peeking problem and ensure accurate A/B test analysis, follow these key steps:</p><p><strong>1. Statistical Power Calculation:</strong> Before you launch your A/B test, determine the minimum sample size needed to achieve statistical significance. This ensures you have enough data to draw reliable conclusions. If you don’t know how to do it, please refer to my previous blog where it is explained in detail.</p><p><strong>2. Set a Predetermined Test Duration:</strong> Decide on a fixed test duration in advance and commit to it. Resist the urge to peek at the results before the test is complete. This might require some discipline, but it’s essential for accurate results.</p><p><strong>3. Use a Statistical Significance Calculator:</strong> These tools help you determine whether your results are statistically significant or simply due to chance. Don’t declare a winner until you’ve reached a predetermined level of confidence.</p><p>By exercising patience and adhering to a well-defined testing plan, you can ensure that your A/B testing decisions are based on solid data, not fleeting illusions, leading to true optimization and growth.</p><h4>2. The Multiple Testing Problem: When Too Much Testing is a Bad Thing</h4><p>Imagine flipping a coin ten times. The probability of getting heads at least once is much higher than the probability of getting heads on a single toss. Similarly, when you run multiple A/B tests, the chance of finding at least one statistically significant result by pure chance increases. This is known as the multiple testing problem or the “look elsewhere effect.”</p><p>In simpler terms, the more tests you run, the more likely you are to find a “false positive” — a result that appears significant but is actually due to random chance. This can lead to implementing changes that don’t truly improve your metrics, wasting time and resources.</p><p><strong>How to Handle Multiple Testing — </strong>There are several strategies to mitigate the multiple testing problem:</p><p><strong>1. Bonferroni Correction: </strong>The Bonferroni correction adjusts the significance level to account for the number of tests. If you conduct k tests, you divide the significance level α by k:</p><p>adjusted α = α/k</p><p>For example, if you’re running 10 tests and your desired significance level is 0.05, the adjusted significance level for each test would be:</p><p>adjusted α = 0.05/10 = 0.005</p><p>This method is simple but can be overly conservative, especially when the number of tests is large, leading to a higher Type II error rate (false negatives).</p><p><strong>2. False Discovery Rate (FDR): </strong>The False Discovery Rate (FDR) approach controls the expected proportion of false positives among the rejected hypotheses. The Benjamini-Hochberg procedure is a common method for controlling FDR:</p><ul><li>Sort the p-values of all tests in ascending order.</li><li>For each p-value pi, calculate the threshold (i*α)/k, where i is the rank of the p-value and k is the total number of tests.</li><li>Identify the largest p-value pi that is less than or equal to its corresponding threshold.</li><li>Reject all hypotheses with p-values less than or equal to pi.</li></ul><p>The FDR approach is less conservative than the Bonferroni correction and is particularly useful when dealing with a large number of tests.</p><p>The best approach for handling multiple testing will depend on your specific situation and goals. By understanding the multiple testing problem and taking steps to address it, you can ensure that your A/B testing results are reliable and actionable, leading to truly impactful changes for your business.</p><h4>3. Novelty and Primacy Effects: The Double-Edged Sword of Newness</h4><p>When you introduce a new variation in an A/B test, you’re not just testing the change itself, but also the inherent human biases that come with it. Two key biases to watch out for are:</p><ol><li><strong>Novelty Effect:</strong> The tendency for new things to spark initial interest and engagement simply because they’re new. This can create a temporary boost in performance for the treatment group, leading to overly optimistic results if the test isn’t run long enough.</li><li><strong>Primacy Effect:</strong> The tendency to remember and favor the first experience or piece of information encountered. In an A/B test, this can lead to an unfair advantage for the control group, as users might be more familiar with the existing version and therefore more likely to stick with it.</li></ol><p><strong>Mitigating the Novelty and Primacy Effects — </strong>To ensure your A/B test results are accurate and actionable, you need to mitigate these biases:</p><ol><li><strong>Extend Experiment Duration:</strong> Don’t rush to conclusions based on initial results. Allow your test to run long enough for the novelty effect to wear off and for users to adjust to the new variation. A good rule of thumb is to run your test for at least two weeks, or even longer if you have lower traffic volume.</li><li><strong>Segment Your Audience:</strong> Analyze your results by different user segments (e.g., new vs. returning users, different demographics) to see if the novelty or primacy effects are more pronounced for certain groups. This can help you tailor your interpretation of the results and make more informed decisions.</li><li><strong>Focus on Long-Term Metrics:</strong> Don’t just look at immediate changes in metrics. Track long-term trends to see if the initial lift in performance due to novelty is sustained over time. This is crucial for determining the true impact of your change.</li></ol><p>By being aware of the novelty and primacy effects and taking steps to mitigate them, you can ensure that your A/B test results accurately reflect the impact of your changes and lead to data-driven decisions that drive real business value.</p><h4>4. Ignoring the Stable Unit Treatment Value Assumption (SUTVA): The Hidden Assumption That Can Derail Your Results</h4><p>Amidst the excitement of designing and analyzing A/B tests, there’s a crucial assumption lurking in the background that often goes unnoticed but plays a vital role in the validity of your results: the Stable Unit Treatment Value Assumption (SUTVA).</p><p><strong>What is SUTVA? </strong>In simple words, this assumption states that the treatment (the change you’re testing) applied to one user should not influence the behavior or outcomes of other users. If this assumption is violated, your test results can become invalidated, leading you to draw incorrect conclusions.</p><p><strong>Understanding the Ripple Effect:</strong> Think of it like this: you’re testing a new on-boarding flow for your mobile app. You randomly assign half of your new users to the control group (the existing flow) and half to the variant group (the new flow). However, if users in the variant group start sharing their positive experiences with friends in the control group, those friends might become more likely to complete the on-boarding process, even though they weren’t exposed to the new flow themselves. This “spillover effect” violates SUTVA and contaminates your results.</p><p>SUTVA violations are particularly common in online platforms where users interact with each other:</p><ul><li><strong>Social Networking Websites:</strong> Imagine you’re testing a new feature that encourages users to share more content. If users in the treatment group start sharing more, their friends in the control group might also see and share more content, even though they weren’t directly exposed to the new feature. This interference between groups violates SUTVA, making it difficult to isolate the true impact of the feature.</li><li><strong>Two-Sided Marketplaces :</strong> Consider a ride-sharing platform like Uber, the SUTVA could be violated if a promotional discount is offered to riders in a specific area. For instance, if the promotion attracts more riders to the platform, it may affect the availability of drivers, leading to longer wait times for users not receiving the discount. This spillover effect, where the treatment of one group (discounted riders) impacts the outcomes of another group (non-discounted riders), violates the assumption that the treatment of one unit should not affect the outcomes of another.</li></ul><p><strong>Safeguarding Against SUTVA Violations — </strong>Fortunately, there are strategies to mitigate the risks:</p><ol><li><strong>Cluster Randomization:</strong> Instead of assigning individuals randomly, you can randomize groups (e.g., schools, cities). This helps reduce interference, as individuals within a cluster are more likely to interact.</li><li><strong>Isolate Test Groups:</strong> Whenever possible, try to isolate your test groups so that users in one group don’t influence those in another. This might involve using different platforms, channels, or time periods for each group.</li><li><strong>Stagger Roll-outs:</strong> If complete isolation isn’t feasible, consider a staggered rollout of your test. Start with a small percentage of users and gradually increase it over time, monitoring for any signs of spillover effects.</li></ol><p>By understanding the importance of SUTVA and taking steps to mitigate interference between test groups, you can ensure that your A/B tests yield accurate, actionable results. Remember, the goal of A/B testing is to isolate the impact of a specific change, and violating SUTVA can undermine this objective</p><h4>5. Sample Ratio Mismatch (SRM): When Your Groups Aren’t So Equal After All</h4><p>Imagine you’re conducting an A/B test with a 50/50 split between the control and treatment groups. You expect roughly half of your users to be in each group. But what if, as your experiment runs, you notice a significant deviation from this expected ratio? This is known as Sample Ratio Mismatch (SRM), and it can wreak havoc on your A/B test results.</p><p><strong>What Causes SRM?</strong> SRM can be caused by various factors, including:</p><ul><li><strong>Technical Issues:</strong> Errors in your experimentation platform, bugs in your code, or problems with data collection can lead to uneven distribution of users between groups.</li><li><strong>Bot Traffic:</strong> Automated bots can skew your results if they are not properly filtered out.</li><li><strong>User Behavior:</strong> In some cases, users might behave in ways that inadvertently lead to SRM. For example, if users in one group are more likely to clear their cookies, they might be re-randomized, causing an imbalance.</li></ul><p><strong>Why SRM is a Problem? </strong>SRM is a problem because it violates the assumption of randomization, which is essential for the validity of your A/B test. If your groups aren’t equally sized or representative of your target population, any observed differences in metrics might not be due to the treatment itself but rather to the inherent differences between the groups.</p><h4>How to Detect and Address SRM</h4><ol><li><strong>Monitor Your Sample Ratio:</strong> Regularly check the actual distribution of users between your control and treatment groups. If you notice a significant deviation from the expected ratio, investigate the cause.</li><li><strong>Statistical Tests:</strong> There are statistical tests (e.g., chi-squared test) that can help you determine whether an observed SRM is statistically significant.</li><li><strong>Adjust Traffic Allocation:</strong> If your testing platform allows, you can dynamically adjust the percentage of traffic allocated to each group to maintain a more balanced distribution.</li><li><strong>Extend Test Duration:</strong> If adjusting traffic allocation isn’t feasible or doesn’t fully resolve the issue, consider extending the test duration. This will give you more time to accumulate data and achieve a more balanced sample size.</li></ol><p>If you can’t correct the SRM, interpret your results with caution, as the imbalance might have influenced your findings. By being vigilant about SRM and taking appropriate measures to address it, you can ensure the integrity of your A/B tests and make confident data-driven decisions.</p><h3>Conclusion</h3><p>A/B testing is an invaluable tool in the data-driven optimizer’s toolkit. It empowers you to make informed decisions, enhance user experiences, and drive business growth. However, as we’ve explored, the path to A/B testing success is not without its challenges. By understanding and proactively addressing these common pitfalls — the peeking problem, multiple testing issues, novelty and primacy effects, SUTVA violations, and sample ratio mismatches — you can elevate your experimentation game and achieve more reliable, impactful results.</p><p>Remember, A/B testing is not a one-and-done activity but an ongoing process of learning and refinement. In our next blog post, we’ll delve into advanced A/B testing techniques, such as Bayesian testing and causal inference, that can further enhance your experimentation capabilities. Follow me for more insights and actionable advice to help you become an A/B testing maestro!</p><p>If you have any questions or would like to discuss A/B testing in more detail, feel free to connect with me on <a href="https://www.linkedin.com/in/surajbansal28/">LinkedIn</a>. Let’s continue the conversation and unlock the full potential of data-driven optimization together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9073e17762" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing Unleashed: The Ultimate Guide to Making Data-Driven Decisions]]></title>
            <link>https://medium.com/@suraj_bansal/a-b-testing-unleashed-the-ultimate-guide-to-making-data-driven-decisions-f9b998c43472?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9b998c43472</guid>
            <category><![CDATA[onlinetesting]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[experiment-design]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 04:18:39 GMT</pubDate>
            <atom:updated>2024-10-02T15:06:23.169Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Vfb3G8dq_PzMiDs1oRD5ww.jpeg" /></figure><p>Remember how you can still see likes on YouTube videos, but dislikes have vanished? That wasn’t a random change. It was a calculated move by Google, a testament to how data-driven companies continuously refine their platforms through A/B testing.</p><p>But what exactly is A/B testing, and why should <em>you</em> care?</p><p>Imagine having a crystal ball that reveals how users will react to your website, app, or product changes. That’s the power of A/B testing. It’s the scientific method applied to decision-making, empowering businesses of all sizes to optimize their offerings based on real user behavior.</p><p>Whether you’re a seasoned marketer, a data scientist, a budding product manager, or simply curious about data-driven decision making, A/B testing is a game-changer. It’s the key to unlocking valuable insights that can transform your approach to product optimization, marketing campaigns, and overall business strategy.</p><p>By the end of this comprehensive guide, you’ll feel confident enough to not only run A/B tests yourself but also explain the process and results to stakeholders with clarity and conviction. We’ll take you from A/B testing novice to expert, covering everything from the fundamental concepts to the nuances of experimental design and analysis.</p><p>Get ready to unlock the secrets behind successful A/B testing, and discover how this powerful tool can transform your approach to product optimization, marketing campaigns, and overall business strategy. It’s time to ditch the guesswork and embrace the scientific method for success.</p><p>Stay tuned for our upcoming blog posts where we’ll dive deeper into the world of A/B testing, exploring advanced techniques like bandit algorithms, causal inference and sequential testing, as well as common pitfalls and mistakes to avoid!</p><p>So, buckle up and get ready to unlock the power of data-driven decision-making with A/B testing!</p><h3><strong>Why A/B Testing is a Superpower for Decision Makers</strong></h3><p>Imagine launching a new feature or marketing campaign with the confidence that it’s going to be a hit. A/B testing gives you that superpower. It replaces guesswork and intuition with hard data, enabling you to make decisions based on evidence rather than gut feeling. Here’s why A/B testing should be an essential tool in your decision-making arsenal:</p><ol><li><strong>Data-Driven Decisions:</strong> In the age of big data, there’s no excuse for relying on hunches. A/B testing allows you to gather concrete evidence of what works and what doesn’t, eliminating the risk of costly mistakes.</li><li><strong>Continuous Improvement:</strong> A/B testing fosters a culture of experimentation and iterative refinement. By constantly testing and tweaking, you can continually improve your website, app, or product, ensuring it stays ahead of the competition.</li><li><strong>Increased ROI:</strong> A/B testing helps you identify the most effective strategies, maximizing your return on investment (ROI). By focusing on what resonates with your audience, you can get more bang for your buck.</li><li><strong>Reduced Risk:</strong> Before rolling out significant changes, A/B testing allows you to test them on a smaller scale, minimizing the risk of negative consequences. This is especially crucial for high-stakes decisions.</li><li><strong>Competitive Advantage:</strong> Companies that embrace A/B testing gain a competitive edge. They can quickly adapt to changing market conditions and user preferences, staying one step ahead of those who rely on intuition alone.</li></ol><h4><strong>Who Can Benefit from A/B Testing?</strong></h4><p>A/B testing isn’t just for tech giants or data scientists. It’s a versatile tool that can benefit a wide range of professionals:</p><ul><li><strong>Marketers:</strong> Optimize ad campaigns, landing pages, email marketing, and social media strategies.</li><li><strong>Product Managers:</strong> Make data-driven decisions about new features, UI/UX changes, and product launches.</li><li><strong>Designers:</strong> Validate design choices and understand how users interact with different layouts and elements.</li><li><strong>Data Scientists:</strong> Rigorously test different models in real-world production environments, ensuring your algorithms and machine learning models perform optimally to drive business outcomes.</li></ul><p>No matter your role or industry, if you’re involved in decision-making that impacts user behavior, A/B testing can be your secret weapon for success.</p><p>In the next section, we’ll demystify the fundamental concepts of A/B testing, laying the groundwork for your experimentation journey. Get ready to embrace the power of data and discover how A/B testing can transform your decision-making process.</p><h3>A/B Testing Fundamentals Demystified</h3><p>A/B testing might sound complex, but at its core, it’s a simple yet powerful concept. It involves comparing two or more versions of a webpage, app, or feature to see which one performs better based on a specific metric. Think of it as a controlled experiment where you make one change at a time and observe the impact on user behavior.</p><h4>Treatment and Control Groups: The Heart of the Experiment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bJrEz0S-zPoX5-6Ia4LiA.png" /><figcaption>Example of treatment vs control group in clinical trials setup</figcaption></figure><p>Before we dive into the hypothesis testing, let’s clarify two essential players in any A/B test:</p><p><strong>Control Group (Group A):</strong> This is your baseline, the status quo. Users in the control group experience the current version of your webpage, app, or feature — the one you want to compare against.</p><p><strong>Treatment Group (Group B):</strong> This is where the magic happens. Users in the treatment group experience the modified version, the one you hypothesize will lead to an improvement.</p><p>Think of it like a race:</p><ul><li><strong>Control Group (A):</strong> The runner in the current shoes.</li><li><strong>Treatment Group (B):</strong> The runner trying out the new, supposedly faster shoes.</li></ul><p>By comparing the performance of these two groups, you can isolate the impact of your change (the new shoes) and determine whether it truly makes a difference.</p><p><strong>Example: </strong>Let’s say you’re testing a new call-to-action button on your website. You might randomly assign half of your visitors to the control group, who see the old button, and the other half to the treatment group, who see the new button. You then track the click-through rate for both groups to see if the new button leads to a significant improvement.</p><h4><strong>The Hypothesis Engine: Fueling Your A/B Test</strong></h4><p>Every A/B test starts with a question that sparks your curiosity and leads to a testable prediction — your hypothesis. In the realm of A/B testing, a hypothesis is typically framed in two parts:</p><ol><li><strong>Null Hypothesis (H0):</strong> This is the default assumption that there is no significant difference between the control group (A) and the treatment group (B). For example: “Changing the button color from blue to orange will have no impact on the click-through rate.”</li><li><strong>Alternative Hypothesis (H1):</strong> This is what you believe to be true, the change you expect to see as a result of your experiment. For example: “Changing the button color from blue to orange will increase the click-through rate.”</li></ol><p><strong>Testing Your Hypothesis: </strong>To determine whether your alternative hypothesis is supported, you need to conduct a statistical test. This involves collecting data from both groups and using statistical methods to analyze the results. Common statistical tests for A/B testing include the z-test, t-test, chi-squared test, and ANOVA (Analysis of Variance).</p><p>While we won’t delve into the mathematical details here, the fundamental idea is to calculate a test statistic that measures the difference between the two groups and compare it to a critical value determined by your desired significance level (e.g., 0.05). If the test statistic exceeds the critical value, you can reject the null hypothesis and conclude that your alternative hypothesis is supported.</p><h4>Metrics That Matter: Choosing Your North Star</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC-OMTCvOgT-POibHixpSg.png" /></figure><p>Metrics are the compass guiding your A/B test. They tell you whether your experiment is sailing towards success or veering off course. But not all metrics are created equal. Some are essential for measuring your core objective, while others provide additional insights or guardrails against unintended consequences.</p><p><strong>Primary Metrics: Your Ultimate Goal</strong></p><p>The primary metric is the single most important measure of your experiment’s success. It’s the metric that directly aligns with your business objective. Are you aiming to increase sales? Then revenue might be your primary metric. Are you trying to boost user engagement? Then time spent on site or clicks per session could be your focus.</p><p>The primary metric is the yardstick by which you judge the overall impact of your experiment. It’s the answer to the question: “Did the change we made in the experimental group (B) lead to a significant improvement compared to the control group (A)?”</p><p><strong>Secondary Metrics: Additional Insights</strong></p><p>Secondary metrics provide additional context and insights into how your experiment impacts user behavior. They might not be directly tied to your primary goal but can reveal interesting trends or unintended consequences. For example, if your primary metric is conversion rate, you might track secondary metrics like bounce rate, time on page, or click-through rates on specific elements.</p><p><strong>Guardrail Metrics: Protecting the User Experience</strong></p><p>Guardrail metrics are designed to safeguard against negative impacts on user experience. They monitor aspects of your product or service that you don’t want to deteriorate as a result of your experiment. For instance, if you’re testing a new checkout flow, you might monitor guardrail metrics like page load time or error rates to ensure the changes don’t inadvertently frustrate users.</p><p>By carefully selecting and tracking the right metrics, you can unlock valuable insights from your A/B tests and make data-driven decisions that drive real business results.</p><h4>Randomization and Sample Size: The Foundation of Reliable Results</h4><p>Imagine flipping a coin to decide who gets the new, potentially improved version of your product. That’s the essence of randomization in A/B testing. It’s the process of randomly assigning users to either the control group (A) or the experimental group (B), ensuring that both groups are comparable and that any observed differences in performance can be attributed to the change you’re testing, rather than other factors.</p><p><strong>Why Randomization Matters</strong></p><p>Without randomization, your A/B test results could be skewed by hidden biases. For example, if you let users self-select into groups, you might end up with tech-savvy early adopters in the experimental group, making the new feature seem more successful than it truly is for the general population. Randomization levels the playing field, making your results more reliable.</p><p><strong>Sample Size: How Many Users Do You Need?</strong></p><p>Sample size is the number of users in each group (control and treatment). It’s a critical factor that determines the statistical power of your experiment — the ability to detect a real difference between the groups if one exists.</p><p>The larger your sample size, the more confident you can be in your results. However, a larger sample size also means a longer experiment and potentially more resources required. So, how do you determine the right sample size for your A/B test?</p><p><strong>Sample Size Calculation for Continuous Metrics</strong></p><p>A common formula used is as follows:</p><pre>n = 2 * (Zα/2 + Zβ)² * σ² / Δ²</pre><p>Where:</p><ul><li>n = Sample size per group</li><li>Zα/2 = Z-score corresponding to the desired significance level (α), typically 0.05 for a 95% confidence level</li><li>Zβ = Z-score corresponding to the desired statistical power (1-β), typically 0.80 for 80% power</li><li>σ² = Variance of the metric in the population (estimate based on historical data or a pilot study)</li><li>Δ = Minimum detectable effect (the smallest difference in means you want to detect)</li></ul><p><strong>Understanding the Formula Components</strong></p><ul><li><strong>Significance Level (α):</strong> This is the probability of rejecting the null hypothesis when it’s actually true (Type I error). It’s often set at 0.05, meaning you’re willing to accept a 5% chance of falsely concluding that there’s a difference when there isn’t. In other words, it’s the level of risk you’re comfortable with for a false positive.</li><li><strong>Statistical Power (1-β):</strong> This is the probability of detecting a real difference between the groups if one exists. It’s often set at 0.80, meaning you want an 80% chance of finding a statistically significant difference if it truly exists. This is the level of risk you’re comfortable with for a false negative.</li><li><strong>Variance (σ²)</strong>: This represents how much the metric typically varies among users. A higher variance means you’ll need a larger sample size to detect a significant difference.</li><li><strong>Minimum Detectable Effect (Δ)</strong>: This is the smallest difference in means between the control and treatment groups that you consider practically significant.</li></ul><h4><strong>Randomization Units: Choosing the Right Level of Granularity</strong></h4><p>While randomization is essential, choosing the right randomization unit is equally important. The randomization unit is the level at which you divide your audience into control and treatment groups. It could be:</p><ul><li><strong>Users:</strong> Each individual user is assigned randomly to either group A or group B. This is the most common randomization unit in A/B testing.</li><li><strong>Sessions:</strong> Each user session (e.g., a visit to your website or app) is randomized. This means the same user could experience different versions of your experiment in different sessions.</li><li><strong>Pageviews:</strong> Each pageview is randomized, leading to even finer-grained experimentation. This is useful when you want to test specific page elements.</li></ul><p>The choice of randomization unit depends on your specific experiment and goals. Here are some factors to consider:</p><ul><li><strong>Consistency:</strong> If you want to ensure that users have a consistent experience throughout their interaction with your product, you might choose to randomize at the user or cookie level.</li><li><strong>Sensitivity:</strong> If you’re testing a change that might have a different impact on different pages or sessions, you might choose to randomize at the pageview or session level.</li></ul><p>For example, to test a new checkout flow, you might randomize at the user level to ensure that each user consistently experiences either the old or new flow throughout their purchase journey.</p><p>Choosing the appropriate randomization unit is crucial for ensuring the validity and reliability of your A/B test results. By understanding the different options and their implications, you can design experiments that provide meaningful insights and drive data-driven decisions.</p><h4>Statistical Significance vs. Practical Significance</h4><p>Once your A/B test concludes, it’s time to analyze the results. Two key concepts help you interpret the findings: statistical significance and practical significance.</p><ul><li><strong>Statistical Significance:</strong> This tells you whether the difference between your control (A) and treatment (B) groups is likely real, not just due to chance. A small p-value (usually less than 0.05) indicates a statistically significant result.</li><li><strong>Practical Significance:</strong> Even a statistically significant result might not be meaningful for your business. Practical significance asks the question: “Is the observed difference big enough to warrant action? Does the change align with your overall objectives? Does the potential benefit outweigh the cost of implementing the change?” Ultimately, practical significance is a subjective judgment that requires you to weigh the statistical evidence against your business context and goals.</li></ul><p>Both statistical and practical significance are crucial. A result may be statistically significant but not worth implementing, while a non-significant result with a large potential impact might warrant further investigation. Always consider both aspects when interpreting A/B test results to make informed decisions that drive real business value.</p><h4>Experiment Duration: Timing is Key</h4><p>You’ve formulated a hypothesis, identified your metrics, randomized your groups, and calculated the necessary sample size. Now, the question is: How long should you run your A/B test?</p><p><strong>Finding the Sweet Spot</strong></p><p>The ideal experiment duration strikes a balance between gathering enough data to make reliable conclusions and not running the test so long that you miss out on potential gains. If you stop too early, you might not have enough data to reach statistical significance, leading to inaccurate conclusions. On the other hand, if you run the test too long, you might expose a large portion of your audience to an under-performing variation, potentially harming your business goals.</p><p><strong>Factors Influencing Experiment Duration</strong></p><p>Several factors influence how long you should run an A/B test:</p><ol><li><strong>Traffic Volume:</strong> The more traffic your website or app receives, the faster you can accumulate the required sample size and reach statistical significance. A high-traffic site might only need a few days for a test, while a low-traffic site might require weeks or even months.</li><li><strong>Desired Confidence Level:</strong> The higher the confidence level you want in your results (e.g., 95% vs. 90%), the longer you need to run your test to ensure you have enough data to support your conclusions.</li><li><strong>Minimum Detectable Effect:</strong> The smaller the difference you want to detect between the control and treatment groups (e.g., a 1% vs. a 5% increase in conversion rate), the longer you’ll need to run your test. Smaller effects require larger sample sizes to achieve statistical significance.</li><li><strong>Seasonality and External Factors:</strong> If your business experiences seasonal fluctuations or external events that could impact user behavior (e.g., holidays, sales, news events), you might need to adjust your experiment duration or schedule your tests during periods of relative stability.</li></ol><p>Remember, experiment duration is not a one-size-fits-all answer. It requires careful consideration of various factors and a balance between statistical rigor and practical constraints. By finding the right duration for your specific test, you can maximize the value of your A/B testing efforts and make data-driven decisions with confidence.</p><h3>Designing Effective A/B Tests: The Art and Science of Experimentation</h3><p>With a solid understanding of the fundamentals, it’s time to delve into the creative and strategic aspects of designing A/B tests that yield meaningful insights and drive impactful changes.</p><h4>Types of A/B Tests: Choosing the Right Tool for the Job</h4><p>Not all A/B tests are created equal. There are different types, each suited for specific scenarios and goals. Let’s explore some common types:</p><ol><li><strong>Simple A/B Tests:</strong> This is the most basic form, where you compare the original version (control) with one variation (treatment). It’s ideal for testing simple changes like button colors, headlines, or call-to-action text.</li><li><strong>Multivariate Tests (MVT):</strong> MVTs are more complex and involve testing multiple variations of multiple elements simultaneously. For example, you might test different combinations of headlines, images, and button colors to find the optimal combination. While MVTs can provide valuable insights, they require larger sample sizes and more sophisticated analysis.</li><li><strong>Bandit Tests:</strong> These tests are adaptive and automatically adjust the allocation of traffic to the better-performing variations during the experiment. This can help you quickly identify winning variations and maximize the benefits of your A/B test.</li></ol><p>The choice of A/B test type depends on your goals, resources, and the complexity of the change you’re testing. Simple A/B tests are a good starting point for most experiments, while MVTs and bandit tests are more suitable for advanced scenarios.</p><h4>What to Test: Finding the Levers of Change</h4><p>One of the most critical decisions in A/B testing is choosing what to test. There are countless elements on your website, app, or product that you could potentially tweak, but focusing on the right ones is key to getting meaningful results.</p><p>Here are some common areas where A/B testing can yield valuable insights:</p><ul><li><strong>Headlines and Copy:</strong> The wording you use can significantly impact user engagement and conversion rates. Test different headlines, calls to action, and body copy to see what resonates best with your audience.</li><li><strong>Layout and Design:</strong> The overall layout and design of your pages can affect how users navigate and interact with your content. Test different layouts, color schemes, and fonts to find what works best.</li><li><strong>Pricing and Offers:</strong> If you’re selling products or services, testing different pricing models, discounts, or promotions can help you find the sweet spot that maximizes revenue.</li><li><strong>Product Features:</strong> A/B testing can be used to validate new features or improvements before rolling them out to all users.</li><li><strong>Personalization:</strong> Experiment with different personalization strategies to see how tailoring content or recommendations to individual users impacts engagement and conversion rates.</li><li><strong>Algorithms and Machine Learning Models:</strong> For data scientists, A/B testing is an essential tool for comparing the performance of different algorithms or models in a real-world setting.</li></ul><p>The possibilities are virtually endless, and the best elements to test will depend on your specific goals and priorities.</p><h4>Test Prioritization: Making the Most of Your Resources</h4><p>You likely have a long list of potential A/B tests you’d like to run. However, you have limited time and resources. This is where test prioritization comes in. It helps you decide which tests to focus on first to maximize your impact and achieve your goals faster.</p><p>There are several frameworks you can use for test prioritization, but one popular approach is the PIE framework.</p><p><strong>The PIE Framework:</strong></p><ul><li><strong>Potential:</strong> How much potential does this test have to improve your key metrics?</li><li><strong>Importance:</strong> How important is this metric to your overall business goals?</li><li><strong>Ease:</strong> How easy is it to implement and analyze this test?</li></ul><p>By assigning scores to each potential test based on these three factors, you can create a prioritized list that guides your experimentation roadmap.</p><h3><strong>Conclusion — Embracing the Experimentation Mindset</strong></h3><p>Congratulations! You’ve now journeyed through the core fundamentals of A/B testing, a powerful tool that can transform how you make decisions and drive results. We’ve explored the why, the what, and the how of A/B testing, from formulating hypotheses to understanding the nuances of randomization, sample size, metrics, and statistical significance.</p><p>Armed with this knowledge, you’re well-equipped to embark on your own A/B testing adventures. Remember, the key to success lies in continuous experimentation, learning from both successes and failures, and always prioritizing user-centricity in your decisions.</p><p><strong>Stay Tuned for More!</strong></p><p>While this guide has covered the essentials, the world of A/B testing is vast and constantly evolving. In future blog posts, we’ll delve deeper into advanced techniques, such as bandit algorithms for dynamic optimization, causal inference and sequential testing for faster decision-making. We’ll also explore common <a href="https://medium.com/@suraj_bansal/pitfalls-and-mistakes-in-a-b-tests-4d9073e17762">pitfalls and mistakes</a> to avoid, ensuring you navigate the complexities of experimentation with confidence.</p><p>Until then, embrace the experimentation mindset, test boldly, and let data be your guiding light in making informed decisions that drive your business forward.</p><p>If you enjoyed this explanation, please consider subscribing to stay tuned for more insights and I love talking about data, so you can also connect with me over <a href="https://www.linkedin.com/in/surajbansal28/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9b998c43472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own AI Chatbot: A Beginner’s Guide to RAG and LangChain]]></title>
            <link>https://medium.com/@suraj_bansal/build-your-own-ai-chatbot-a-beginners-guide-to-rag-and-langchain-0189a18ec401?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/0189a18ec401</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[rag-chatbot]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Mon, 06 May 2024 15:00:09 GMT</pubDate>
            <atom:updated>2024-05-06T15:00:09.796Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Wouldn’t it be awesome if you had your own personal encyclopedia that could also hold a conversation? 🤓 Well, with the power of RAG and LangChain, you’re about to become the architect of your very own AI chatbot!</p><p>Chatbots are everywhere these days — helping us shop, solving our tech woes, and even keeping us company. But what if you could build a chatbot that’s not just helpful, but actually<strong> smart</strong>? 😎</p><p>Enter RAG (Retrieval-Augmented Generation). It’s like giving your chatbot a brain full of searchable knowledge. Imagine a chatbot that could tap into a vast library of information and generate creative text. That’s the magic of RAG.</p><p>And to make things even easier, there’s LangChain — think of it as a set of super helpful building blocks for creating all kinds of AI applications. As the saying goes, “Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime” Let’s teach you to build an awesomely intelligent chatbot! 🤖</p><p>In this comprehensive tutorial, you’ll discover:</p><ol><li>The key concepts behind RAG and how to use LangChain to create sophisticated chatbots.</li><li>How to build both stateless and stateful (context-aware) chatbots using LangChain with step by step explanation of the code.</li><li>The steps to connect your chatbot to a knowledge repository like a PDF, empowering it to answer questions about the document’s content. 📖</li><li>Hidden Secrets<strong>: </strong>A bonus section awaits those who crave a deeper understanding. We’ll crack open some LangChain secrets and see how the magic works under the hood.</li></ol><p>Spoiler Alert — In this tutorial, we’ll dive into building a RAG chatbot that can interact with a research paper (PDF format). The beauty is, you can easily adapt the code to work with any content — html files, csv, SQL databases, websites, and more! Get ready to unlock the knowledge within your documents.</p><p>To make this journey even smoother, you’ll find the complete code and data on my <a href="https://github.com/adroit-ds/rag-chatbot/blob/main/README.md">GitHub</a> repository.</p><p><strong>A Note for Experienced AI Adventurers </strong>— This article is packed with information! It starts with a thorough exploration of RAG and LangChain concepts and gradually guides you through building your chatbot. If you’re already well-versed in the theory, feel free to jump to the sections titled “Setting up Your Environment” or “Building Your RAG Chatbot (Step-by-Step)”.</p><p>However, even for seasoned AI enthusiasts, skimming the earlier sections might provide a helpful refresher. As the saying goes, “Knowledge is power”</p><p><strong>Ready to take your AI skills to the next level? Let’s dive in and build the knowledge-powered chatbot of your dreams!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzB4vITuRz6fKL9j9FyTkA.png" /></figure><h3>Prerequisites</h3><p>Before diving into the world of RAG chatbot creation, let’s make sure you have the right tools and knowledge:</p><ol><li><strong>Basic Python Proficiency:</strong> While I will provide code examples, a fundamental understanding of Python concepts (variables, functions) will make the process much smoother.</li><li><strong>Essential Libraries:</strong> You’ll need to install the following libraries using the ‘pip’ package manager in your terminal:<br> — langchain: The heart of our chatbot building process.<br> — openai: Lets us tap into powerful language models from OpenAI.<br> — pinecone-client: For setting up our vector database to store knowledge.</li><li>OpenAI and Pinecone Accounts: You’ll need API keys to use these services. Instructions for getting them are included below.</li><li>Your Knowledge Source: The beauty of RAG is that you provide the data your chatbot learns from! Have your research paper (PDF) or other content type (text files, website URLs, company documents) ready.</li></ol><p><strong>Don’t worry if you’re new to all of this! I’ll help guide you through setting up your environment along the way.</strong></p><p>Ready to take the next step? Let’s uncover the fascinating theory behind rag and Langchain!</p><h3>Understanding RAG, and LangChain</h3><p>Ever had a conversation where someone seems to know everything? Maybe a friend who aced history class or a family member who can fix anything. That’s kind of the magic we’re aiming for with your PDF chatbot — a constant source of knowledge at your beck and call.</p><p>But how do we make a computer program that can tap into the vastness of the PDF and have a conversation? That’s where RAG and LangChain come in!</p><h4>RAG (Retrieval-Augmented Generation): Your Chatbot’s Super-powered Search Engine</h4><p>Imagine you’re at a giant library with countless books on every topic imaginable. RAG is like having a super-efficient assistant who can instantly find the most relevant books based on your questions. Here’s the gist of how it works:</p><ol><li>You ask your chatbot a question. For instance, “What’s the capital of France?”</li><li>RAG swings into action! It scans your chosen data source for entries that match your question.</li><li>With the most relevant information retrieved, RAG hands it over to the language model.</li><li>The language model now uses this factual information to form an accurate and helpful response, telling you that the capital of France is Paris. ⛪️</li></ol><p>At its core, Retrieval-Augmented Generation (RAG) leverages the strengths of two powerful AI techniques: information retrieval and large language models (LLMs). Let’s delve into the process:</p><ol><li><strong>Query Understanding:</strong> When a user interacts with your chatbot, RAG first employs natural language processing (NLP) techniques. This involves breaking down the user’s question into its constituent parts (tokens) and analyzing its semantic meaning and intent.</li><li><strong>Retrieval from the Knowledge Base:</strong> Armed with an understanding of the user’s query, RAG interacts with a specialized database like FAISS, Weaviate, or Pinecone. These databases don’t store text directly. Instead, they store meaning-based mathematical representations of information called vectors. RAG generates a similar vector for the user’s query and finds the most closely matching vectors in the database. These matching vectors lead RAG to the specific sections of text most likely to contain the answer.</li><li><strong>Enhancing the LLM with Retrieved Knowledge:</strong> Once RAG successfully retrieves the most pertinent information (text snippets, article summaries etc.), it feeds this data to a pre-trained LLM like GPT, Gemini etc. These LLMs are statistical models trained on massive amounts of text data, granting them the ability to process information and generate human-quality text.</li><li><strong>Response Generation:</strong> Empowered by the retrieved knowledge from the provided text, the LLM steps in to craft the response to the user’s query. This response can take various forms depending on the prompt provided. It could be a concise answer to the question, a comprehensive summary of the article, or even a creatively formatted text response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*VIC4SGSBHMkZ9ktYdO5ApA.png" /><figcaption>Source — <a href="https://www.elastic.co/search-labs/blog/retrieval-augmented-generation-rag">https://www.elastic.co/search-labs/blog/retrieval-augmented-generation-rag</a></figcaption></figure><p><strong>Summary </strong>— Traditionally, an LLM relies on its stored knowledge to answer questions. RAG enhances this process through three key steps: retrieval, augmentation, and generation. First, your question is converted into a “vector embedding”. RAG then performs retrieval, searching a database where content from your information source is also stored as vectors. It identifies the most relevant content, which is used for augmentation — combining it with your original question to create a richer input. Finally, the LLM uses this enhanced input for generation, producing a more accurate and helpful answer.</p><h4>LangChain: The Modular Maestro</h4><p>LangChain is a powerful 💪 Python-based framework designed to simplify the development of applications powered by large language models (LLMs). It does this by providing a modular and flexible structure that streamlines common NLP tasks and the integration of various AI components. Here’s why it’s a valuable tool for our chatbot project:</p><ul><li><strong>Abstraction</strong>: LangChain breaks down complex LLM interactions into reusable building blocks like chains, agents, and prompts. This abstraction layer eliminates much of the intricate coding, especially when dealing with the interplay of tools like RAG, making development more accessible.</li><li><strong>Modularity</strong>: Its modular design promotes flexibility and experimentation. You can easily swap out different components or modify your chatbot’s structure without the need to completely rebuild from scratch.</li><li><strong>Integration</strong>: LangChain seamlessly connects with various external data sources, retrieval models, and LLMs. This makes the process of integrating the any knowledge base and RAG a smooth experience.</li></ul><p>Think of LangChain as a toolbox filled with different components to build your chatbot. Here are the key players:</p><ol><li>Chains: These are essentially pipelines that connect various components within the chatbot architecture. In our case, we’ll construct a chain that seamlessly integrates the user’s query with the retrieval manager (RAG) and subsequently, the response generation stage.</li><li>Agents: These are like the workers in your chatbot factory. We will create a specialized agent that acts as a bridge between LangChain and RAG. It receives the user’s query from the chain, transmits it to RAG for information retrieval, and then feeds the retrieved data back into the chain for further processing.</li><li>Prompts: LangChain empowers you to design prompts that guide the LLM in crafting the most effective response. For example, a prompt might instruct the LLM to provide a succinct answer to the user’s question or generate a concise summary of a retrieved Wikipedia article.</li></ol><p>The synergy between RAG’s information retrieval capabilities and LangChain’s modular structure lays the foundation for constructing a chatbot that leverages the vast and complicated content in any data source (in our case PDF) to deliver informative and creative responses to user queries.</p><p>If you’re wondering why we wouldn’t simply use standard Large Language Models (LLMs) to get answers to specific questions through a chatbot, then you’re on the right track. Let’s delve into why this approach might not be ideal.</p><h3>Why RAG? The Limitations of Standard LLMs</h3><p>Standard Large Language Models (LLMs) like GPT-3.5 are remarkable tools, able to generate impressively human-like text, translate languages, and more. However, when it comes to building a chatbot for specialized knowledge domains, they have shortcomings:</p><ul><li><strong>Open-Domain Limitations:</strong> While LLMs have learned from a massive amount of text data, they may struggle when presented with questions about very specific topics, such as the technical details of a product or the intricacies of a company policy.</li><li><strong>Handling Large Documents:</strong> LLMs often have token limits, meaning they can only process a limited amount of text at once. This makes it difficult to use them directly on lengthy documents like research papers or complex manuals.</li><li><strong>The Risk of Hallucination</strong>: LLMs can sometimes generate responses that are confidently worded but factually incorrect, particularly if the topic is outside the common knowledge they were trained on. This can be misleading for users relying on your chatbot as an information source.</li><li><strong>Harnessing Your Knowledge:</strong> Your company likely has a wealth of information in documents, guides, and databases. Standard LLMs don’t tap directly into this knowledge; you need a way to channel this information for your chatbot to leverage.</li></ul><h4>How RAG Excels:</h4><p>RAG addresses these limitations by:</p><ul><li><strong>Focused Knowledge:</strong> RAG allows you to train your chatbot on a specific knowledge base, such as your company’s manuals or research papers. This ensures responses are relevant and grounded in verified information.</li><li><strong>Fact-Checking Potential:</strong> With RAG, your chatbot can cite relevant sections of your documents, increasing the trustworthiness of its responses.</li><li><strong>Controlled Expertise:</strong> You gain control over what information the chatbot knows, allowing you to tailor its expertise to the exact domain you need.</li></ul><p>Time to Gear Up! Let’s get your environment ready for the exciting journey of building a RAG chatbot.</p><h3>Setting up Your Environment</h3><p>Ready to make some magic happen with RAG and LangChain? Follow these steps to make sure you have everything in place to build our chatbot:</p><h4>API Keys</h4><ul><li>OpenAI: To interact with powerful language models, you’ll need an API key from OpenAI.<br> — Visit <a href="https://beta.openai.com/signup/">https://platform.openai.com/signup/</a> to create an account if you don’t have one.<br> — Navigate to your account settings and find your existing API keys, or generate a new one. <strong>Keep this secure!</strong><br> — Important Note: As far as I know, OpenAI no longer offers a free tier. You may need to add a payment method and a small amount of credit (around $5 should be more than plenty for a plethora of experimental projects) to your account.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC47OyOhuw83EIzGIBjreA.png" /><figcaption>Generating open-AI API key</figcaption></figure><ul><li>Pinecone: For this tutorial, we’ll use Pinecone to create a vector database — a powerful way to store our knowledge base for fast and accurate information retrieval.<br> — It offers a <strong>generous free tier</strong>, perfect for getting started.<br> — Create an account at <a href="https://www.pinecone.io/">https://www.pinecone.io/</a><br> — Find your API key in your Pinecone console. <br> — You’ll also need to create an index in Pinecone. An index is like a container that will hold the vector embeddings of your knowledge documents. You can choose a suitable embedding model like ‘text-embedding-ada-002’ which generates embeddings of size 1536. I created an index named ‘pdf-vectorised’, but feel free to give it a different name. Remember, we’ll use this index name in our code to access and store vectors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8o2Qbzf2sq97h62wWRqy2g.png" /><figcaption>Create a Pinecone index (pdf-vectorised) and API Key to store vector embeddings</figcaption></figure><h4>Install the Necessary Libraries</h4><p>I highly recommend setting up a virtual environment for this project. Virtual environments help isolate your project’s dependencies from other Python projects on your system, preventing potential conflicts. Here’s how to install the libraries:</p><ul><li>Create a file named requirements.txt in your project directory and add the libraries as shown below.</li></ul><pre>langchain<br>openai<br>pinecone-client<br>langchain-pinecone<br>langchain-openai<br>python-dotenv<br>pypdf</pre><ul><li>From your terminal, navigate to your project directory and run the following command pip install -r requirements.txt</li></ul><p>Now that we have our foundation, let’s get to the interesting stuff and code up our first chatbot that interacts with a PDF using RAG and LangChain. I hope you guys are excited to see it in action 😎</p><h3>Building Your RAG Chatbot (Step-by-Step)</h3><p>Get ready to dive into the exciting world of coding! In this section, we’ll lay the groundwork for your RAG chatbot. We’ll be using a PDF of a research paper titled “The Impact, Advancements and Applications of Generative AI” to build a chatbot that can interact with its content. First, let’s set up some essential files and load the paper’s data into our Pinecone vector database.</p><h4>Environment Files and Data Ingestion</h4><p>First, let’s prepare the ground for successful development:</p><p><strong>Environment Variables</strong></p><p>Create a file named .env in your project directory. Remember to keep this file safe — it’ll hold sensitive information like your API keys. We’ll use a Python library called dotenv to access these keys securely.</p><pre>OPENAI_API_KEY={openAI API key}<br>INDEX_NAME={Pinecone index name}<br>PINECONE_API_KEY={Pinecone API key}</pre><p><strong>Data Ingestion</strong></p><p>Step 1 — Importing Libraries</p><p>Create a file named ingestion.py and import all the libraries we’ll need to read and ingest data.</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import CharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_pinecone import PineconeVectorStore<br><br>load_dotenv()</pre><p>Don’t worry if some of these libraries and their purposes seem unclear now. As we write our data ingestion code, you’ll gain a clearer understanding of how each one plays its part.</p><p>Step 2 — Loading the PDF Content</p><pre>loader = PyPDFLoader(&quot;data/impact_of_generativeAI.pdf&quot;)<br>document = loader.load()</pre><ul><li><strong>pdf_file_path</strong>: Make sure to replace the placeholder with the correct location of your research paper PDF on your computer.</li><li><strong>loader</strong>: We create a PyPDFLoader object, giving it the path to your PDF file. This loader is specifically tailored to handle PDF documents within the LangChain framework.</li><li><strong>documents</strong>: When we call loader.load(), it reads your PDF, extracts the text, and returns a list of LangChain documents, ready for further processing.</li></ul><p>Step 3 — Splitting Documents into Chunks</p><p>Now that we have our loaded documents, let’s break them down into smaller pieces for a more efficient workflow. Here, we’ll use LangChain’s CharacterTextSplitter</p><pre>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>texts = text_splitter.split_documents(document)<br>print(f&quot;created {len(texts)} chunks&quot;)</pre><p>Why Split Documents? There are three main reasons for splitting documents into smaller chunks:</p><ol><li><strong>Memory Efficiency:</strong> Large documents can be resource-intensive to process. Splitting them into smaller pieces reduces the memory footprint, making the process smoother, especially when dealing with hefty PDFs.</li><li><strong>Token Limits:</strong> Language models can only process a limited amount of text at once. Splitting up our documents allows us to work within those limitations.</li><li><strong>Context Preservation:</strong> While splitting, we want to ensure each chunk retains some context from its surrounding text. This helps the language model understand the meaning of each piece accurately.</li></ol><p><strong>Understanding Chunk Size and Overlap</strong></p><p>The CharacterTextSplitter takes two important parameters:</p><ol><li><strong>chunk_size</strong>: This defines the maximum number of characters in each split chunk. A smaller chunk size creates more, but shorter, chunks. A larger chunk size creates fewer, but longer, chunks. It’s crucial to find a good balance when choosing the chunk_size. Extremely small chunks might not contain enough context for the language model to understand properly, whereas very large chunks might become processing bottlenecks.</li><li><strong>chunk_overlap</strong>: This specifies the number of characters that overlap between consecutive chunks. Overlap helps the language model maintain context between neighboring pieces, especially important for longer sentences that might be split across chunks. We set chunk_overlap to 100 characters. This ensures some overlap between chunks, helping the language model understand the flow of information across splits.</li></ol><p>Step 4 — Creating Embeddings and Storing in Pinecone</p><p>Now that we have our text chunks, let’s use OpenAI’s language models to create vector representations (embeddings) that capture their meaning. We’ll then store these embeddings in our Pinecone database for efficient retrieval later.</p><pre>embeddings = OpenAIEmbeddings(openai_api_type=os.environ.get(&quot;OPENAI_API_KEY&quot;))<br>PineconeVectorStore.from_documents(texts, embeddings, index_name=os.environ.get(&quot;INDEX_NAME&quot;))</pre><ul><li><strong>OpenAIEmbeddings</strong>: We import this class from LangChain to interact with OpenAI’s embedding models using OpenAI API key which we set in the .env file.</li><li><strong>PineconeVectorStore</strong>: This class connects LangChain to your Pinecone vector database. By calling the from_documents method, we save the vector embeddings corresponding to every text chunk in your Pinecone database.</li></ul><p>After running this code, if you go to your Pinecone UI and navigate to the specified index, you should see the vector embeddings being uploaded and stored (as shown in the image below), ready for your RAG chatbot to access!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrBzP48ThfSU-VzbuMl7zA.png" /><figcaption>Vector Embeddings updated in the Pinecode index</figcaption></figure><h4>Building a Stateless RAG Chatbot with LangChain</h4><p>It’s time to build the heart of your chatbot! Let’s start by creating a new Python file named stateless-bot.py. Within this file, begin by importing the necessary packages:</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_openai import OpenAIEmbeddings<br>from langchain.chains import RetrievalQA<br>from langchain_community.chat_models import ChatOpenAI<br>from langchain_pinecone import PineconeVectorStore</pre><p>We’re calling this script stateless-bot.py because in its current form, the bot doesn’t keep track of previous conversations. Each question and answer interaction is independent, which is a great start, but shortly we will also explore adding a “memory” to the bot.</p><p>Step 1 — Loading Your Knowledge</p><p>Now that we have our imports in place, let’s set up a way to access the vector embeddings we stored in Pinecone earlier. This will allow our chatbot to retrieve relevant information from the PDF. Here’s the code:</p><pre>embeddings = OpenAIEmbeddings()<br>vectorstore = PineconeVectorStore(<br>        index_name=os.environ[&quot;INDEX_NAME&quot;], embedding=embeddings<br>)</pre><p>This code specifically establishes a connection to your existing Pinecone index where you’ve stored the vector representations (embeddings) of your research paper.</p><p>Step 2 — Building Your RAG Chains and Asking Questions</p><p>Let’s set up the LangChain workflows (chains) that will drive the logic behind your RAG chatbot:</p><pre>chat = ChatOpenAI(verbose=True, temperature=0, model_name=&quot;gpt-3.5-turbo&quot;)<br><br>qa = RetrievalQA.from_chain_type(<br>    llm=chat, chain_type=&quot;stuff&quot;, retriever=vectorstore.as_retriever()<br>)    <br><br>res = qa.invoke(&quot;What are the applications of generative AI according the the paper? Please number each application.&quot;)<br>print(res) <br><br>res = qa.invoke(&quot;Can you please elaborate more on application number 2?&quot;)<br>print(res)</pre><ul><li>Initializing OpenAI: We initialize the ChatOpenAI LLM specifying temperature=0. This encourages the model to generate more focused and less creative responses.</li><li>Core RAG Chain: In LangChain, RetrievalQA.from_chain_type is a function used to create a RetrievalQA chain, a specific type of chain designed for question answering tasks.</li></ul><p>Here is the output</p><pre>{&#39;query&#39;: &#39;What are the applications of generative AI according the the paper? Please number each application.&#39;,<br> &#39;result&#39;: &#39;Based on the provided context, the applications of generative AI mentioned in the paper are as follows:\n\n1. Creative Content Generation\n2. Data Augmentation\n3. Simulation and Modeling\n4. Scenario Generation and Planning\n5. Personalization and Recommendation Systems\n6. Design and Creativity Assistance\n7. Scientific Discovery and Exploration\n8. Bridging Gaps in Data\n\nThese applications cover a wide range of fields and industries where generative AI can be utilized.&#39;}<br>{&#39;query&#39;: &#39;Can you please elaborate more on application number 2?&#39;,<br> &#39;result&#39;: &quot;I&#39;m sorry, but the specific application numbers are not provided in the context you shared. If you can provide more details or context about application number 2, I would be happy to help elaborate on it.&quot;}</pre><p>Based on the responses you received, you can clearly see the impact of the chatbot being stateless. While the first question, “What are the applications of generative AI according to the paper? Please number each application,” was answered successfully, the second question, “Can you please elaborate more on application number 2?”, resulted in the response “I do not have enough context.”</p><p>This happens because our current chatbot doesn’t retain information from previous interactions. Each question is treated independently. In the second query, the bot lacks the context of the specific application we refer to (number 2) because it doesn’t remember the answer or details provided in the first response</p><p><strong>Congratulations! </strong>🎉 You’ve successfully built your first chatbot with the remarkable power of RAG! It can tap into the knowledge within your PDF and respond thoughtfully to your questions.</p><p>The beauty of LangChain lies in how it simplifies the process of building such sophisticated chatbots. With a few lines of code, we’ve harnessed powerful language models and created a focused knowledge retrieval system.</p><p>For a more detailed breakdown of how RetrievalQA works, refer to the “Bonus — Breaking Down the LangChain Chain” section.</p><h3>Enhancing Your Chatbot with Context (Stateful)</h3><p>So far, our chatbot treated each question as an isolated event. While it could answer standalone queries, it struggled with follow-up questions or conversations that build upon previous interactions. This is where stateful chatbot excel.</p><h4><strong>Why Stateful Matters</strong></h4><p>Stateful chatbot maintain a memory of the conversation. This offers several advantages:</p><ul><li><strong>Understanding Context:</strong> They can understand how the current question relates to previous inquiries, providing more insightful and accurate answers.</li><li><strong>Natural Conversation Flow:</strong> The conversation feels more fluid and less repetitive, as the chatbot can reference past interactions, making the experience more engaging for the user.</li><li><strong>Tailored Responses:</strong> The ability to draw upon past context allows the chatbot to tailor its responses specifically to the ongoing conversation.</li></ul><p>Let’s see how we can transform our chatbot into a stateful one using LangChain’s ConversationalRetrievalChain</p><pre>import os<br>import warnings<br>from dotenv import load_dotenv<br>from langchain_openai import OpenAIEmbeddings<br>from langchain.chains import ConversationalRetrievalChain<br>from langchain_community.chat_models import ChatOpenAI<br>from langchain_pinecone import PineconeVectorStore<br><br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>load_dotenv()<br><br>chat_history = []<br><br>if __name__ == &quot;__main__&quot;:<br><br>    embeddings = OpenAIEmbeddings(openai_api_type=os.environ.get(&quot;OPENAI_API_KEY&quot;))<br>    vectorstore = PineconeVectorStore(<br>        index_name=os.environ[&quot;INDEX_NAME&quot;], embedding=embeddings<br>    )<br><br>    chat = ChatOpenAI(verbose=True, temperature=0, model_name=&quot;gpt-3.5-turbo&quot;)<br><br>    qa = ConversationalRetrievalChain.from_llm(<br>        llm=chat, chain_type=&quot;stuff&quot;, retriever=vectorstore.as_retriever()<br>    )  <br><br>    res = qa({&quot;question&quot;: &quot;What are the applications of generative AI according the the paper? Please number each application.&quot;, &quot;chat_history&quot;: chat_history})<br>    print(res)<br><br>    history = (res[&quot;question&quot;], res[&quot;answer&quot;])<br>    chat_history.append(history)<br><br>    res = qa({&quot;question&quot;: &quot;Can you please elaborate more on application number 2?&quot;, &quot;chat_history&quot;: chat_history})<br>    print(res)</pre><p><strong>Explanation: Tracking the Conversation</strong></p><ul><li>chat_history List: We’ve introduced the chat_history list, which acts as a memory bank for our chatbot.</li><li>Saving Interactions: After each question-answer exchange, we create a tuple containing both the user’s question and the model’s response. This tuple is then appended to the chat_history list, effectively storing the conversation history.</li></ul><p>This is enabled by using ConversationalRetrievalChainthat facilitates context-aware retrieval with history. Let’s look at the output.</p><pre>{&#39;question&#39;: &#39;What are the applications of generative AI according the the paper? Please number each application.&#39;,<br> &#39;chat_history&#39;: [],<br> &#39;answer&#39;: &#39;Based on the paper, the applications of generative AI are as follows:\n\n1. Art, entertainment, design, and scientific research\n2. Healthcare\n3. Fashion\n4. Gaming\n5. Advertising\n6. Content creation\n\nThese are some of the industries where generative AI can be applied according to the paper.&#39;}<br>{&#39;question&#39;: &#39;Can you please elaborate more on application number 2?&#39;,<br> &#39;chat_history&#39;: [(&#39;What are the applications of generative AI according the the paper? Please number each application.&#39;, &#39;Based on the paper, the applications of generative AI are as follows:\n\n1. Art, entertainment, design, and scientific research\n2. Healthcare\n3. Fashion\n4. Gaming\n5. Advertising\n6. Content creation\n\nThese are some of the industries where generative AI can be applied according to the paper.&#39;)],<br> &#39;answer&#39;: &#39;Generative AI has various applications in healthcare. It can contribute by generating synthetic medical data for training AI models, simulating biological processes, and designing personalized treatment plans. Generative AI can also assist in drug discovery by generating new molecule structures and predicting their properties. Additionally, it can be used to simulate complex scenarios for research and training purposes in the medical field. Overall, generative AI in healthcare aims to improve personalized treatment options, enhance drug discovery processes, and simulate biological processes for better understanding and advancements in the medical field.&#39;}</pre><p>Such an amazing thing! 🤩 Observe how our chatbot is learning as the conversation progresses. Initially, the chat_history was empty during the first question. Our chatbot provided a solid general answer. Now, look at the output from the second query! The first interaction has become part of the chat_history, providing much-needed context. Because of this, the chatbot understands we’re specifically interested in healthcare applications of generative AI. This allows it to provide a focused and informative answer tailored to application number 2. Our chatbot is becoming truly conversational!</p><p>Therefore, by adding state awareness with chat_history management and leveraging the capabilities of ConversationalRetrievalChain, our chatbot gains the ability to understand context and craft responses that build upon previous interactions. This significantly enhances the user experience by creating a more natural and engaging conversation flow.</p><p>Before we conclude this article, let’s take a moment to peek under the hood and gain a deeper understanding of how those LangChain chains function. Let’s take a moment to peek under the hood and gain a deeper understanding of how those LangChain chains function.</p><h3>Bonus — Breaking down the LangChain chain</h3><p>LangChain chains are the building blocks of applications built with the LangChain framework. These chains connect various components, like Large Language Models (LLMs), retrieval methods, and data sources, to perform complex tasks. They essentially define the workflow for how information flows through your application.</p><h4>RetrievalQA</h4><p><strong>RetrievalQA</strong> is a specialized type of Langchain chain designed specifically for question answering tasks. These chains leverage the power of LLMs while incorporating a retrieval step to improve the accuracy and context of the answers.</p><p>Here’s a breakdown of the key components within a RetrievalQA chain created using RetrievalQA.from_chain_type:</p><ul><li><strong>LLM (Large Language Model)</strong>: This is the core AI component responsible for generating the answer. You can specify the LLM you want to use within the function’s arguments.</li><li><strong>Retriever</strong>: This component plays a crucial role in the retrieval step. It identifies and fetches documents or information most relevant to the user’s question. The specific retrieval method used depends on the chosen retriever within the function.</li><li><strong>Chain Type</strong>: While the default chain type is “stuff”, which combines all retrieved documents, RetrievalQA.from_chain_type allows you to specify different chain types. These chain types offer various strategies for handling retrieved information and interacting with the LLM for answer generation. Examples include MapReduce for processing large datasets or Refine for iterative refinement based on LLM feedback.</li></ul><p>By combining these elements, RetrievalQA chains enable you to build effective question answering applications within the LangChain framework. The retrieved information provides valuable context for the LLM, leading to more comprehensive and informative answers.</p><h4>ConversationalRetrievalChain</h4><p>Remember how we transformed our chatbot to understand conversations? That magic happened thanks to LangChain’s ConversationalRetrievalChain. Let’s dive deeper into how it enables us to build stateful chatbots that maintain a conversation history. While RetrievalQA excels at answering individual questions based on retrieved information, ConversationalRetrievalChain takes it a level up. This specialized chain empowers you to build stateful chatbots that maintain a conversation history when passed explicitly.</p><p>To further understand how these chains work, let’s understand into the respective prompts used underneath both chain types.</p><h4>Sneak Peek into Prompts Used</h4><p><strong>RetrievalQA Prompt:</strong> The emphasis here is on providing the relevant context and current question to the LLM for the best possible answer as shown in the prompt below.</p><pre>prompt_template = &quot;&quot;&quot;Use the following pieces of context to answer the question at the end. If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br><br>{context}<br><br>Question: {question}<br>Helpful Answer:&quot;&quot;&quot;</pre><p><strong>ConversationalRetrievalChain Prompt: </strong>This prompt is more complex. It’s designed to work chat history, if pass explicitly. It cleverly leverages the LLM’s capability to rephrase a follow-up question into a standalone one, ensuring that it can be answered using the provided chat history as context.</p><pre>_template = &quot;&quot;&quot;Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.<br><br>Chat History:<br>{chat_history}<br>Follow Up Input: {question}<br>Standalone question:&quot;&quot;&quot;<br>CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)<br><br>prompt_template = &quot;&quot;&quot;Use the following pieces of context to answer the question at the end. If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br><br>{context}<br><br>Question: {question}<br>Helpful Answer:&quot;&quot;&quot;</pre><h3>Conclusion — The Power of RAG and LangChain</h3><p>Throughout this guide, we’ve embarked on an exciting journey into building Retrieval Augmented Generation (RAG) chatbot with the power of LangChain. Here’s a quick recap:</p><ul><li><strong>Understanding RAG and LangChain:</strong> We delved into how RAG chatbots combine retrieval and generation to provide informed and comprehensive answers. We also learned how LangChain simplifies the development of such sophisticated AI applications.</li><li><strong>Developing Stateful and Stateless Chatbots:</strong> We developed both stateless and stateful RAG chatbots from scratch using LangChain. This exploration highlighted the importance of context and how to achieve it using ConversationalRetrievalChain</li><li><strong>The Power of Pinecone:</strong> We discovered how Pinecone can be used for storing and efficiently retrieving the vector embeddings that represent our knowledge base.</li><li><strong>Unleashing Creativity</strong>: We had a look under the hood of LangChain itself, dissecting chains like RetrievalQA and ConversationalRetrievalChain. This gave us insight into how to customize prompts and build the perfect chatbot for our specific needs.</li></ul><h4>The Path Ahead</h4><p>The world of RAG chatbots is just opening up! Imagine the possibilities! You can continue to refine your chatbot by exploring more advanced chain types, incorporating memory strategies, and adding the ability to summarize documents or answer questions based on images. LangChain’s flexibility will be your greatest tool in this endeavor.</p><p>If you found this journey exciting, I encourage you to share your RAG creations and continue to explore the limitless potential of LangChain!</p><p>Stay Tuned for More!</p><p>If you enjoyed learning how to harness the power of RAG and LangChain, consider subscribing to my account. This way, you’ll be the first to know when I share new insights and tutorials. Plus, let’s connect on <a href="https://www.linkedin.com/in/surajbansal28/">LinkedIn</a> — I’d love to continue the conversation about data, machine learning, AI and language models!</p><h3><strong>References</strong></h3><ul><li><strong>LangChain Official Documentation:</strong> For a deep dive into all things LangChain, the official documentation is your best resource. Explore tutorials, reference guides, and more. <a href="https://python.langchain.com/docs/get_started/introduction/">https://python.langchain.com/docs/get_started/introduction/</a></li><li><strong>LangChain GitHub Repository:</strong> Take a look at the heart of LangChain — its codebase — and find examples on the official GitHub repository. <a href="https://github.com/langchain-ai">https://github.com/langchain-ai</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0189a18ec401" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to “Effortless Integration: Connecting VS Code to AWS EMR, EC2 Instances and Beyond…]]></title>
            <link>https://medium.com/@suraj_bansal/introduction-to-effortless-integration-connecting-vs-code-to-aws-emr-ec2-instances-and-beyond-ccade6aa4927?source=rss-c40d0f7a4cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccade6aa4927</guid>
            <category><![CDATA[cloud-dev-best-practices]]></category>
            <category><![CDATA[jupter-in-vs-code]]></category>
            <category><![CDATA[vs-code-with-emr-and-ec2]]></category>
            <category><![CDATA[pyspark-emr-workflow]]></category>
            <category><![CDATA[vs-code-aws-integration]]></category>
            <dc:creator><![CDATA[Suraj Bansal]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 15:22:49 GMT</pubDate>
            <atom:updated>2024-01-15T15:22:49.068Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to “Effortless Integration: Connecting VS Code to AWS EMR, EC2 Instances and Beyond for Enhanced Development and Data Workflows”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2UqltR7-JkP2iSP_TfQ4Q.png" /></figure><p>In the dynamic world of software development, the synergy between integrated development environments (IDEs) and cloud computing services is reshaping how we approach project workflows. Visual Studio Code (VS Code), celebrated for its adaptability and user-centric design, stands at the forefront of this evolution. When integrated with an array of Amazon Web Services (AWS), such as Elastic MapReduce (EMR), Elastic Compute Cloud (EC2), and even Elastic Kubernetes Service (EKS), it unlocks unparalleled efficiency and scalability.</p><p>The beauty of connecting VS Code with AWS lies in its ability to cater to a diverse range of development needs, transcending the boundaries of just data science and tapping into the broader spectrum of software development. This integration grants developers the flexibility to manage, develop, and deploy applications using the vast infrastructure of AWS, right from their local machines. It’s a leap towards simplifying cloud-based development, enriching both the speed and versatility of your workflow.</p><p>While a variety of IDEs can facilitate this connection, our focus here is on VS Code, renowned for its seamless user experience and robust features. In this article, we will primarily explore how to connect VS Code to AWS EMR, a popular choice for processing vast amounts of data. However, the methodologies and insights shared can be adapted for other AWS services involving remote machines, showcasing the versatile nature of this integration.</p><p>Join me as I guide you through the process of linking VS Code with AWS services. This walkthrough is designed not just for seasoned developers but also for those new to cloud computing, aiming to provide a clear, step-by-step approach to setting up a powerful development environment. Embrace this journey into the realm of cloud-enabled development, where the fusion of VS Code and AWS services paves the way for innovative, scalable, and efficient software solutions.</p><h4><strong>Section 1: Setting Up Your Environment</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQmpQSMNVthJZN3vWR4HDg.png" /></figure><p>In this section, we’ll cover the initial steps to configure your development environment in Visual Studio Code (VS Code) for connecting to AWS services. This setup is crucial for anyone looking to harness the power of cloud computing for development projects, regardless of the scale.</p><p><strong>1. Downloading and Installing Visual Studio Code:</strong><br>Start by downloading VS Code from the <a href="https://code.visualstudio.com/">official website</a>. After installation, familiarize yourself with its interface. VS Code offers an intuitive layout, making it accessible for both beginners and experienced developers.</p><p><strong>2. Installing the Remote — SSH Extension:</strong><br>One of the most powerful features of VS Code is its extensive library of extensions. For connecting to AWS services, the ‘Remote — SSH’ extension is essential. Here’s how to install it:</p><ul><li>Open VS Code and navigate to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window.</li><li>Search for ‘Remote — SSH’ in the Extensions view search bar.</li><li>Click on the install button next to the ‘Remote — SSH’ extension.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTWoygJ3ij-OPqetgMl5FQ.png" /><figcaption>Remote — SSH Extension</figcaption></figure><p><strong>3. Preparing Your PEM File:</strong><br>Before creating a configuration file, ensure your PEM (Private Key) file has the correct permissions:</p><ul><li>Open a terminal or command prompt.</li><li>Use the command chmod 400 /path/to/your/pem/file.pem to set the required permissions.</li></ul><p>This step is crucial for secure access to your AWS instances.</p><p><strong>4. Creating a Configuration File:</strong><br>After installing the extension, you need to set up a configuration file for your SSH connections. This file will store the details of the AWS machines you wish to connect to.</p><ul><li>Open the Command Palette in VS Code (Ctrl+Shift+P on Windows/Linux, Command+Shift+P on macOS).</li><li>Type ‘Remote-SSH: Open Configuration File’ and select it.</li><li>Choose a location to save your SSH configuration file.</li></ul><p>In the configuration file, add the details of your AWS machine. For example:</p><pre>Host aws-emr<br>    HostName ec2-xx-xxx-xx-xxx.compute-1.amazonaws.com<br>    User ec2-user<br>    IdentityFile /path/to/your/pem/file.pem</pre><ul><li>Host is a friendly name for your remote connection.</li><li>HostName is the public DNS or IP address of your AWS machine.</li><li>User is the default username for the AWS service (e.g., ec2-user for EC2 instances).</li><li>IdentityFile is the path to your private key file (.pem file).</li></ul><p><strong>5. Connecting to Your AWS Machine:</strong><br>Once your configuration file is set up, you can easily connect to your AWS machine:</p><ul><li>Open the Command Palette again.</li><li>Type ‘Remote-SSH: Connect to Host’ and select it.</li><li>Choose the host you configured in the previous step.</li></ul><p>Your VS Code is now connected to your AWS machine, and you can start developing directly on the cloud!</p><h3>Bonus Section: Leveraging Jupyter Notebooks in VS Code for Data Engineers and Scientists</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72pGYo9ojmTTQv_7lwUXSw.png" /></figure><p>In this bonus section, we focus on a feature that’s particularly beneficial for data engineers and scientists: the integration of Jupyter notebooks within Visual Studio Code (VS Code) for interactive development on remote AWS machines like EMR clusters.</p><p>Jupyter notebooks have revolutionized data analysis and visualization, making them indispensable tools for data professionals. By integrating these notebooks with VS Code, especially when connected to AWS EMR clusters, you elevate your data workflows to new heights of efficiency and interactivity.</p><ol><li><strong>Connecting to Your AWS Machine:</strong><br>To use Jupyter notebooks in VS Code:</li></ol><ul><li>Ensure Python is installed on your AWS EMR cluster.</li><li>Crucially, install both the Python and Jupyter Notebook extensions on the remote AWS machine via VS Code.</li><li>Create a new file with a .ipynb extension to start a Jupyter notebook.</li><li>In your notebook, go to the kernel section in VS Code and search for an appropriate Python kernel. This kernel will be used to run your notebook code.</li><li>Consider setting up a separate virtual environment to avoid potential dependency issues with the base environment. This practice ensures a clean and isolated workspace for your projects.</li><li>Once you’ve selected the suitable kernel, you’re ready to begin your interactive coding session.</li></ul><p><strong>2. Running PySpark on AWS EMR Cluster:</strong><br>For data processing with PySpark on an AWS EMR cluster:</p><ul><li>Make sure Spark is installed and configured on your EMR cluster.</li><li>In your Jupyter notebook in VS Code, use findspark to locate and initialize Spark on the cluster</li></ul><pre>import findspark<br>findspark.init()<br><br>from pyspark.sql import SparkSession<br>from pyspark.conf import SparkConf<br><br>conf = (SparkConf()<br>            .setAppName(&quot;test_app&quot;)<br>       )<br><br>spark = SparkSession.builder.config(conf=conf).getOrCreate()</pre><ul><li>With the Spark session created, you can now proceed with your PySpark code, processing data interactively on the EMR cluster.</li><li>With the Spark session created, you can now proceed with your PySpark code, processing data interactively on the EMR cluster.</li></ul><p><strong>3. Advantages for Data Professionals:</strong><br>Integrating Jupyter notebooks in VS Code for AWS EMR work presents significant advantages:</p><ul><li>Freedom from Limitations: Unlike relying on EMR Workspace, default Jupyter notebooks, or Zeppelin provided by AWS, using your preferred editor like VS Code offers unparalleled freedom. Each AWS-provided tool has its own limitations, which are overcome in VS Code.</li><li>Access to Powerful Extensions: VS Code provides access to a wide range of powerful extensions like IntelliSense and GitHub Copilot, which are not available in other platforms.</li><li>Modular Code Development: With VS Code, you can write and test code modularly and interactively. This approach is more efficient than writing code in Zeppelin notebooks and then modularizing it.</li><li>Interactive Development: Directly interact with large datasets on AWS EMR, with real-time data processing and visualization capabilities.</li></ul><h3>Conclusion: Revolutionising Cloud Development with VS Code and AWS</h3><p>In summarizing our exploration of integrating Visual Studio Code (VS Code) with AWS services, it’s evident that this synergy is a game-changer in the world of cloud development. By bridging VS Code with AWS’s powerful cloud infrastructure, notably EMR and EC2, and leveraging the interactivity of Jupyter notebooks, we unlock a streamlined and efficient workflow. This integration not only facilitates a more seamless development experience but also enriches the capabilities of developers and data scientists alike, allowing them to innovate and execute tasks more effectively on the cloud.</p><p>The journey we’ve navigated, from setting up VS Code for remote connections to utilizing advanced features of Jupyter notebooks, underscores a transformative approach to cloud-based projects. It empowers professionals to break free from traditional constraints and harness the full potential of modern development tools. This fusion of VS Code with AWS exemplifies the future of cloud computing, offering a robust platform for cutting-edge development and data exploration. Adopting these practices signifies a step forward into an era of enhanced productivity and innovation in the cloud.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccade6aa4927" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>