<?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 Saptarshi Karmakar on Medium]]></title>
        <description><![CDATA[Stories by Saptarshi Karmakar on Medium]]></description>
        <link>https://medium.com/@saptarshi7karmakar?source=rss-3555410fc5b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NX4L0vX-ROUQ5jH3HqQf_A@2x.jpeg</url>
            <title>Stories by Saptarshi Karmakar on Medium</title>
            <link>https://medium.com/@saptarshi7karmakar?source=rss-3555410fc5b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:01:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saptarshi7karmakar/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[Designing Calibrated Human-in-the-Loop Agents: Bayes Risk Gating with System-1 Decision Models]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://aiadvances.org/designing-calibrated-human-in-the-loop-agents-bayes-risk-gating-with-system-1-decision-models-e8b7b0cf90cd?source=rss-3555410fc5b8------2"><img src="https://cdn-images-1.medium.com/max/2600/0*68cw-4ddKO7VQGrK" width="3769"></a></p><p class="medium-feed-snippet">How pairing discriminative probability calibration with durable state-machine interrupts eliminates operator fatigue and prevents&#x2026;</p><p class="medium-feed-link"><a href="https://aiadvances.org/designing-calibrated-human-in-the-loop-agents-bayes-risk-gating-with-system-1-decision-models-e8b7b0cf90cd?source=rss-3555410fc5b8------2">Continue reading on AI Advances »</a></p></div>]]></description>
            <link>https://aiadvances.org/designing-calibrated-human-in-the-loop-agents-bayes-risk-gating-with-system-1-decision-models-e8b7b0cf90cd?source=rss-3555410fc5b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b7b0cf90cd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Saptarshi Karmakar]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 11:37:08 GMT</pubDate>
            <atom:updated>2026-10-06T11:37:08.738Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Probability Calibration: Turning Raw Model Scores Into Confidence You Can Actually Trust]]></title>
            <link>https://pub.towardsai.net/probability-calibration-turning-raw-model-scores-into-confidence-you-can-actually-trust-3a558e267552?source=rss-3555410fc5b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a558e267552</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Saptarshi Karmakar]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 22:01:01 GMT</pubDate>
            <atom:updated>2026-07-09T01:54:14.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcJNm7nID_c-CHkU" /><figcaption>Photo by <a href="https://unsplash.com/@bildflickan?utm_source=medium&amp;utm_medium=referral">Zarah V. Windh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>“All models are wrong, but some are useful.”</em> <strong>— George E. P. Box</strong></blockquote><p>Box’s words have guided statisticians for decades. But there is a quieter, less celebrated corollary that often goes unnoticed and unaddressed:</p><p><strong><em>A model that is wrong about how confident it is, is wrong in the worst possible way.</em></strong></p><p>That is what this writeup is about. It is about making your model not just accurate — but <em>honest</em>. And the tool that gets you there is called <strong>probability calibration</strong>.</p><p>Accuracy tells you how often a model gets the answer right — on average, across a test set. Calibration tells you something more personal and more actionable: when this model says it is 80% confident, does 80% of the time actually see the right outcome? Those are not the same question, and the gap between them is where models fail in production.</p><p><strong><em>This article is about closing that gap</em></strong><em>.</em></p><h4>The Scenario: A Fleet of 1,400 Vehicles</h4><p>Every example in this article is grounded in a single, concrete domain: predicting whether a vehicle will fail its next inspection. We have 1,400 vehicles, each described by mileage, engine age, brake wear, tyre depth, time since last service, and logged fault codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OTZ6BzvPEAIgGTQGLHN7w.png" /><figcaption><strong>Original Image:</strong> <em>Each row is a vehicle. Red rows failed inspection; White rows passed.</em></figcaption></figure><p>Intuitively shows genuine calibration problems to carry directly into mechanical risk scoring, credit underwriting, or demand forecasting.</p><h3>What Probability Calibration Is?</h3><p>When a Random Forest outputs 0.82, most people read that as &quot;82% chance of failure.&quot; The uncomfortable truth is that this number is shaped by the model’s internal mathematics — the vote-averaging of trees, the loss function, the training distribution. It is a confidence signal, not a probability.</p><p><strong>Probability calibration</strong> is the process of transforming those raw scores so that stated confidence matches observed reality.</p><p>The simplest test: if your model says “82% confident” on 100 vehicles, roughly 82 of them should actually fail. If only 55 fail, your model is overconfident. If 97 fail, it is underconfident.</p><h4>The Calibration Curve: Your Diagnostic Tool</h4><p>The calibration curve (also called a reliability diagram) is built by sorting predictions into probability bins, then comparing the mean predicted probability in each bin to the actual fraction of positives.</p><p>If the model is perfectly calibrated, every bin produces a point on the diagonal line from (0,0) to (1,1). Points below the diagonal indicate overconfidence; points above indicate under-confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvNuJuTNI2VLb9zfjjKThg.png" /><figcaption><strong>Original Image:</strong> <em>The dashed diagonal is perfect calibration. Red circles below it mark an overconfident model; blue squares above it mark an underconfident one.</em></figcaption></figure><p>The anatomy diagram below labels each element of the curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWHP9aFmqJRXTJ6DpkWsFw.png" /><figcaption><strong>Original Image:</strong> <em>Arrows mark the calibration gap — the distance from each bin’s point to the diagonal. Larger gaps mean larger calibration error.</em></figcaption></figure><p><strong>Worked example — reading a single bin:</strong></p><p>Suppose the bin covering predictions between 0.60 and 0.70 contains 50 vehicles. The model’s average score in this bin is 0.65. Of those 50 vehicles, 21 actually failed — an actual fault rate of 0.42. The point on the calibration curve is plotted at (0.65, 0.42). It sits below the diagonal by 0.23, contributing proportionally to the Expected Calibration Error.</p><p>An empirical behavioral insight from different algorithms, re-emphasizing the need of calibration in real world use</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeIZGuTwGG8qm_fsgqUpSQ.png" /><figcaption>Sourced Image: sckit-learn blogs: <a href="https://scikit-learn.org/stable/auto_examples/calibration/plot_compare_calibration.html">https://scikit-learn.org/stable/auto_examples/calibration/plot_compare_calibration.html</a></figcaption></figure><h3>What Perfect Calibration Means</h3><p>Imagine looking only at the 10 vehicles your model rated between 80% and 90% confident of failure.</p><p>If your model is perfectly calibrated, 8 or 9 of those vehicles actually fail — roughly matching the stated 85% confidence. If only 4 of them fail, your model has substantially overclaimed its certainty. That gap is the calibration error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dKIt5jCbqJNOgxRfVSF9g.png" /><figcaption><strong>Original Image:</strong> <em>Left: a well-calibrated model. Points cluster on the diagonal. Right: an overconfident model. Points bow below the diagonal, including the annotated bin where the model said 85% but reality was 40%.</em></figcaption></figure><h4>The Sigmoid Function: Necessary YET not Sufficient</h4><p>The sigmoid function converts any real number into a value between 0 and 1:</p><pre>σ(z) = 1 / (1 + e^(−z))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMcrDG1cuxykL1gIj8Dv9g.png" /><figcaption>Base Sigmoid</figcaption></figure><p>When z is strongly positive, the output approaches 1.0. When z is strongly negative, the output approaches 0.0. At z = 0, the model is maximally uncertain.</p><p>The sigmoid is a necessary step — it produces a bounded number. But it does not guarantee that the number reflects real-world probability. The raw score z is shaped by the model’s training process, not by the actual fault rate of vehicles. That is why calibration is a separate, explicit step.</p><h4>Measuring Mis-calibration: The ECE Score</h4><p>The <strong>Expected Calibration Error (ECE)</strong> quantifies miscalibration in a single number:</p><pre>For each bin:<br>  Calibration Error = |Average Predicted Probability − Actual Fraction of Positives|<br><br>ECE = Σ (bin_size / total_samples) × Calibration Error</pre><p>Lower ECE is better. ECE of 0 is perfect calibration (theoretical). A practical target for production systems is <strong>ECE &lt; 0.05</strong>.</p><pre>def expected_calibration_error(y_true, y_prob, n_bins=10):<br>    bins = np.linspace(0, 1, n_bins + 1)<br>    ece  = 0.0<br>    for i in range(n_bins):<br>        mask = (y_prob &gt;= bins[i]) &amp; (y_prob &lt; bins[i + 1])<br>        if mask.sum() == 0:<br>            continue<br>        bin_acc  = y_true[mask].mean()<br>        bin_conf = y_prob[mask].mean()<br>        bin_size = mask.sum() / len(y_true)<br>        ece += bin_size * abs(bin_acc - bin_conf)<br>    return ece</pre><pre>from sklearn.calibration import calibration_curve<br>import matplotlib.pyplot as plt<br><br>def plot_calibration(y_true, y_prob, model_name=&#39;Model&#39;):<br>    frac_pos, mean_pred = calibration_curve(y_true, y_prob, n_bins=10)<br>    plt.plot([0, 1], [0, 1], &#39;k--&#39;, label=&#39;Perfect calibration&#39;)<br>    plt.plot(mean_pred, frac_pos, &#39;o-&#39;, label=model_name)<br>    plt.xlabel(&#39;Mean Predicted Probability&#39;)<br>    plt.ylabel(&#39;Fraction of Positives (Actual Fault Rate)&#39;)<br>    plt.legend()<br>    plt.tight_layout()<br>    plt.show()</pre><h3>Random Forest: The Classic Overconfidence Problem</h3><p>Random Forests are powerful, but they are notoriously overconfident — and the reason is architectural. Each tree casts a hard 0/1 vote. The forest’s output is the average of those votes. When 100 trees vote, the resulting score is bounded between 0 and 1, but the averaging effect compresses it toward the middle: scores that should be 0.05 end up at 0.25; scores that should be 0.95 end up at 0.72.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TAAFJA12wQCJ26JYAiL5Q.png" /><figcaption><strong>Original Image:</strong> <em>The RF calibration curve (red) runs below the diagonal across all bins. Gap annotations show the difference between predicted and actual at each bin. The middle bins are closest to correct; the extremes are most overconfident.</em></figcaption></figure><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.25, random_state=42, stratify=y<br>)<br><br>rf_raw = RandomForestClassifier(n_estimators=150, random_state=42)<br>rf_raw.fit(X_train, y_train)<br>p_raw = rf_raw.predict_proba(X_test)[:, 1]<br><br>print(f&#39;ECE (Raw RF): {expected_calibration_error(y_test, p_raw):.4f}&#39;)</pre><pre>Output: ECE (Raw RF): 0.0521</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsp0dCMXpss7H8xQ5jZwcg.png" /><figcaption><strong>Original Image:</strong> Score/Output Expanded</figcaption></figure><h3>Calibration Beyond Classification: Regression</h3><p>Calibration applies equally to regression models, but the measure changes. Instead of asking whether stated probabilities match actual frequencies, we ask whether stated prediction intervals contain the true value at the claimed rate.</p><p>A model that produces 95% prediction intervals should have 95% of true values falling inside them. When only 81% do, the intervals are too narrow — the model is underestimating its own uncertainty.</p><p><strong>Example: predicting vehicle repair cost</strong></p><pre>from sklearn.linear_model import LinearRegression<br><br>model = LinearRegression().fit(X_tr, y_tr)<br>y_pred = model.predict(X_te)<br>std_err = np.std(y_tr - model.predict(X_tr))<br><br>z = 1.96  # 95% confidence<br>lower = y_pred - z * std_err<br>upper = y_pred + z * std_err<br><br>coverage = ((y_te &gt;= lower) &amp; (y_te &lt;= upper)).mean()<br>print(f&#39;Claimed: 95.0%  Actual: {coverage * 100:.1f}%&#39;)</pre><pre>Output: Claimed: 95.0%  Actual: 81.4%</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7Yu8xoSaG0_Bj4TKugWWg.png" /><figcaption><strong>Original Image:</strong> <em>Left: before calibration — intervals are too narrow, true values escape frequently. Right: after scaling — intervals now contain approximately 95% of true values.</em></figcaption></figure><p><strong>The fix is a single scaling step:</strong></p><pre>scale     = 0.95 / coverage  # widen by the coverage ratio<br>midpoint  = (lower + upper) / 2<br>half_w    = (upper - lower) / 2<br>new_lower = midpoint - scale * half_w<br>new_upper = midpoint + scale * half_w</pre><h3>Calibration in Time Series</h3><p>Time series models like ARIMA produce point forecasts and confidence bands. Those bands rest on distributional assumptions — typically Gaussian errors — that break down when the real data contains seasonality, structural breaks, or heavy tails.</p><p><strong>Example: monthly fleet fault count forecasting</strong></p><pre>from statsmodels.tsa.arima.model import ARIMA<br><br>model    = ARIMA(train, order=(2, 1, 2)).fit()<br>forecast = model.get_forecast(steps=6)<br>pred_ci  = forecast.conf_int(alpha=0.05)  # 95% stated bands<br><br>coverage_ts = ((test &gt;= pred_ci.iloc[:, 0]) &amp;<br>               (test &lt;= pred_ci.iloc[:, 1])).mean()<br>print(f&#39;95% CI Coverage: {coverage_ts * 100:.1f}%&#39;)</pre><pre>Output: 95% CI Coverage: 66.7%</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcmvJz32qPfog84k5lyCmg.png" /><figcaption><strong>Original Image:</strong> <em>Left: raw ARIMA confidence bands — several actual values (red dots) fall outside the stated 95% band. Right: after empirical scaling, the bands are wider and the actual coverage matches the stated level.</em></figcaption></figure><p>The fix is identical in spirit to the regression case: widen the bands by the ratio of claimed to actual coverage.</p><pre>scale_ts = 0.95 / coverage_ts<br>mid      = (pred_ci.iloc[:, 0] + pred_ci.iloc[:, 1]) / 2<br>hw       = (pred_ci.iloc[:, 1] - pred_ci.iloc[:, 0]) / 2<br>new_lo   = mid - scale_ts * hw<br>new_hi   = mid + scale_ts * hw</pre><h3><strong>Calibration comparison across model types:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H356I7Es-YElqLIbUcntGg.png" /><figcaption><strong>Original Image:</strong> Applicability Mental Model</figcaption></figure><h4>The Coverage Curve: Regression’s Equivalent of the Calibration Curve</h4><p>For regression and time series, the calibration curve has a direct analogue: the <strong>coverage curve</strong>. Instead of binning by predicted probability, we plot stated confidence level on the x-axis and actual coverage on the y-axis. A perfectly calibrated model lies on the diagonal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHNYFUMHfJNvtl4jLuYyOg.png" /><figcaption><strong>Original Image:</strong> <em>Red circles show an uncalibrated regression model: when it claims 95% intervals, actual coverage is only 81%. Green triangles show the same model after calibration: the points now follow the diagonal.</em></figcaption></figure><p>Reading a coverage curve is identical to reading a calibration curve: points below the diagonal mean the model is more confident than it should be; points above mean it is more cautious than necessary.</p><h4>Low Confidence Is Information, Not Failure</h4><p>A model that says <em>“I am 51% confident this vehicle will fail”</em> is not malfunctioning. It is being honest about its uncertainty. That honesty is what makes calibration valuable: once your scores are calibrated, you can treat uncertainty as a routing signal rather than noise.</p><pre>def triage_vehicle(prob, high_thresh=0.75, low_thresh=0.25):<br>    if prob &gt;= high_thresh:<br>        return &#39;SCHEDULE INSPECTION — High Fault Risk&#39;<br>    elif prob &lt;= low_thresh:<br>        return &#39;CLEAR VEHICLE — Low Fault Risk&#39;<br>    else:<br>        return &#39;REFER TO MECHANIC — Model Uncertain&#39;</pre><p>This three-way routing is one of the most practical downstream uses of calibration. It keeps high-confidence predictions in the automated lane and routes genuinely uncertain cases to humans.</p><h3>Fixing Calibration: Platt Scaling and Isotonic Regression</h3><p>Two methods dominate real-world calibration for classifiers.</p><p><strong>Platt Scaling</strong> fits a logistic (sigmoid) function on top of the raw model scores:</p><pre>Calibrated Probability = σ(A × raw_score + B)</pre><p>The parameters A and B are learned from a held-out calibration set. Platt Scaling works well for SVMs and neural networks where miscalibration is smooth and systematic.</p><p><strong>Isotonic Regression</strong> fits a monotone step function — no shape assumption, purely data-driven. It is more flexible than Platt Scaling and better suited to Random Forest and Gradient Boosting, where the miscalibration is non-linear and irregular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l46-tVJmxeDCaYFfWYRLPA.png" /><figcaption><strong>Original Image:</strong> <em>Left: Platt Scaling applies a smooth sigmoid remap. Right: Isotonic Regression learns a step function, correcting each region of the score range independently.</em></figcaption></figure><pre>from sklearn.calibration import CalibratedClassifierCV<br><br># Platt Scaling<br>rf_platt = CalibratedClassifierCV(<br>    RandomForestClassifier(n_estimators=150, random_state=42),<br>    method=&#39;sigmoid&#39;, cv=5<br>)<br>rf_platt.fit(X_train, y_train)<br>p_platt = rf_platt.predict_proba(X_test)[:, 1]<br><br># Isotonic Regression<br>rf_iso = CalibratedClassifierCV(<br>    RandomForestClassifier(n_estimators=150, random_state=42),<br>    method=&#39;isotonic&#39;, cv=5<br>)<br>rf_iso.fit(X_train, y_train)<br>p_iso = rf_iso.predict_proba(X_test)[:, 1]</pre><p>Before and After: <strong><em>Measuring the Improvement</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xAtK3XqItQVBCDTjWGSPw.png" /><figcaption><strong>Original Image:</strong> <em>Left chart: three calibration curves. The raw RF (red) deviates most from the diagonal. Platt (orange) gets closer. Isotonic (green) tracks the diagonal most faithfully. Right chart: score distributions after calibration spread toward more decisive values.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2Y8mmvvmYv5uVk5ve-Bsg.png" /><figcaption><strong>Original Image:</strong> <em>Left: raw RF calibration curve bowing below the diagonal. Right: after isotonic calibration, the curve aligns with the diagonal across all bins.</em></figcaption></figure><p><strong>What changed, bin by bin:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPe-_6ZjU3sq3I9mi2uJRw.png" /><figcaption>Original Image: The Transition through Transform-Calibration</figcaption></figure><p>Isotonic Regression does not apply a uniform correction. It learns a different correction for each region of the score range, <strong><em>which is precisely why it outperforms Platt Scaling for models with irregular miscalibration patterns.</em></strong></p><pre>ece_raw   = expected_calibration_error(y_test, p_raw)<br>ece_platt = expected_calibration_error(y_test, p_platt)<br>ece_iso   = expected_calibration_error(y_test, p_iso)<br><br>print(f&#39;ECE — Raw RF:   {ece_raw:.4f}&#39;)<br>print(f&#39;ECE — Platt:    {ece_platt:.4f}&#39;)<br>print(f&#39;ECE — Isotonic: {ece_iso:.4f}&#39;)</pre><p><strong>Note:</strong> The need and usage of <em>Probability Calibration</em> goes beyond the <em>Statistical, Machine Learning</em> paradigms to deep into more complex sciences such as <em>Deep Learning, — extending the techniques of Platt Scaling, Isotonic Regression, Temperature Scaling etc.</em></p><h4>End To End View</h4><pre>import numpy as np<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.calibration import CalibratedClassifierCV, calibration_curve<br>from sklearn.model_selection import train_test_split<br><br># 1. Train raw model<br>rf_raw = RandomForestClassifier(n_estimators=150, random_state=42).fit(X_train, y_train)<br><br># 2. Train calibrated model<br>rf_cal = CalibratedClassifierCV(<br>    RandomForestClassifier(n_estimators=150, random_state=42),<br>    method=&#39;isotonic&#39;, cv=5<br>).fit(X_train, y_train)<br><br># 3. Get probabilities<br>p_raw = rf_raw.predict_proba(X_test)[:, 1]<br>p_cal = rf_cal.predict_proba(X_test)[:, 1]<br><br># 4. ECE<br>def ece(y_true, y_prob, n_bins=10):<br>    bins, score = np.linspace(0, 1, n_bins + 1), 0.0<br>    for i in range(n_bins):<br>        m = (y_prob &gt;= bins[i]) &amp; (y_prob &lt; bins[i + 1])<br>        if m.sum():<br>            score += (m.sum() / len(y_true)) * abs(y_true[m].mean() - y_prob[m].mean())<br>    return score<br><br>print(f&#39;ECE (Raw):        {ece(y_test, p_raw):.4f}&#39;)<br>print(f&#39;ECE (Calibrated): {ece(y_test, p_cal):.4f}&#39;)<br><br># 5. Triage<br>def triage(p, hi=0.75, lo=0.25):<br>    if p &gt;= hi: return &#39;SCHEDULE INSPECTION&#39;<br>    if p &lt;= lo: return &#39;CLEAR&#39;<br>    return &#39;MANUAL REVIEW&#39;</pre><h3>The Ultimate Guide</h3><h4>When to Calibrate — and Which Method to Use (A Sample view)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2epjnGNIXaAK9kr7vOYVaA.png" /><figcaption><strong>Original Image:</strong> The common thread: <strong>if a probability score drives a decision or a cost, it must be calibrated.</strong></figcaption></figure><p><strong>Algorithm-to-method mapping</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-58EdWp08qlxZDeHt4ncqg.png" /><figcaption><strong>Original Image:</strong> Algorithm-to-method mapping</figcaption></figure><p><strong>Decision guide</strong></p><ul><li>Fewer than ~1,000 calibration samples : use Platt Scaling (Parametric)</li><li>More than ~1,000 samples : try Isotonic Regression (Non-Parametric)</li><li>Logistic Regression output → verify ECE before adding anything</li><li>Prediction intervals (regression, time series) → coverage-based scaling, not Platt or Isotonic</li><li>Always plot the calibration curve first; the shape will tell you which correction to apply</li></ul><h3>Conclusion</h3><p><strong><em>Accuracy</em></strong> is what a model does on average. <strong><em>Calibration</em></strong> is what a model does on any given prediction — whether the confidence it expresses corresponds to the confidence it has earned.</p><p>A Random Forest that says “87% confident this vehicle will fail” when it is really only 64% right in that range is not just inaccurate. It is systematically misleading every downstream decision that uses that number: the inspection schedule, the parts order, the staffing plan.</p><p>Calibration is how you fix that. It is ten lines of code. It fits into any evaluation pipeline. It costs nothing in latency or model complexity. And it is one of the most underinvested practices in applied machine learning.</p><p>Build models that are accurate. Then go further, and build models that are honest.</p><p><em>Further reading</em></p><ul><li><em>Guo et al. (2017) — On Calibration of Modern Neural Networks — ICML</em></li><li><em>Niculescu-Mizil &amp; Caruana (2005) — Predicting Good Probabilities with Supervised Learning</em></li><li><em>Platt (1999) — Probabilistic Outputs for Support Vector Machines</em></li><li><em>scikit-learn: </em><em>sklearn.calibration.CalibratedClassifierCV, </em><em>sklearn.calibration.calibration_curve</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a558e267552" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/probability-calibration-turning-raw-model-scores-into-confidence-you-can-actually-trust-3a558e267552">Probability Calibration: Turning Raw Model Scores Into Confidence You Can Actually Trust</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GenAI Concepts mMade Simple: A Human-Mnemonics Guide]]></title>
            <link>https://pub.towardsai.net/genai-concepts-mmade-simple-a-human-mnemonics-guide-b933de500f11?source=rss-3555410fc5b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b933de500f11</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Saptarshi Karmakar]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 00:02:50 GMT</pubDate>
            <atom:updated>2026-01-13T04:20:59.174Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>GenAI Concepts Made Simple: A Human-Mnemonics Guide</strong></h3><figure><img alt="An idea to understand Generative AI in new perspective." src="https://cdn-images-1.medium.com/max/1024/0*tvxj332t8CTZrs_9" /><figcaption>Photo by <a href="https://unsplash.com/@procopiopi?utm_source=medium&amp;utm_medium=referral">Omar:. Lopez-Rincon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Generative AI is reshaping the industries rapidly. Yet, reliable reports suggest that a significant (~60%) workforce population still struggle to grasp the foundational concepts and modus operandi, majorly due to the inherent complexities. This article takes a thoughtful attempt with a fresh perspective to use human-life analogies making GenAI concepts intuitive, memorable and applied.</p><p><strong>Read the Read</strong></p><blockquote>“If you can’t explain it simply, you don’t understand it well enough.” — Albert Einstein</blockquote><blockquote>“Out of intense complexities, intense simplicities emerge.” — Winston Churchill</blockquote><p>Motivated and Challenged by these famous quotes, this article takes inspiration from our <strong>‘being’</strong> to explain the core concepts of Generative AI. Aim is to establish easy mnemonics with similarities of these concepts to <strong>‘Human’</strong> journey of life.</p><p>Two points to consider as we take the journey, the article covers the Generative side of AI, not the Conventional/Traditional AI landscape (Machine/Deep learning). The concepts are intentionally kept at abstract level, delving deep into each area on our own is highly recommended.</p><p><strong>Foundation Models = School Students</strong></p><figure><img alt="Conceptual similarity of ‘human kid going through the school days’ to ‘Foundation Language Model training’" src="https://cdn-images-1.medium.com/max/936/1*jjHLnMcbUn1jrrjO_SUowA.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>Picture a person just out of school, armed with basic knowledge and social skills to engage with the world. Every action ,draws from what they have learned. A deeper lead into our actions prevails a <strong>‘Cause’</strong>. Figuratively, the cause creates a gap to be filled with the available knowledge. That’s exactly all that the Human individuals or foundation models do:</p><p><em>Drawing from the stored wisdom to complete the puzzle of any question, one piece at a time.</em></p><p><strong>For example</strong>, When asked to talk about the history of a country, in our mind it’s a question “<em>The history of the country is </em><strong><em>__GAP TO FILL__</em></strong>”. Then we subscribe the knowledge from brain (gathered from books/sessions in schools) and structure to fill the gap with speech or text or drawing (again gathered/trained from school or sessions).</p><p>In the world of <strong>Generative AI</strong>, the <strong><em>Foundation Language Models</em></strong> are the core. These models have conceptually evolved from the <em>Sciences of Natural Language Processing (NLP) and Deep Learning (DL)</em> with <strong>Transformers</strong> at core. These models are trained with common internet accessed digital knowledge, which is efficiently stored and accessed as <strong>PARAMETERS</strong>. These models are trained to fill the gaps by understanding the context (The way we Human, do really).</p><p>The history question from the <strong>example</strong>, will trigger the model to rely on the <em>knowledge</em> and <em>behavior</em> stored in the <em>parameters</em> and structure an output.</p><p>The astonishing <em>similarity</em> between the foundation model and a student fresh out of school are</p><ol><li>Conceptually with common knowledge, perform tasks that are largely of common nature.</li><li>Like a student’s knowledge is limited to the learnings from school, foundation modes are <em>limited to their respective </em><strong><em>data cut-off</em></strong>. For example, if the knowledge stops at 2024, a new planet discovered in 2025, neither the model nor the student can talk about it until they acquire the new knowledge.</li></ol><p>To maintain simplicity, the article refrains from deeper insights into the fascinating science behind information storage for both Brain and Parameters.</p><p>Some of the prominent model providers that we should know about are ;<strong><em>OpenAI-GPTs, Anthropic-Claude, Google-Gemini, Meta-Llama, Mistral-AI</em></strong> etc. General understanding of a specific model would be:</p><p><strong>LLaMA 2–70B</strong> is a 70 billion parameter foundation model from <em>Meta</em>.</p><p><strong>Note:</strong> Quantum of parameters, drives the size and computational expenses of the model. Hence, the <em>Large Language Models (LLMs)</em> and <em>Small Language Models(SLMs)</em> are used as fit to the use cases.</p><p>Deeper understanding of Language Model’s internals with Transformers a must read: [<a href="https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf">1</a>] <a href="https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf">Attention is all you need</a></p><p><strong>Specialized Models = College Majors</strong></p><figure><img alt="Conceptual Similarity between Human college studies to a post-trainng of Language Models." src="https://cdn-images-1.medium.com/max/936/1*CREHkPf2TStDXIhG12q6RA.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>Post schooling, we take up specialization in <em>Science, Arts, Engineering and other Majors;</em> head to tune ourselves in different directions of expertise with the motivation to solve real world problems in future. Hence, we delve deeper into area specific concepts and tools.</p><p>The pioneer organizations of the Generative AI field by practice tune the foundation models for more specific purposes with deeper concepts and tools. Like a college graduate in a specific field, the specialized models are then purposed to be precise to a focused area of expertise with related deep knowledge, reasoning ability and tool usage capability.</p><p><strong>Example: </strong>A Math Graduate knows the foundation to deeper concepts of Mathematics and can use scientific calculator to solve complex mathematics problem.</p><p><strong>DeepSeekMath-Instruct 7B</strong> is specialized model, trained further on advanced mathematical concepts. This can solve more complex math problems and use scientific tools as relevant. Like the Math graduate was a school student before, this specialized model is version built on training <strong>DeepSeek-base foundation model</strong> further.</p><p>The specialization is not limited to the text-based concepts. Like human, the expertise can be tuned for different modalities like <em>Image, Speech</em> etc, which leads to models tuned to generate images, videos. e.g. <em>DALL-E 3 an image generation model.</em></p><p><strong>Prompting = Art of Asking</strong></p><figure><img alt="Effectiveness of Human conversation depends on art of asking/talking. This is conceptually similar to Effective Prompting techniques to Language Models." src="https://cdn-images-1.medium.com/max/936/1*oVblqD8rAk_D0H6LiBCFLA.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>Prompting is a ubiquitous term in Generative AI space. This holds the same meaning of <em>asking a question</em>, be it to a <em>human or a language model</em>. Like the art of human communication, the effective answers will rely on preciseness, clarity and structure of the prompt. In this space, a moderately deeper concept is the <strong>Context</strong>. During our conversations we use context &amp; examples to maintain effectiveness, which is also applicable when a model is prompted.</p><p><strong>Example: </strong>Imagine you phoned your buddy a <em>Professor in Botany</em>, while you’re with a grade 5 students’ group;</p><p>“<strong><em>Explain Photosynthesis”</em></strong> is what you asked.</p><p>A possible multifold complex explanation from your friend, almost certainly will rule out any possible future <em>Botanist</em> from that group.</p><p>You would be better off with: <strong><em>“Context: You are a 5th-grade teacher. Explain photosynthesis using simple analogies and a fun, engaging tone for a science class”</em></strong></p><p>And that’s the <em>art of asking questions to human or prompting an AI model for suitable answer.</em> The number of practices to tune the prompts, led to a prominent stream of its own called <strong>Prompt Engineering.</strong> A simpler strategy is adding examples to the prompt:</p><ol><li><strong>Zero-Shot</strong>: No Examples.</li><li><strong>One-Shot</strong>: One Example.</li><li><strong>Few-Shots</strong>: Few Examples.</li></ol><p>While the terms may appear different to our regular conversations, the purpose remains the same on how you <strong>influence Human and AI Model</strong> to answer effectively to your specific need.</p><p><strong>Model Hallucination = Human Guess Work</strong></p><p>I’m sure we are familiar to the situations (at least once), where we socially looked smart though conveyed wrong information. Either the <em>fact was not known</em> at all and we guessed, or the <em>fact in mind simply had wrong/biased</em> <em>foundation</em>. And that’s in <em>GenAI world, is hallucination</em>. As answering is related to smartness, the <strong>non-timid</strong> nature of models will lead to a <strong>fabricated, nonsensical or incorrect answer</strong>.</p><p>The core reasons are like humans:</p><ol><li><strong>Probabilistic Nature:</strong> Models predict the next most likely word, not necessarily the most truthful one.</li><li><strong>Training Data:</strong> Biases or inaccuracies in massive datasets can be replicated or misinterpreted.</li><li><strong>Context Limitations:</strong> Difficulty remembering long conversations or understanding nuanced prompts.</li></ol><p><strong><em>Re-training</em></strong> may sound as an obvious choice, it’s still the <strong><em>most computationally expensive</em></strong>. Hence, we’ll see alternative processes in subsequent sections.</p><p><strong>RAG = Open Book Exam</strong></p><figure><img alt="Conceptual similarity between Retrieval Augmented generation (RAG) to Human taking an Open Book Exam." src="https://cdn-images-1.medium.com/max/936/1*AmsGOtoenLWSrqpVyU-1-w.png" /><figcaption>Source: Image by the Author</figcaption></figure><p><strong>Retrieval Augmented Generation or RAG</strong>, is a way to supply <em>external knowledge as context</em> to the model to answer better. The external knowledge is mostly stored in Vector Databases for similarity search. This is also an <em>effective process to eliminate/reduce hallucination</em>. Drawing a parallel to the set up of an exam,</p><ol><li><strong><em>Candidate = Language Model (Foundation and/or Specialized Model)</em></strong></li><li><strong><em>Question Papers = Prompt</em></strong></li><li><strong><em>Books = Necessary knowledge in vector database</em></strong></li><li><strong><em>Book Indexes = Vector Similarity and Search Indexes (To enable Faster Search)</em></strong></li><li><strong><em>Answers = Answers</em></strong></li></ol><p>As the name ‘<strong>RAG’</strong> suggests, the key words from the question/prompt helps identifying the topics from the book/vector database which stores the relevant information as text/knowledge vectors. That helps the human candidate/model to extract and enrich information which might not be known already. With that as context, the generated answer is bound to be factually better.</p><figure><img alt="Detaild technical steps involved in RAG process. Question -&gt; Similarity Search in Information Base -&gt; Enriched/Augmented Question with retrieved information -&gt; Prompt to Langauge Model -&gt; Answer" src="https://cdn-images-1.medium.com/max/936/1*bGJO_bBzNp-YvgErhK3HZg.png" /><figcaption>Source: Image by the Author</figcaption></figure><p><strong>Note:</strong> This is one of the most applied techniques in Generative AI landscape. The evaluation strategy has two steps,</p><ol><li>Evaluate Retrieval effectiveness.</li><li>Evaluate overall Generation level.</li></ol><p>Frameworks like <strong>Ragas, DeepEval</strong> are prominent frameworks in this space.</p><p><strong>AI Agents = Workforce Teams</strong></p><figure><img alt="Image depicts the similarity of Teamwork and Agentic collaboration where each member in the team is represented as an agent in the Agentic workflow." src="https://cdn-images-1.medium.com/max/936/1*AEbbYT-eTxvPJAc5hw5vMA.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>With college/specialization accomplished, we embark to solve real world problems: the Job (or by other means); we become part of workforce. We take part of teams which is built with individuals with specific <em>expertise, responsibilities and accountability</em>. Some parts and decisions are <em>autonomous some are dependent</em>.</p><p>A typical software team consists of people with <em>Design responsibility/expertise, some for development(s). Mostly the team is needs one person for process management and one for project management/overseeing</em>.</p><p>The Generative AI paradigm to functionally scale &amp; solve real world problem, require similar dimensions in terms of variety of expertise and responsibilities working together. That’s what is known as <strong>Agentic</strong>. An <em>AI Agent is like an individual with specific </em><strong><em>background, responsibility and tools</em></strong>. Such variety of Agents are employed together to tasks and purposes, to together solve the problem in hand. the <em>techniques</em> for the agents to collaborate are inspired from the way teammates speak internally, exchange relevant information.</p><p>Notably, each agent’s built and behavior reflects the human counter part’s ways of working. We <strong>reason</strong> with the information we have or can access for the task in hand. We use <strong>tools</strong> relevant to the job, and we take <strong>action</strong> to succeed in the task. We evaluate the progress and we <strong>retry</strong> as needed. The <strong>Reason-Action</strong> to <strong>ReAct</strong> is the core functional philosophy for AI Agents.</p><p><strong>Note:</strong></p><p>1. [<a href="https://docs.crewai.com/en/concepts/agents">2</a>] Crew.AI , [<a href="https://docs.langchain.com/oss/javascript/langchain/agents">3</a>] LangChain, LangGraph are the most prominent and evolved frameworks in this technology space.</p><p>2. There are protocols like [<a href="https://modelcontextprotocol.io/docs/getting-started/intro">4</a>] MCP (Model Context Protocol), A2A (Agent-To-Agent) which are built to simplify the interaction of GenAI models to Non-AI software components.</p><p><strong>Fine-tuning = Professional Up-skilling</strong></p><figure><img alt="Like Human professionals take training and sessions to up-skill in a particular professional field, Language Models can be fine tuned to get better at a specific job." src="https://cdn-images-1.medium.com/max/936/1*jOVajyVZ5eF-p3nJ35icBw.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>Getting better at the job is a natural drive to us, the <strong>Human</strong>. While the opportunity might lie continual sense of specifics, technology, concept etc; the need is certainty due to the gap of knowledge/behavior between excising and now. Considering the <em>cost and effort</em>, we don’t go through college again; rather we <em>rely on existing capability to take up smaller courses and trainings</em>.</p><p>Training is the most expensive task in Gen AI space. Hence, The AI world have evolved to something very similar, known as <strong><em>Post-Training/Fine-Tuning</em></strong><em> a cost-effective way (only a few layers) for the models to learn new specific knowledge and behavior</em>. This is a mammoth topic on its own, but adhering to the simplicity of the article we’ll leave it to a few important terms:</p><ol><li><strong>Quantization:</strong> Mathematically alter the dimension of model parameters/knowledge into smaller space to significantly reduce the model size without greatly compromising the model’s quality.</li><li><strong>Parameter-Efficient Fine-Tuning (PEFT):</strong> A cost-effective way to adapt models through adjustments to only a small fraction of model parameters.</li><li><strong>Knowledge Distillation:</strong> Transfers knowledge from large models to smaller ones.</li><li><strong>PLAN-TUNING:</strong> A specialized method using synthetic planning steps to boost complex reasoning.</li></ol><p><strong>Disclaimer</strong></p><figure><img alt="Human can naturally remember information till some extent without a extended learning process. The Language models cant naturally remember information without re-training or fine tuning." src="https://cdn-images-1.medium.com/max/936/1*GgjEHPCIS_sge6bJknRi9w.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>The conceptual similarities between the realms of Human and Generative AI Models are truly astonishing. That said, there exist a clear difference in the memory:</p><p><strong><em>‘The language models are stateless while Human mind is not’</em></strong></p><p>Even when we perform some actions we memorize and learn effortlessly, the core language models don’t memorize the conversations automatically, neither does it automatically learn.</p><p><strong>Example: </strong>When we meet a new person, we ask the name and we memorize. We can use that as a reference information from later conversations. Same situation with the core language models, will need the name every time.</p><p><strong>Note:</strong> Some might differ to the idea saying <em>Chat-GPT/Grok</em> etc remembers information from our interactions. That’s done by the framework, platform and the complete ecosystem around the core models which stores and uses that information when we chat with the models. Core Language Models are completely stateless.</p><p><strong>Recap</strong></p><figure><img alt="A theoretical similarity between Human and GenAI concepts such as School Kids = Foundation Model ; College Student = Specialized Model ; Asking Question = Prompting ; Guess Work = Hallucination ; Open Book Exam = RAG ; Human Workforce =  AI Agents ; Professional Training = Fine Tuning;" src="https://cdn-images-1.medium.com/max/580/1*TZg7dXyBkJFpmvojPlFRcw.png" /><figcaption>Source: Image by the Author</figcaption></figure><p>Generative AI concepts mirror our human journey, from learning basics to mastering specializations. By drawing a simple parallel to the concepts through relatable analogies, this guide hopefully made the complex the simple. If this article was a thoughtful nudge, please follow!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b933de500f11" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/genai-concepts-mmade-simple-a-human-mnemonics-guide-b933de500f11">GenAI Concepts mMade Simple: A Human-Mnemonics Guide</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to better employ automated decision-making for business]]></title>
            <link>https://medium.com/@saptarshi7karmakar/how-to-better-employ-automated-decision-making-for-business-26cb2e8323bc?source=rss-3555410fc5b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/26cb2e8323bc</guid>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Saptarshi Karmakar]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 14:40:00 GMT</pubDate>
            <atom:updated>2024-01-08T04:34:22.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>Real-world use cases are largely one-sided about Accuracy-Business Value trade-off</h4><p><strong><em>Introduction</em></strong></p><p>Data-driven, automated decision-making is a common practice in today’s business intelligence environment. The best method to unlock value is nearly always to serve decisions fast and first. Many algorithms, including Deep Learning, Decision Trees, Classification, and others, have been successfully applied in this field. These ideas are being rapidly adopted into a wide range of business processes in an effort to speed up decision-making and minimise the need for human interaction.</p><p>These concepts are great (and probably easy) to apply, but how reliably we can extract the business value is undeniably an interesting problem statement on its own. To put it simply, <em>for you to rely on a decision-maker in a process for your business, you need to always ask:</em></p><blockquote><em>“How accurate is the decision(s) making model? VS How right or wrong are the decision(s)?”.</em></blockquote><p>In this article, we’ll look at the enabling concepts to answer these questions correctly. Through this journey, we aspire to make the most of decision-making and classification algorithms that address the exact business case.</p><p><strong><em>Assumptions</em></strong></p><p>Background on classification algorithms, confusion matrixes, and simple mathematical concepts leads to unequivocally applying the concepts from the article.</p><p>To keep the journey simple, we’ll talk about the binary class decision-making problem, where the target classes can only be ‘Y’ or ‘N’.</p><p><strong><em>Problem Statement under the lens</em></strong></p><p>In a simple world, the distribution of classes is balanced, and the individual wrong decisions for either of the classes are of negligible importance. In such a case, blunt <em>Accuracy</em> is the simple answer.</p><ol><li>The possibility of the wrong classification is lessened.</li><li>The cost of incorrect classifications can be ignored.</li></ol><p>Real-world business cases are very different, as the distribution of classes is mostly imbalanced, and correctly predicting one class is of higher importance than another. To draw an analogy, let us take a sample set of 10 predictions vs. actual observations from insurance claim anomaly detection decision-making intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PbAXyWt2bqyPG3HL15D29A.png" /><figcaption>fig 1: Y: In-valid Claim needs review, N: Valid Claim needs no review</figcaption></figure><p><strong>Y</strong>: Invalid claim needs review. <strong>N</strong>: A valid claim needs no review.</p><p>Enforcing the business context significantly influences the process.</p><ol><li>As the actual observations are very skewed towards valid claims, it’s obvious that the algorithm predictions will align towards similar distributions. <em>Hence, accuracy will be high and misleading, which is 0.8 in this example</em>.</li><li>Observation 8: A claim with a true anomaly being classified as a valid one can have a significant financial impact.</li><li>Observation 10: When a valid claim is classified for review, probably that’s of lesser business impact as it’ll trigger manual review.</li></ol><p><strong><em>How do we address it?</em></strong></p><p>All we need to do is to mathematically translate the business needs into the model and evaluation process. Let’s exercise some of the fundamental concepts which’ll pave the way forward for us.</p><h4><em>Categorization of Decision or Classes</em></h4><p>The <em>Confusion Matrix</em> is a widely used tool to map decisions to categorizations of being right or wrong. It’s a simple process to draw a two-dimensional matrix representing <em>Actual Observations vs Predictions</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*BTTmUClFSBqkbMEUjIwQGw.png" /><figcaption>fig 2: Derived Confusion Matrix for the sample</figcaption></figure><p>Referring to the example</p><p><strong><em>TP: True Positives</em></strong>, both predicted and actual values, are marked for review.</p><p><strong><em>FP: False Positive</em></strong>, predicted for review but actual is not.</p><p><strong><em>FN: False Negative</em></strong>, predicted as not for review but actual is in-valid (up for review)</p><p><strong><em>TN: True negative</em></strong>: both predicted and actual values are marked for non-review (valid).</p><p><strong><em>Shifting the focus from Accuracy to Business context-driven measures</em></strong></p><h4>Accuracy:</h4><p>This is a native measure of the model’s prediction quality, ignoring the kinds of errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*KYZzfwRr5We1FEujR2T1MA.png" /><figcaption>fig 3: Accuracy equation and relation to Confusion Matrix</figcaption></figure><h4>Precision:</h4><p>This is a measure of the model’s ability to predict the positive class accurately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAIC9XckWrDUrmbgfKWgJw.png" /><figcaption>fig 4: Precision equation and relation to Confusion Matrix</figcaption></figure><p>Precision trades off <em>False Negative</em> errors in order to improve <em>True Positives</em>. Precision varies from 0.0 to 1.0, while closer to 1 represents a better possibility of the model detecting correct positives. Ideal to use when the cost of <em>False Positive</em> is high.</p><h4>Recall:</h4><p>This measure is also known as TPR (True Positive Rate or Sensitivity), as it measures at what rate the actual positives are identified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9Me-R-dFMNa4EO9HEkXiw.png" /><figcaption>fig 5: Recall equation and relation to Confusion Matrix</figcaption></figure><p><em>False Positives</em> are traded-off in order to improve the chance of covering most of <em>True Positive cases</em>. This measure also varies from 0.0 to 1.0, aspiring to be closer to 1.0. This is a good measure for use cases with a high cost of <em>False Negatives</em>.</p><p>To solve the use cases with a balanced cost of <em>False Positives</em> and <em>False Negatives</em>, there are some effective measures to apply.</p><h4>F1 Score:</h4><p>F1 scores bring together both <em>Precision and Recall</em> by applying a weighted average. Using this method, we can optimize the model for a balanced cost-use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*ECwYNzB3uZXLypMxD4wBCw.png" /><figcaption>fig 6: F1 Score equation and relation to Confusion Matrix</figcaption></figure><h4>AUC:</h4><p>The <em>Receiver Operating Characteristic Curve (ROC)</em> is a graph representation of how a classification model behaves, measuring <em>True Positive Rate (TPR) vs False Positive Rate (FPR)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*7Xz7ZM4c9w4xHan9MyiNYg.png" /><figcaption>fig 7: TPR and FPR equation and relation to Confusion Matrix</figcaption></figure><figure><img alt="https://en.wikipedia.org/wiki/Receiver_operating_characteristic#/media/File:Roc_curve.svg" src="https://cdn-images-1.medium.com/max/646/1*Ab5HedtJlqSHe01wdkbI_g.png" /><figcaption>fig 8: ROC AUC with different classification threshold. image src: <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic#/media/File:Roc_curve.svg">https://en.wikipedia.org/wiki/Receiver_operating_characteristic#/media/File:Roc_curve.svg</a></figcaption></figure><p>AUC is Area Under ROC, which is an iterative process to plot and measure the area under the curve given a varied classification threshold.</p><p>A <em>decision/classification</em> threshold is a fractional value set from the business context to measure if a predicted probabilistic decision is to be considered 1 (positive) or 0 (negative).</p><p>The natural choice of the <em>classification threshold is 0.5</em>, which represents the random plane split. For real-world cases, this threshold is set based on the cost sensitivity of the error for <em>FP vs. FN</em>.</p><p><em>Considering the example that is sensitive to False Negative probability, the classification threshold can be 0.2 to 0.3</em>. Hence, even the low-confidence ‘Y’ will be considered &#39;Y&#39;.</p><p>There are variations of this approach, such as <em>Area Under PR</em>, which emphasizes the sensitivity of the rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*GYgIKPUSfDoqU0lRRCWFqA.png" /><figcaption>fig 9: ROC AUC score for the given sample</figcaption></figure><p><strong><em>Baring the effect:</em></strong></p><p>We embarked on the journey with a focus on <em>accuracy</em> in evaluation. Given the use case, it’s obvious to employ the <em>F1 Score, ROC AUC or PR AUC</em> to yield a better outcome for the business.</p><p>Looking at the evolution of the evaluator given the business case:</p><pre># Earlier version of Evaluator used<br>MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;,<br>                                  labelCol=&quot;actual&quot;,<br>                                  metricName=&quot;accuracy&quot;)</pre><pre># Modified Evaluators based on the current business case<br>MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;,<br>                                  labelCol=&quot;actual&quot;,<br>                                  metricName=&quot;fMeasureByLabel&quot;)<br>BinaryClassificationEvaluator(rawPredictionCol=&quot;prediction&quot;,<br>                              labelCol=&quot;actual&quot;,<br>                              metricName=&quot;areaUnderPR&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*FeWjLV6eQDNz2ad7-5gyIA.png" /><figcaption>fig 9: Sample observations post retraining the model with new evaluators</figcaption></figure><ol><li>Accuracy: 0.7 (Reduced)</li><li>Precision: 0.4 (Reduced)</li><li>Recall: 1 (Improved)</li><li>F1 Score: 0.571 (Improved)</li><li>ROC AUC Score: 0.8125 (Improved)</li></ol><p>The optimized observations shows less <em>Accuracy</em>, but in the current business context, this model is evidently more effective in terms of unlocking value as the use case is more sensitive to a specific kind of error. This intelligence-baked decision-making will be able to capture the majority of the <em>True Anomalies</em> in the claims at the cost of surfacing a few valid claims for review.</p><p><strong><em>Conclusion</em></strong></p><p>Initially, we used a more accurate model to support intelligence-based decision-making. By posing the question of how accurate the judgements or classifications are, the article lets readers see how misleading accuracy may be. We developed the core methods to convert the unique business requirements into assessments that yield the most possible value.</p><p>With this, we set the foundation. Depending on how we choose to use them, there are several methods to practice these strategies.Some of the pointers for further research,</p><ol><li>The techniques that we have seen today primarily address the error of being wrong in identifying the positives. The majority of libraries and framework families offer labels (1.0, 2.0, etc.) to have control over the error type.</li><li>We can assign weights to the observation categories for further granular control over the effect of error estimations.</li><li>We need to be mindful about where we employ these techniques. While this might be effective in serving intelligence, these choices can also be very impactful during the <em>hyperparameter</em> tuning process.</li><li>The decisions or classifications are driven by varied features. Hence, we need to apply the right Ml engineering and MlOps strategies, such as adequate Feature Engineering, Data Drift Handling, Ensembling etc for this models to continue to be effective.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_LtOGvtR0gZKUrh0" /><figcaption>Photo by <a href="https://unsplash.com/@garri?utm_source=medium&amp;utm_medium=referral">Vladislav Babienko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26cb2e8323bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do you solve the maze of feature weights?]]></title>
            <link>https://medium.com/@saptarshi7karmakar/how-do-you-solve-the-maze-of-feature-weights-5a1fc5093f4d?source=rss-3555410fc5b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a1fc5093f4d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Saptarshi Karmakar]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 18:15:45 GMT</pubDate>
            <atom:updated>2023-12-11T14:20:00.072Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>We all know that a machine learning model’s prediction or target variable is dependent on the one-to-many (majority of the cases) influencer variables, which in other terms are called features. Real-life models / algorithms prove to have differences in the importance or weight of the features that they rely on. These weights are generally applied as multiplicative factors to the features when fed to the model.</p><p>While tuning the hyper-parameters for a model plays an important role in its performance, the accuracy of the outcome greatly depends on how optimal the feature weights are. Well, features are discovered through a variety of experimentation and domain extractions, which is why we often find ourselves assigning weights based on domain knowledge. But human intuitions can (if not mostly) lead to suboptimal outcomes. Another option is manually trying our different weights. The sheer scale of possibilities might lead you to say, <em>‘I’m done searching for the needle(s) in a haystack’.</em></p><p>This article takes you through one of the systematic processes to find near-optimal weights for the involved features. In this journey, we’ll understand the core problems and how we get around applying mathematical concepts using some of the best-known libraries.</p><p><strong>Assumptions</strong></p><p>Since machine learning and optimisation paradigms will overlap, it helps to have some foundational knowledge on topics like functions, minima, scientific Python, value optimisation, and fundamental machine learning terminology.</p><p><strong>What are the problems, and why are they essential to be solved?</strong></p><p>Lets look at the simple steps (well, it can be deceiving)</p><figure><img alt="Fig1: Broadly, there are three steps to this iterative process" src="https://cdn-images-1.medium.com/max/904/1*bvcNH0bHSBTJ-PrNN4TfaA.png" /><figcaption>Fig. 1: Broadly, there are three steps to this iterative process</figcaption></figure><p>Let us now understand what’s so challenging about it</p><h4>Scale of the Problem:</h4><p>Intuition-based weight selection / assignment can almost always lead to unfathomable possibilities, even for a simple algorithm. When you are trying to address even a moderately complex real-life model, you’ll find yourself trying to manage the state of gradients and directions of change to understand the next possible weight selection. The time and space complexity of the process increases exponentially with the increase in the number of involved features.</p><h4>Local Minima Trap:</h4><p>You are searching for the minimum possible value of the lost function for the model with weighted features. Even if you find a minimum that can well be a local minima of a curve, there can be other local minima(s) that represent a lesser value of loss functions, which is a better accuracy of the model. Hence, you might find yourself trapped selecting a local minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*AYbSukjZNumXPkNJSNBjsg.png" /><figcaption>Fig. 2: We are searching for the x0 global minima.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*DctmcyJlcGwoQ92xCvL55Q.png" /><figcaption>Fig. 3: We may get trapped with x0 while there is one (or more) x1. x0 is a local minima.</figcaption></figure><p>The more we drill down in the finding process, we can understand that feasibility also relies on the factor of the convexity of the function in any dimension. For example, the search can take off to a non-convex line or a surface, which’ll essentially lead nowhere. We are really missing out on any exit criteria.</p><h4>Uncertain Outcome:</h4><p>The distribution of the loss function outcome varies from one model to another; hence, we can’t specifically have a well-defined starting point. The results are almost always inconclusive, which leads to the necessity of maximum possible iterations at resource cost.</p><h4>Impact on MLOps:</h4><p>ML engineering practices require any related process to be definitive, deterministic (as possible), resource-aware, and well defined. The nature of the problem statement and the aforementioned points clearly make it really difficult for us to fit into such an ecosystem.</p><p>From the hypothetical loss functions, we can intuitively observe the discussed points. (Fig 4.)</p><p><em>Single Feature weight : f: (x**2)**2 + (x — 20)**2</em></p><p><em>Two Features weight(s) : f: (x**2 + y — 2)**2 + (x + y**2 -20)**2</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*hZ9bEdLB0xK8IXtY6MrfGg.png" /><figcaption>Fig. 4: We realise the challenges with one-to-multiple features.</figcaption></figure><p><strong>How can you have a pragmatic approach?</strong></p><p>Neural network-based algorithms are a natural fit for these kinds of optimisation problems, but that’s really an expensive process. What we’ll explore today is a comparatively inexpensive way to use suitable approaches and libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*pw8b4It1QwEQ9spVvDI3xQ.png" /><figcaption>Fig. 5: Simple mental mapping for the approach</figcaption></figure><h4>Random Weight Assignment:</h4><p>Assign a random starting point for the weights. We can define it from a random distribution.</p><h4>Local Optimiser:</h4><p>The responsibility of the local optimizer is to search within a local space and return the weights and gradients for the minimum loss function value. You can consider this step to find a local minima. Considering the problem statements, you simply need to assign</p><ul><li><em>The maximum number of iterations for a local search.</em></li><li><em>The exit criteria, if not a minimum, are found.</em></li><li><em>Acceptable range of weights.</em></li><li><em>Search algorithm. There are variety of algorithms like Nelder-Mead, Newton-CG etc.</em></li></ul><p>An excellent Python representation of such a local optimizer is <em>scipy.optimize.minimize (</em><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html"><em>documentation</em></a><em>)</em>. Which allows you to pass a variety of methods and other parameters in addition to what we have discussed above (Documentation Reference). SLSQP, or sequential least squares programming, is one of the most widely used methods because it is gradient-aware and resource-optimized.</p><h4>Global Optimiser:</h4><p>You need to assign a driver process to oversee and align the local optimization processes. Global Optimizer does just that. It ensures the state-managed next set of weights is passed to be locally optimized and makes the decision based on the feedback from the local optimizer. Apart from the properties for local optimizer, it also needs the parameters,</p><ul><li><em>Number of maximum iterations for the global optimizer.</em></li><li><em>Step size is used to estimate the gradient shift.</em></li></ul><p>A very prominent approach to such global optimization comes from the concept of ‘<em>the natural process of energy minimization of clusters of atom’</em>. The concept is called <strong>Basinhopping</strong> where each basin represents the local search and the hopping to another basin is based on external definitions and local optimization feedback.(<a href="https://en.wikipedia.org/wiki/Basin-hopping">Reference</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*YH99zrJs-Z_LaBD6-CCuvA.png" /><figcaption>Fig. 6: An intuitive view of basinhopping approach</figcaption></figure><p>Scientific Python has an implementation for some of the <strong>Basinhopping</strong> concepts, which is <em>scipy.optimize.basinhopping</em> (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html">Documentation</a>).</p><h4>Fit for MLOps:</h4><p>Now, with a possible set of best weights, you can run the model on test data. Drawing our focus back to the problem that we had discussed earlier in the chapter, you have now figured a way to have a process which easily fits the right parameters of MLOps with</p><ul><li><em>Completely automated process to come up with the best possible weights.</em></li><li><em>Finite iterations with predefined exit criteria in case of a failed search.</em></li><li><em>Search process to cross the barrier of the local minima trap.</em></li><li><em>Logical search mechanism.</em></li><li><em>Resource-aware execution process.</em></li><li><em>Almost deterministic and definitive process to generate close to truly optimum weights.</em></li></ul><p><strong>Applying the Concept</strong></p><p>Let’s take one of the sample functions that you have analysed before.</p><p><em>f: C + (x**2 + y — 2)**3 + (x + y**2 -20)**3</em></p><p>In the interest of simplicity, let us assume this function represents two feature’s (X and Y) weight influence on the outcome of model application and loss function. Based on this assumption, the minimum possible value (given the constraints) will prove to be the best model performance based on the weights assigned. If we are to operate with a model, the passed function should feed the model and loss function together into the optimizer(s).</p><p>Post-application of <strong>Basinhopping</strong> and <strong>Minimize</strong> concepts with <em>SLSQP</em>, we can observe that the <strong><em>l</em></strong><em>ocal minima and global minima are different, and the weight(s) for global minima leads to a lesser error of </em><strong><em>~61.24</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWpRaweC9vQB-5aIpW05yQ.png" /><figcaption>Fig. 7: Shape of the loss function: <em>C + (x**2 + y — 2)**3 + (x + y**2 -20)**3</em></figcaption></figure><pre>from scipy.optimize import minimize<br>from scipy.optimize import basinhopping<br><br># Local Optimizer<br><br>fun = lambda x: random.uniform(0, 1) + (x[0]**2 + x[1] -2)**3 + (x[0] + x[1]**2 -20)**3<br><br># Acceptable Constraint and conditions<br>cons = ({&#39;type&#39;: &#39;eq&#39;, &#39;fun&#39;: lambda x:  x[0]*4 + x[1]/5})<br>bnds = ((-0.05, 0.05), (-0.05, 0.05))<br><br># Initial Weights<br>x0 = (random.uniform(0, 1), random.uniform(0, 1))<br><br>res = minimize(fun, x0, method=&#39;SLSQP&#39;, bounds=bnds,<br>               constraints=cons, options={&#39;maxiter&#39;: 100, &#39;disp&#39; : True})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bwuABqXxaHiJY5h50JUIQ.png" /><figcaption>Fig. 8: Local Optimizer output</figcaption></figure><pre># Global Optimizer<br># Parameters for local optimiser<br>minimizer_kwargs = {<br>                    &#39;method&#39;:&#39;SLSQP&#39;, <br>                    &#39;bounds&#39;:bnds,<br>                    &#39;constraints&#39;:cons, <br>                    &#39;options&#39;:{&#39;maxiter&#39;: 100, &#39;disp&#39; : True}<br>                   }<br><br># Global optimiser parameters<br>global_max_itr = 200<br>stepsize=0.005<br><br>global_res = basinhopping(fun, x0, minimizer_kwargs=minimizer_kwargs,<br>                   niter=global_max_itr, )<br><br>print(&quot;global minimum: x = [%.4f, %.4f], f(x) = %.4f&quot; % (global_res.x[0],<br>                                                          global_res.x[1],<br>                                                          global_res.fun))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPji36lnhE4PFQGauUgZvw.png" /><figcaption>Fig. 9: Global Optimizer output (snapshot from the final iteration)</figcaption></figure><p><strong>Conclusion</strong></p><p>We have witnessed the significance—and, more crucially, the inevitable challenges—of the feature weight optimisation process for machine learning algorithms. We discussed how it makes ML engineering methods for real-world models more difficult. Obviously, we didn’t give up! We came up with a mathematically sound and computationally less costly method to manage it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a1fc5093f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series — Stationary and non-Auto-Correlation: Assumption —Realization— Materialisation]]></title>
            <link>https://medium.com/@saptarshi7karmakar/time-series-stationary-and-non-auto-correlation-assumption-realization-materialisation-394f23de0b40?source=rss-3555410fc5b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/394f23de0b40</guid>
            <category><![CDATA[time-series-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Saptarshi Karmakar]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 15:19:09 GMT</pubDate>
            <atom:updated>2023-11-28T04:23:40.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Series — Stationary and non-Auto-Correlation: Assumption —Realization— Materialisation</h3><p><strong>Introduction<em>:</em></strong></p><p>The Estimation and Forecasting space of Time Series Data is heavily influenced by how assumptions are made about the data. This article discusses the fundamental ideas of the Stationary &amp; Autocorrelation properties of time series data, emphasising the goal, methodology, and significance of estimation. We will also discuss various statistical methods that are considered highly useful for identifying and/or deriving the basis for Stationary &amp; Non-Auto Correlated Time Series, such as <em>“Auto Correlation Function” and “Augmented Dickey Fuller.”</em></p><p><strong>What(s) &amp; Why(s) of Stationary Property:</strong></p><p>Time series data fundamentally is the observation of facts at a time interval and its representation as a function of time. Temperature over time and the end-of day price of a stock captured over a few months or years are typical examples of time series data.</p><figure><img alt="Figure 1: Sample Non-Stationary Timeseries data of 1000 timesteps. A trend at longer period of time, with sudden directional deviations, seasonality are easy intuitive observations. Example: The statistical property: Mean (Rolling-100) is changing with time as well." src="https://cdn-images-1.medium.com/max/904/1*Lnj8ZP_o-u5vvVFUNZjQXA.png" /><figcaption>Figure 1: Sample Non-Stationary Timeseries data of 1000 timesteps. A trend at longer period of time, with sudden directional deviations, seasonality are easy intuitive observations. Example: The statistical property: Mean (Rolling-100) is changing with time as well.</figcaption></figure><p>The presence of trends or seasonal patterns is natural for a time series, but any possibility to exclude these factors positively influences the reliability of the forecast estimation. The stationary property of time series data suggests just that. In simple mathematical terms, a stationary series has approximately constant statistical properties over time steps.</p><p>For example, factors like <em>Mean, Variance, correlation</em> etc. don’t change as function of time; hence, they are independent of time steps.</p><p>Many of the Time Series Forecasting and Estimation Models assume that the time series is stationary. Realizing the correlation among the consecutive observations helps model or process discovery. Hence as part of the modelling process, it’s important to look at a few fundamental approaches to test the series for stationary properties and autocorrelation. If need be, apply transformation to achieve it to a certain degree.</p><p>Conceptually, these techniques are to systematically figure out if the time series (in its original or derived form) is stationary and apply certain transformations to pragmatically remove the effects of long-term trend, sudden shifts, time step correlations, etc.</p><p><em>1. Test for Stationary (Augmented Dickey Fuller Method)</em></p><p><em>2. If not, apply Transformation (Differencing). Repeat 1–2.</em></p><p><em>3. Test for Time Step based Correlation (Auto Correlation Function). Repeat 2–3</em></p><p><em>4. Result: A transformed series, which is possibly a Stationary one, with auto-acorrelation measures suggestive of possible model parameters.</em></p><p><strong><em>How to navigate through the steps: </em></strong>Zooming into the process</p><p>Test for Stationary through ADF: Augmented Dicky Fuller</p><p>This statistical test measure works with the hypothesis ‘A significant unit root exists in the series’ which makes it non-stationary. Rejecting the null hypothesis by unit root significance between -.999 and +.999 (Unit Circle -1,1) will prove that the series is stationary. For a simple equation of linear representation (below), alpha(t) is the root as a multiplicative factor can represent the possibility of sudden change in direction over immediate time steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*1I1pMXWMw0ZIK-_EbPNhdw.png" /><figcaption>Equation 1: simple linear equation Alpha outside of the unit circle identifies the series as non-stationary.</figcaption></figure><p>ADF Test returns ADF Statistic and p-value. To reject the null hypothesis, the ADF statistic needs to have a large negative value, and the p-value should be less than 0.05.</p><p><strong>Test for Time Step-Based Correlation (Auto Correlation Function):</strong></p><p>Correlation measures the extent of a linear relationship between two variables. Autocorrelation therefore measures the linear relationship between the lagged values of a time series. Thus, the ACF reveals how the correlation between any two values changes as the lag increases. Here, the lag is simply the number of timesteps separating two values.</p><p>In the presence of a trend, a plot of the ACF will show that the coefficients are high for short lags, and they will decrease linearly as the lag increases. If the data is seasonal, the ACF plot will also display cyclical patterns. Hence, if the coefficients are gradually converging to a stable long-term stable state in terms of confidence interval, we can safely assume that the time-step correlations are manageable and non-significant. (Figure 2)</p><p><strong>Apply Transformation: Differencing</strong></p><p>This is a process of stabilising the mean and seasonality of the series. The idea is, rather than looking at the point in time observations, measuring the observation differences between the time steps. This is a very effective way of estimating the movement over time steps, with the flexibility to slowly increase the order of differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*eBjmR0KWNnlFZ1TnFv1WWQ.png" /><figcaption>Equation 2: Simple Mathematical representation of time lag based differencing.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*Yi61Og88kB7nnk_gtr1s3A.png" /><figcaption>Equation 3 : Visual Presentation of Differencing Process</figcaption></figure><p><strong>Putting together what we have seen so far, to Action:</strong></p><p>To see the effect, let us refer to the same time series (Figure 1) to apply the ADF and ACF to derive our intuition of the series being non-stationary and autocorrelated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*De00aAj4HY6kDBSs-LGPlQ.png" /><figcaption>Figure 2: Estimations on the actual series to establish Non-Stationary</figcaption></figure><p><strong><em>Takeaway from the Identification Phase:</em></strong></p><p><strong>ADF Estimates:</strong> The null hypothesis stands as the adf-statistic is <strong>NOT</strong> a large negative value and the <strong>p-value is NOT &lt;0.05</strong>.</p><p><strong>ACF Estimates:</strong> Correlation Coefficients remain significant with considerable lag.</p><p>According to the established process, if we apply the 2nd-order differencing transformation and run the same set of tests, the results will appear to achieve a <strong>Derived Stationary Time Series</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*5wnXsWhqVspWoNUBtBw7Cw.png" /><figcaption>Figure 3: Post-transformation of 2nd-order differencing</figcaption></figure><p><strong><em>Takeaway from the Transformation Phase:</em></strong></p><p><strong>ADF Estimates</strong>: The null hypothesis is <strong>REJECTED</strong> as the adf-statistic has a large negative value and the <strong>p-value is &lt;0.05</strong>.</p><p><strong>ACF Estimates:</strong> Correlation Coefficients <strong>become non-significant </strong>under the confidence interval (Light Blue Shaded Area) after 1–2 lags (Figure 3).</p><p><strong>Final stationary time series:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Tfxd_GID_MTwveeKLmA64Q.png" /><figcaption>Figure 4: Derived Stationary time series from Figure 1.</figcaption></figure><p><strong>Conclusion:</strong></p><p>We have now understood the process of identifying and re-modelling a time series to be a stationary series if possible. Not only does this process significantly influence the discovery of adequate model paradigm, this it also builds reliable foundation for Forecasting models like Random Walk, MA(q), AR(p) and ARMA(p,q) etc.</p><p><strong>A few points to remember:</strong></p><p><em>1. Differencing, as a transformation, essentially leads to a loss of context from the data in order to find a space for relative stability.</em></p><p><em>2. Process with Transformations are naturally paired with a reverse transformation at the end to scale the estimations or forecasts back to the original context of the series.</em></p><p><em>3. Time series might still continue to have trend and seasonality effects post-transformations. In such cases, more complex time-series models might be a better fit. e.g. ARIMA, SARIMAX, etc.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394f23de0b40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>