<?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 SUJIT on Medium]]></title>
        <description><![CDATA[Stories by SUJIT on Medium]]></description>
        <link>https://medium.com/@7799sujit?source=rss-9a1fde120311------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6H5y9PZPP31JqErru7RyEw.png</url>
            <title>Stories by SUJIT on Medium</title>
            <link>https://medium.com/@7799sujit?source=rss-9a1fde120311------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:05:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@7799sujit/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[Reinforcement Learning(Part 5: Function Approximation)]]></title>
            <link>https://7799sujit.medium.com/reinforcement-learning-part-5-function-approximation-0a6774163433?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a6774163433</guid>
            <category><![CDATA[function-approximation]]></category>
            <category><![CDATA[deepreinforcementlearning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 13:31:07 GMT</pubDate>
            <atom:updated>2026-04-25T19:00:17.479Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“In a 3×3 maze, we can store a value for every cell. In a video game with millions of pixel combinations, we need something smarter.”</em></p><h4>The Problem with Tables</h4><p>In tabular RL, we store one value per state or state-action pair. This breaks for real problems:</p><pre><strong>Problem</strong>              <strong>State Space Size</strong>           <strong>Table Feasible?</strong><br>3×3 maze             9 states                   Easy<br>Chess               ~10⁴⁷ states                Impossible<br>Go                  ~10¹⁷⁰ states               Impossible</pre><h4><strong>Two fatal problems:</strong></h4><ol><li><strong>Memory:</strong> Can’t store 1⁰⁴⁷ values.</li><li><strong>Generalisation:</strong> In tabular methods, visiting state A teaches you NOTHING about similar state B. If a robot visits room 1 and learns it’s safe, it knows nothing about nearly-identical room 2.</li></ol><h3>So now we ask:</h3><blockquote><em>“Can we learn a </em>pattern<em> instead of memorising everything?”</em></blockquote><h4>Now we learn: Function Approximation</h4><p>This is where things start becoming <em>real AI</em>.</p><h3>Function Approximation</h3><p>Until now, we stored values in a <strong>table</strong>: One state → one value</p><p>But what if:</p><ul><li>States are too many?</li><li>Or even infinite?</li></ul><h4>The Core Idea</h4><p>Instead of storing values, we learn:</p><p>V(s) ≈ f(s,w)</p><p>What does this mean?</p><ul><li><strong>s</strong> → state</li><li><strong>w</strong> → parameters (weights we learn)</li><li><strong>f</strong> → a function (like a model)</li></ul><p>Instead of remembering everything… We learn a <strong>rule that predicts values</strong></p><p>You can think of predicting house prices:</p><ul><li>You don’t memorise the price of every house</li><li>You learn a formula:<br> Price = f(size, location, rooms)</li></ul><p>That’s <strong>function approximation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5W30JXawIVdbKh0fmchzlA.jpeg" /></figure><h4>Feature Vectors: Describing States</h4><p>We don’t feed raw states — we describe them using <strong>features<br></strong>A feature vector = important characteristics of a state</p><h4>Maze Example</h4><p>Let’s define 2 features:</p><ul><li><strong>x₁(s)</strong> = distance to goal</li><li><strong>x₂(s)</strong> = number of nearby traps</li></ul><pre><strong>State</strong>                <strong>x₁ (goal dist)</strong>     <strong>x₂ (traps nearby)      Feature vector</strong><br>A1                   2                  0                      [2, 0]<br>A2                   1                  0                      [1, 0]<br>B1                   3                  1                      [3, 1]<br>C1                   4                  1                      [4, 1]<br>C3(never visited!)   3                  1                      [3, 1]</pre><p>In this, if you look,<strong> “</strong>C3” has the same features as “B1”, so they’ll get similar values even if “C3” was never visited! That’s a generalisation<strong>.</strong></p><p>It&#39;s like judging a student:</p><ul><li>Two students with the same marks + skills<br> You expect similar performance</li></ul><p>Even if you’ve never met one of them.</p><h3>Types of Function Approximation</h3><ol><li>Linear<br>Simple weighted sum</li><li>Non-linear<br>Neural networks (deep learning)</li></ol><h3>1: Linear Function Approximation</h3><p>We compute values like:</p><p><strong>Value = weighted sum of features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cKcq2LtUSv01PdwAGXyGg.jpeg" /></figure><p><strong>Let&#39;s understand with an example:</strong></p><p>Consider weight as : w = [-1.5, -3.0]</p><p>Now the value function will be =&gt;</p><pre>v^(A1) = (−1.5)(2)+(−3.0)(0) = −3.0<br>v^(B1) = (−1.5)(3)+(−3.0)(1) = −4.5−3.0 = −7.5<br>v^(A2) = (−1.5)(1)+(−3.0)(0) = −1.5</pre><p><strong>What the weights mean:</strong></p><ul><li>w₁ = -1.5 (negative): being FAR from goal is bad</li><li>w₂ = -3.0 (negative): having traps nearby is VERY bad</li></ul><p>In this approximation, we are learning the right value of “W” which will minimise our loss.</p><h4>How Do We Measure Error?</h4><p>We want our approximation close to the true value. The loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7tdGK2S2a50W-6z3sDbXw.jpeg" /></figure><p><strong>Every Term Explained</strong></p><ul><li>Σ_{s∈S} : Sum over all states</li><li>μ(s) : State visitation frequency</li><li>v_π(s) : True value (unknown!)</li><li>v̂(s, w) : Our approximation</li><li>[…]² : Squared error</li></ul><blockquote>Note μ(s) : Not all states are equally important<br>Frequently visited states → more important<br>Rare states → less important</blockquote><p>You can look at this like exams:</p><ul><li>Topics asked often → you focus more than I learn that without any mistake</li><li>Rare topics → less priority</li></ul><p><strong>Let&#39;s look at a numeric Example</strong></p><p>With w = [-2.0, +1.5], computing error for 4 states:</p><pre>State    v_π(s) (true)   v̂(s, w)   Error   Error²     μ(s)    Weighted<br>A1       +7.0            +5.0      2.0     4.0        0.30    1.20<br>A2       +9.0            +8.0      1.0     1.0        0.25    0.25<br>B1       +3.0            +1.0      2.0     4.0        0.25    1.00<br>C1       -2.0            -4.0      2.0     4.0        0.20    0.80</pre><p>Value Error =1.20+0.25+1.00+0.80=3.25</p><blockquote><em>Our goal: adjust w to make this number as small as possible.</em></blockquote><p>Function approximation replaces lookup tables with a smart formula that learns patterns and generalises to new situations.</p><blockquote>Now you may think <strong>function approximation in RL</strong> looks a lot like <strong>supervised learning</strong>… but the <em>source of learning</em> is completely different.</blockquote><p>Now, look at why RL and supervised learning are different. In Supervised Learning, the target is known, <strong>i.e. y (true label), but </strong>in Reinforcement Learning, the target is NOT directly known</p><p>We use:</p><ul><li>Monte Carlo → actual return</li><li>TD → estimated target</li></ul><p>In short, in RL:<br> <strong>You are learning from your own predictions, and t</strong>hat’s very different from supervised learning. In RL, “y” is not given… it is learned and keeps changing</p><p>Think like this: Learning to Play a Game</p><ul><li>No one tells you the “correct move” (no y)</li><li>You try something</li><li>You see the result (win/lose)</li><li>You update your belief</li></ul><p>Over time, you <em>construct your own y</em></p><h4>Now let&#39;s look at how we are learning weight “w” and updating the weight based on loss.</h4><p>Earlier: We stored values in a table</p><p>Now: We <strong>learn a function</strong></p><p>v^(s,w)</p><p>And the real goal is:<br><strong>Learn the best weights “w”</strong></p><p>We already know about Gradient Descent Deep Learning: <a href="https://www.analyticsvidhya.com/blog/2021/10/a-comprehensive-guide-on-deep-learning-optimizers/">You can learn here</a></p><blockquote>w_t+1 = w_t - alpha*(d[v(s, w)]/dL)</blockquote><blockquote>where let&#39;s say d[v(s, w)]/dL = ∇_w ​J(w​) <br>and ∇_w ​J(w​) is our loss</blockquote><h4>Deriving the Weight Update</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sY30rmAcdXjLaoEHK4aXVQ.jpeg" /></figure><h4>For Linear v̂</h4><p>When v̂(s, w) = w·x(s), the gradient is simply the feature vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtDzG2cJstXESADoS__huQ.jpeg" /></figure><p>Each weight w_i gets adjusted proportionally to its corresponding feature x_i(s). Features that are large for this state get bigger corrections.</p><h4>Now the practical problem: We don’t know the true value v_π(s)</h4><p>The update requires v_π(s) — the true value. We don’t have it. So we use approximations:</p><p><strong>1st: Monte Carlo Target:</strong></p><blockquote>Target = Gt​</blockquote><p>So the equation looks like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Xopl82b70e0AfjQ_gwjiA.jpeg" /></figure><p><strong>Why G_t works:</strong> v_π(s) = E[G_t], so G_t is a noisy but unbiased sample. Like estimating average height by measuring one random person, noisy but correct on average.</p><p><strong>Properties:</strong> True gradient (no approximation in the derivative), unbiased, but high variance.</p><p><strong>2nd: Temporal Difference</strong></p><blockquote>Target = R_{t+1} + γv̂(S_{t+1})</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mukn3vc7Pg6DpLF55fQ0lg.jpeg" /></figure><p>The TD target depends on w (through v̂(S_{t+1})). The full gradient would differentiate through the target too:</p><p>Full gradient: −2δt​(∇v^(St​)−γ∇v^(St+1​))</p><p>But we <strong>ignore</strong> the second term and only differentiate v̂(S_t):</p><p>Semi-gradient: −2δt⋅∇v^(St)</p><p>Why? Including the full gradient causes instability. The semi-gradient works well in practice despite not being a true gradient.</p><p><strong>Properties:</strong> Not a true gradient (semi-gradient), biased, but low variance and learns every step.</p><h4>Complete Numeric Example: TD with Linear Approximation</h4><pre>Setup<br>w = [-1.0, -2.0], α = 0.1, γ = 0.9<br>Features: x₁ = goal distance, x₂ = trap distance<br>Agent at B1 (x = [3, 1]), goes Up, R = -1, lands at A1 (x = [2, 2]).<br><br>Compute Current Estimates<br>v^(B1)=(−1.0)(3)+(−2.0)(1)=−3.0−2.0=−5.0<br>v^(A1)=(−1.0)(2)+(−2.0)(2)=−2.0−4.0=−6.0<br><br>TD Target<br>target=R+γv^(A1)=−1+0.9(−6.0)=−1−5.4=−6.4<br><br>TD Error<br>δ=−6.4−(−5.0)=−1.4<br><br>&quot;B1&#39;s value should be -6.4 but we estimated -5.0. We were too optimistic by 1.4.&quot;<br><br>Update Weights<br><br>Using features of B1 = [3, 1]:<br>w1←−1.0+0.1×(−1.4)×3=−1.0−0.42=−1.42<br>w2←−2.0+0.1×(−1.4)×1=−2.0−0.14=−2.14<br><br>New w = [-1.42, -2.14]<br><br>Notice: w₁ changed MORE (-0.42) than w₂ (-0.14) because x₁ = 3 was larger than x₂ = 1. Features with larger values get bigger corrections — the gradient automatically assigns blame.</pre><h4>Challenges of Function Approximation</h4><p><strong>Challenge 1: Coupled Updates</strong></p><h3>Challenge 1: Coupled Updates (Everything is Connected)</h3><p>In <strong>tabular RL</strong>:</p><ul><li>Updating one state → affects only that state</li></ul><p>But in <strong>function approximation</strong>:</p><ul><li>All states share the same weights</li><li>Updating one state → affects many others</li></ul><p><strong>Consider this example<br></strong>You updated weights to fix <strong>B1</strong>:</p><p>Before: v^(A1) = −6.0<br>After updating weights: v^(A1) = −7.12</p><p>You fixed one thing…<br> But accidentally broke another</p><p><strong>You can think of a company policy change:</strong></p><ul><li>You improve sales incentives</li><li>Sales improve</li><li>But employee stress increases</li></ul><p>One change affects many outcomes</p><p><strong>Challenge 2: The Deadly Triad</strong></p><p>Combining these can cause <strong>divergence</strong> (values blow up to infinity):</p><ol><li><strong>Function approximation</strong> (can’t represent all values perfectly)</li><li><strong>Bootstrapping</strong> (TD learning — using estimates to update estimates)</li></ol><p>You are learning from your own guesses… and those guesses affect everything.<strong> </strong>Each is useful alone, but all together can be unstable.</p><p><strong>You can imagine:</strong></p><ul><li>You write notes from memory (bootstrapping)</li><li>You use one notebook for all subjects (function approximation)</li></ul><p>Now:</p><ul><li>One mistake in notes</li><li>Affects all subjects</li><li>You revise from the same notes again</li></ul><p>Mistakes keep growing</p><h3>2: Nonlinear Function Approximation</h3><p><strong>Neural Networks as Value Functions</strong></p><p>Earlier, we used something like:</p><ul><li>A straight line (linear model)</li></ul><p>But real-world problems are messy.</p><p>So, we replace the value function with:</p><p>A neural network</p><p>V^(s) = f(s,w)</p><p>But now:</p><ul><li>f is not a simple equation</li><li>It’s a <strong>multi-layer neural network</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*LDFZulukokRt27XhiRSufg.jpeg" /></figure><p><strong>Advantage:</strong> Neural networks can learn their own features from raw input (pixels, text).</p><p><strong>Disadvantage:</strong> No convergence guarantees. More hyperparameters. Harder to train.</p><h4>Let’s tie it all together:</h4><ol><li><strong>Monte Carlo</strong> → learn at the end</li><li><strong>TD Learning</strong> → learn step-by-step</li><li><strong>Function Approximation</strong> → replace tables</li><li><strong>Neural Networks</strong> → handle complex environments</li></ol><h3>Final intuition</h3><p><em>We are no longer storing values.<br>We are training a system that </em>understands states<em>.</em></p><h4>Now… what comes next?</h4><p>Till now, we’ve focused on:</p><p><strong>Value Functions: </strong><em>“How good is this state?”</em></p><h4>Next step:</h4><blockquote><strong><em>Policy Control using Function Approximation</em></strong></blockquote><p>Now we’ll answer a bigger question:</p><p>Not just:</p><p><em>“How good is this state?”</em></p><p>But:</p><p><em>“What action should I take?”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a6774163433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning(Part 4: Temporal Difference Control)]]></title>
            <link>https://7799sujit.medium.com/reinforcement-learning-part-4-temporal-difference-control-8a508381a501?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a508381a501</guid>
            <category><![CDATA[temporal-difference]]></category>
            <category><![CDATA[temporal-diff-control]]></category>
            <category><![CDATA[td-learning]]></category>
            <category><![CDATA[temporal-difference-rl]]></category>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 03:59:43 GMT</pubDate>
            <atom:updated>2026-04-25T16:56:36.107Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Why wait until the end to learn? I can improve my understanding after every single action.”</em></p><blockquote>Part 3 : <a href="https://7799sujit.medium.com/reinforcement-learning-part-3-monte-carlo-methods-704952e84bb9">Blog</a></blockquote><h4>Let’s quickly rewind…</h4><p>So far, you’ve learned two important ways of learning:<br><strong>1. Monte Carlo (MC)</strong></p><p>You:</p><ul><li>Play the <strong>entire episode</strong></li><li>Wait till the end</li><li>Then say: <em>“Okay… now I know how good that path was.”</em></li></ul><p>Like waiting for <strong>final exam results</strong> to judge your preparation.</p><p><strong>2: Dynamic Programming (MDP)</strong></p><p>You:</p><ul><li>Use full knowledge of the environment</li><li>Apply the <strong>Bellman equation</strong></li></ul><p>Like having the <strong>answer key already</strong>.</p><h4>Now… what’s missing?</h4><p>Both approaches have a problem:</p><ul><li>MC → <em>Too slow (wait till the end)</em></li><li>MDP → <em>Needs full environment knowledge</em></li></ul><h4>Now we learn something powerful: Temporal Difference (TD)</h4><p>This is where things get interesting.</p><p><strong>TD Learning combines both worlds:</strong></p><ul><li>Learns from experience (like MC)</li><li>Updates using estimates (like MDP)</li></ul><pre>Monte Carlo:    S₀ → S₁ → S₂ → ... → S_T (wait for end, then update)<br>TD Learning:    S₀ → S₁ (update NOW!) → S₂ (update NOW!) → ...</pre><p>Instead of:</p><blockquote><em>“I’ll learn at the end…”</em></blockquote><p>Now you say:</p><blockquote><em>“I’ll learn after EVERY step.”</em></blockquote><p><strong>Now that you understand <em>why TD exists</em>…</strong></p><p>Let’s learn the simplest version</p><h4><strong>The Simplest TD Method</strong></h4><p><strong>The Update Rule</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFuF0lRk2S6VkKyqQRsSCQ.jpeg" /></figure><blockquote>Update my belief about state “s” by moving it toward (reward now + estimated future value)</blockquote><p><strong>Break it piece by piece</strong></p><ol><li>V(s) =&gt; Current belief about state s<br>“How good I think this state is”</li><li>r =&gt; Immediate reward<br> “What I got right now”</li><li>γV(s′) =&gt; Estimated future value<br> “How good the next state looks”</li><li>r+γV(s′) =&gt; Target (new estimate)<br>“What I <em>now think</em> this state should be worth”</li><li>(r+γV(s′)−V(s)) =&gt; <strong>TD Error</strong><br> “How wrong was my previous guess?”</li><li>α =&gt; Learning rate<br> “How fast I update my belief”</li></ol><p><strong>Compare with Monte Carlo:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBQQrO7mDBlJ2DYoKu7yJQ.jpeg" /></figure><pre>                 MC target                       TD target<br>Formula          G_t = R₁ + γR₂ + γ²R₃ + ...     R_{t+1} + γV(S_{t+1})<br>Uses             ALL real rewards until end      ONE real reward + estimate<br>When available   End of episode                  Immediately after one step<br>Bias             Unbiased                        Biased (uses estimated V)<br>Variance         High (G_t varies wildly)        Low (one-step target)</pre><p><strong>Key difference from Monte Carlo</strong></p><p>Monte Carlo:</p><ul><li>Wait till the end</li><li>Use actual return Gt</li></ul><p><strong>TD Learning:</strong></p><ul><li>Update immediately</li><li>Use estimate V(s′)</li></ul><p><strong>Super intuitive view</strong></p><p>New value = Old value + Correction<br>Where correction is: “Immediate reward + guessed future − old belief”</p><p><strong>Think like this: Learning a Course</strong></p><ul><li><strong>Monte Carlo</strong><br> → Wait until the final exam → then decide how good you are</li><li><strong>TD Learning</strong><br> → After every lecture:<br> * “Did I understand this?”<br> * Adjust immediately</li></ul><p>TD = <strong>continuous self-correction</strong></p><h4><strong>The TD Error</strong></h4><p>This part drives everything:</p><p>Think of it as:</p><blockquote><em>“How wrong was my expectation?”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHB7cRWmlhu6NWW0wLo2Uw.jpeg" /></figure><p>Interpret it like this:</p><ul><li><strong>δ &gt; 0</strong> → “Things are better than expected” → increase value</li><li><strong>δ = 0</strong> → “Perfect prediction” → no change</li><li><strong>δ &lt; 0</strong> → “Worse than expected” → decrease value</li></ul><h4>Now, let’s make it real with a simple example</h4><p>We’ll go step by step just like the agent learns.</p><p><strong>Maze:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PA-aFbdnAdanpMdZT0k_g.jpeg" /></figure><p>All V(s) = 0, α = 0.1, γ = 0.9.</p><p><strong>Step 1: A1 → Right → A2, R = -1</strong></p><pre>δ = R + γV(A2)−V(A1) = −1+0.9(0)−0 = −1.0<br><br>V(A1) ← 0 + 0.1(−1.0) = −0.1</pre><p><strong>Learn immediately!</strong> No need to finish the episode.</p><p><strong>Step 2: A2 → Right → A3 (GOAL), R = +10</strong></p><pre>δ = 10 + 0.9(0)−0 = +10.0<br><br>V(A2) ← 0+0.1(10.0) = +1.0</pre><p><strong>Huge positive error.</strong> V(A2) jumps up. The goal’s value starts propagating.</p><p><strong>Step 3 (New episode): A1 → Right → A2, R = -1</strong></p><pre>δ = −1+0.9(1.0)−(−0.1) = −1+0.9+0.1 = 0.0<br>V(A1) ← −0.1+0.1(0.0) = −0.1</pre><p>Now V(A2) = 1.0 (learned from Step 2), so the TD target for A1 uses this improved estimate. <strong>Information flows backwards!</strong></p><p><strong>Step 4: A2 → Right → A3 (GOAL), R = +10</strong></p><pre>δ = 10+0−1.0 = +9.0<br><br>V(A2) ← 1.0+0.1(9.0) = 1.9</pre><p>V(A2) keeps growing toward its true value.</p><p><strong><em>Value Evolution</em></strong></p><pre>After step       V(A1)      V(A2)      V(B1)      V(C1)<br>Init             0          0          0          0<br>2                -0.1       1.0        0          0<br>4                -0.1       1.9        0          0<br>........<br>10               2.5        5.5        -0.5       0<br>........<br>50               5.8        8.2        2.5        -1.5<br>........<br>200              6.5        8.5        3.0        -1.0</pre><h4>Big Insight: How learning spreads</h4><p>Think of it like a chain reaction:</p><ol><li>Goal gives reward → A2 improves</li><li>A2 improves → A1 improves</li><li>A1 improves → B1 improves</li></ol><h4>Why Bootstrapping Works</h4><p>You might be thinking:</p><blockquote><em>“Wait… if my estimate V(St+1) is wrong…<br> won’t everything become wrong?”</em></blockquote><p>Short answer:<br> <strong>Yes, at the beginning. But it fixes itself.</strong></p><p>It self-corrects through a chain reaction:</p><h4>Let’s walk through it slowly (this is the key intuition)</h4><p>We have learned:</p><ul><li>TD uses <strong>estimates</strong></li><li>And updates happen <strong>immediately</strong></li></ul><p>Now, let’s see how wrong estimates become right over time.</p><pre><strong>Step 1: The truth enters the system</strong><br>Agent reaches GOAL, gets R = +10<br>→ V(A2) improves (contains real reward)<br><br><strong>Step 2: One step before the goal</strong><br>Agent visits A1, goes to A2<br>        → TD target uses improved V(A2)<br>        → V(A1) improves<br><br><strong>Step 3: One more step back</strong><br>Agent visits B1, goes to A1<br>        → TD target uses improved V(A1)<br>        → V(B1) improves<br><br>Goals value propagates backward, one step at a time.</pre><h4>Pause — see the pattern?</h4><p>We never directly updated B1 using a reward.</p><h4>This is Bootstrapping</h4><blockquote><em>Learning from your own improving estimates.</em></blockquote><p>The reward travelled backwards<strong> step-by-step</strong></p><p>Think of it like: Imagine people passing exam answers:</p><ul><li>First student sees the correct answer</li><li>Tells the next</li><li>Then the next…</li></ul><p>Eventually, everyone gets closer to the truth</p><h4>But yes, it is valid</h4><p>Early estimates can be wrong.</p><p>So why doesn’t everything collapse?</p><p>Because:</p><ul><li>Updates happen <strong>many times</strong></li><li>Each update uses <strong>slightly better information than before</strong></li></ul><h4>The Self-Correction Loop</h4><p>Think of it like: <em>Guess → Adjust → Better Guess → Adjust → Better Guess…</em></p><p>Eventually:<br> * Errors shrink<br> * Values stabilize</p><blockquote><em>TD learning is like continuously correcting your beliefs using slightly improved guesses each time.</em></blockquote><h4>Pros and cons of TD</h4><ul><li><strong>Pros:</strong> Fast, online, stable, practical</li><li><strong>Cons:</strong> Biased, depends on estimates, and slower correction</li></ul><h4>Now… what’s the next challenge?</h4><p>So far, we assumed:</p><p>We can store values in a <strong>table</strong></p><p>But think:</p><ul><li>What if states = millions?</li><li>Or continuous (like positions, images)?</li></ul><h4>That breaks our current approach</h4><p>We can’t store everything in a table anymore.</p><p>So next, we learn: <strong><em>Function Approximation</em></strong></p><p>Instead of a table:</p><ul><li>We use a <strong>function (like a model)</strong></li><li>That can <strong>generalise across states</strong></li></ul><h4>So basically, in that, instead of remembering:</h4><blockquote><em>“Every single road in the city”</em></blockquote><p>You learn:</p><blockquote><em>“How roads </em>generally behave<em>”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a508381a501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning(Part 3: Monte Carlo Methods)]]></title>
            <link>https://7799sujit.medium.com/reinforcement-learning-part-3-monte-carlo-methods-704952e84bb9?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/704952e84bb9</guid>
            <category><![CDATA[monte-carlo-control]]></category>
            <category><![CDATA[monte-carlo-rl]]></category>
            <category><![CDATA[monte-carlo-method]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 11:44:48 GMT</pubDate>
            <atom:updated>2026-04-25T16:37:55.744Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I don’t need a map of the world. I just need to try things, see what happens, and remember what worked.</em></p><p>Part 2: <a href="https://medium.com/@7799sujit/reinforcement-learning-part-2-markov-decision-processes-3cdf2c35bfa4">Blog Link</a></p><h4>What we have learned so far</h4><p>Till now, we have learned how to compute value functions using the <strong>Bellman equation</strong>.</p><p>But there was a problem…</p><p>We needed to know the environment completely<br>Specifically, we needed transition probabilities like:<br> <strong>P(s′ | s, a)</strong></p><p>And in real life?</p><p>We usually <em>don’t know this</em></p><h3>So what’s the alternative?</h3><p>Now we will learn something more practical…</p><h3>Monte Carlo Methods</h3><p>Instead of depending on equations and full knowledge, we take a very human approach:</p><blockquote><em>“Let me try things… see what happens… and remember what worked.”</em></blockquote><p>So basically, play complete episodes, observe the returns, and average them.</p><p>Now that you’ve seen the motivation, here’s the key intuition:</p><p>If I experience a state many times and average what actually happened… I will eventually learn its true value</p><p>Think of it like rating a restaurant:</p><ul><li>One visit → unreliable</li><li>Many visits → accurate rating</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pHauSgloHnncbE3696LHA.jpeg" /></figure><blockquote>Monte Carlo learns value by averaging real outcomes from complete experiences, instead of relying on known probabilities.</blockquote><p><strong>So Monte Carlo Works like this</strong></p><p>The Three Steps</p><pre>Step 1: PLAY    → <strong>Run a complete episode using policy π</strong><br>                  S₀, A₀, R₁, S₁, A₁, R₂, ..., S_T (terminal)</pre><pre>Like: <em>“Let me finish the whole journey first.”</em></pre><pre>Step 2: COMPUTE → <strong>Calculate return G_t for each state visited</strong><br>                  G_t = R_{t+1} + γR_{t+2} + γ²R_{t+3} + ...</pre><pre>Like: “From this point, how good did things turn out overall?”</pre><pre>Step 3: UPDATE  → <strong>Update value estimate toward the observed return</strong><br>                  V(s) ← V(s) + α(G_t - V(s))</pre><pre>Like: <em>“</em>correcting your belief:<br>Old belief = V(s)<br>Reality = G_t<br>Move slightly toward reality”</pre><blockquote>Equation : V(s) ← V(s) + α(G_t — V(s))</blockquote><p><strong>Break it piece by piece, the formula:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eG34sA4I_MtOT5-2wQkjzA.jpeg" /></figure><h4><strong>How to read this equation</strong></h4><blockquote>Update my current estimate Q by moving it a little toward the actual return Gt</blockquote><p><strong>Step-by-step Reading</strong></p><ul><li><strong>Q ← Q</strong><br> → Start with what I currently believe</li><li><strong>+ α × (…)</strong><br> → Adjust it a little (α controls how big the step is)</li><li><strong>(Gₜ − Q)</strong><br> → The mistake I made<br> <em>(actual − predicted)</em></li></ul><p>Suppose:</p><ul><li>You think a restaurant rating = <strong>5</strong></li><li>You go and experience = <strong>9</strong></li></ul><p>Now:</p><ul><li>Error = 9−5 = 4</li></ul><p>If α=0.1</p><ul><li>Update = 5+0.1×4 = 5.45 + 0.1 × 4 = 5.45+0.1×4 = 5.4</li></ul><p>You don’t jump to 9<br>You move slightly toward it</p><blockquote>Learn from your mistake by nudging your estimate toward what actually happened.</blockquote><h4>Now let’s see it in action</h4><p>Now that we understand the process, let’s walk through an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PA-aFbdnAdanpMdZT0k_g.jpeg" /></figure><p>Every normal step costs R = -1, γ = 0.9, α = 0.1. All V(s) are initialised to 0.</p><h4><strong>Episode 1: A1 → A2 → A3 (GOAL)</strong></h4><p><strong>Trajectory:</strong> A1 →(R=-1)→ A2 →(R=+10)→ A3</p><p><strong>Calculate returns (from the END, working backwards):</strong></p><pre>At A2 (last non-terminal state):<br><br>G1 = R2 = +10<br><br>At A1:<br><br>G0 = R1+γG1 = −1+0.9(10) = −1+9 = 8.0<br><br>Update values:<br><br>V(A2) ← 0 + 0.1(10−0) = 1.0<br>V(A1) ← 0 + 0.1(8.0−0) = 0.8</pre><p>After 1st episode :</p><pre><br>State  | V before |  G_t    |   V after<br>A1       0           8.0        0.8<br>A2       0           10.0       1.0</pre><p><strong>Episode 2: A1 → B1 → C1 → C2 (TRAP)</strong></p><p><strong>Trajectory:</strong> A1 →(R=-1)→ B1 →(R=-1)→ C1 →(R=-10)→ C2</p><p><strong>Calculate returns (backward):</strong></p><pre>At C1:<br><br>G2 = −10<br><br>At B1:<br><br>G1 = −1+0.9(−10) = −1−9 = −10.0<br><br>At A1:<br><br>G0 = −1+0.9(−10.0) = −1−9.0 = −10.0<br><br>Update values:<br>V(C1) ← 0+0.1(−10−0) = −1.0<br>V(B1) ← 0+0.1(−10.0−0) = −1.0<br>V(A1) ← 0.8+0.1(−10.0−0.8) = 0.8−1.08=−0.28</pre><p>After the 2nd episode :</p><pre>State | V before | G_t    | V after<br>  C1       0       -10.0     -1.0<br>  B1       0       -10.0     -1.0<br>  A1       0.8     -10.0     -0.28</pre><p><strong>Episode 3: A1 → A2 → A3 (GOAL)</strong></p><p><strong>Returns:</strong> G(A1) = 8.0, G(A2) = 10.0</p><pre>V(A1) ← −0.28+0.1(8.0−(−0.28)) = −0.28+0.828 = 0.548<br>V(A2) ← 1.0+0.1(10.0−1.0) = 1.0+0.9 = 1.9</pre><p>After 100th episode: <strong><em>Tracking Convergence</em></strong></p><pre>Episode   V(A1)   V(A2)   V(B1)   V(C1)    What happened<br>0 (init)  0       0       0       0        Know nothing<br>1         0.8     1.0     0       0        Found goal!<br>2         -0.28   1.0     -1.0    -1.0     Found trap!<br>3         0.55    1.9     -1.0    -1.0     Goal again, A1 recovers<br>10        3.2     5.5     0.5     -3.0     Getting better<br>100       6.5     8.5     3.0     -1.0     Near convergence</pre><h4>What’s happening overall?</h4><p>Now that you’ve seen multiple episodes:</p><p>The agent is <strong>balancing experiences</strong></p><ul><li>Good outcomes push values up</li><li>Bad outcomes push values down</li></ul><p>Over time → it stabilises</p><h4>Final Intuition</h4><p>“Try → Observe → Adjust → Repeat →…………→ stabilises”</p><blockquote><strong><em>Monte Carlo learns state values by averaging real outcomes from complete episodes.</em></strong></blockquote><h3>Let&#39;s look at some questions :</h3><p><strong>Question: So in the above calculation, where is averaging?</strong></p><h4>Where is the “average”?</h4><p>Good question.</p><p>We are not directly averaging<br>But every update moves toward new data</p><p>Over time, it becomes a <strong>weighted average of all experiences</strong></p><h4>Now, a new concept</h4><p>Now that we understand basic MC…</p><p>Let’s handle a tricky situation:</p><p><strong>What if the agent visits the same state TWICE in one episode?<br></strong>Example: A1 → B1 → A1 → A2 → A3 (the agent went in a circle)</p><p>State A1 appears at t=0 AND t=2. Which return do we use?</p><p><strong>First-Visit MC</strong></p><p>Only use the return from the <strong>FIRST</strong> time a state is visited in each episode.<br>For the episode above:</p><ul><li>A1 first visited at t=0: use G₀ = -1 + 0.9(-1) + 0.81(-1) + 0.729(10) = 4.48</li><li>A1 visited again at t=2: <strong>IGNORE this visit</strong></li></ul><p><strong>Property:</strong> First-visit MC is an <strong>unbiased</strong> estimator of V_π(s).</p><p><strong>Every-Visit MC</strong></p><p>Use the return from <strong>EVERY</strong> visit.</p><p>For the episode above:</p><ul><li>A1 at t=0: use G₀ = 4.48</li><li>A1 at t=2: use G₂ = -1 + 0.9(10) = 8.0</li><li>Both contribute to V(A1)’s average</li></ul><p><strong>Property:</strong> Every-visit MC is <strong>biased</strong> (because visits in the same episode are correlated), but has <strong>lower variance</strong> and is simpler to implement.</p><h4>Now we move to the next level</h4><p>So far:</p><p>We learned <strong>state values V(s)</strong></p><p>But now we ask:</p><p>“Which action is better?”</p><h4>Enter Q-Values</h4><p>Now we learn: <strong>Q(s, a)</strong> = value of taking action <em>a</em> in state <em>s</em></p><h3>Monte Carlo for Q-Values (MC Control)</h3><p>Same process, just applied to (state, action)</p><blockquote><em>“When I took this action… how did things turn out?”</em></blockquote><p><strong>Q. Why Q-Values Instead of V-Values?</strong></p><p>To improve the policy, we need to compare actions. With V(s), we’d need the transition model:</p><p>“Is going right better? Well, Right leads to A2 with V=8.5, and Down leads to B1 with V=3.0…”</p><p>This requires knowing P(s’|s, a). With Q(s,a), we just compare directly:</p><p>Q(A1, Right) = 7.5 vs Q(A1, Down) = 2.0 → Right is better!</p><h4>MC for Q-Values</h4><p>Same algorithm, but track returns for <strong>(state, action)</strong> pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Btvtnj9nWdkZCcavlx4ggQ.jpeg" /></figure><p><strong>Example</strong></p><p><strong>Episode:</strong> At A1 took Right (R=-1), at A2 took Right (R=+10), reached Goal.</p><p>Returns:</p><ul><li>Q(A1, Right): G = -1 + 0.9(10) = 8.0</li><li>Q(A2, Right): G = 10</li></ul><p>Updates:</p><p>Q(A1, Right) ← 0 + 0.1(8.0−0) = 0.8</p><p>Q(A2, Right) ← 0 + 0.1(10−0) = 1.0</p><p><strong>Intuition</strong></p><p>“When I took this action, how good did things turn out?”<br>So:</p><ul><li>Good outcome → increase Q</li><li>Bad outcome → decrease Q</li></ul><p>After many episodes, Q-values converge, and we can derive the optimal policy:</p><blockquote>π∗(s) = arg⁡max⁡aQ(s,a)</blockquote><h4>Now the big goal</h4><p>Now that we can evaluate actions…</p><p>We want to find the <strong>best policy</strong></p><h4>Finding the Optimal Policy</h4><p>Now we introduce:</p><p><strong>Exploration vs Exploitation</strong></p><h4>Problem:</h4><p>If we always pick the best-known action:</p><p>We may miss better options</p><p><strong>Solution:</strong></p><p>ε-greedy strategy</p><ul><li>With probability <strong>1−ε</strong> → best action</li><li>With probability <strong>ε</strong> → random action</li></ul><p>You can think of it like :</p><p>You always order your favourite dish…</p><p>But what if something else is better?</p><p>So, you need to try new things sometimes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*3lBd1ypsOZFsbNBS4wqI-w.png" /></figure><p><strong>The Algorithm: MC with ε-Greedy</strong></p><pre>Initialize Q(s, a) = 0 for all s, a<br>Repeat for many episodes:<br>    1. Generate episode using ε-greedy policy based on Q:<br>       - With prob 1-ε: pick argmax_a Q(s,a)<br>       - With prob ε: pick random action<br>    <br>    2. For each (s, a) pair in the episode:<br>       - Calculate return G_t<br>       - Update: Q(s,a) ← Q(s,a) + α(G_t - Q(s,a))<br>    <br>    3. Decrease ε slightly (explore less over time)</pre><h4>Why ε-Greedy Is Essential</h4><p>If we always pick the best action (pure greedy), we might NEVER try other actions. Some actions that look bad initially might actually be great.</p><p><strong>Example:</strong></p><p>After Episode 1, Q-values at A1:</p><ul><li>Q(A1, Right) = 0.8 (tried once, got decent return)</li><li>Q(A1, Down) = 0 (never tried!)</li></ul><p>Pure greedy always picks Right. But what if Down leads to an amazing shortcut? Without exploration, we’ll never discover it.</p><p>ε-greedy ensures every action gets tried occasionally, so we eventually discover the best policy.</p><h4>Advantages</h4><ol><li><strong>No model needed <br></strong>You don’t need to know environment rules (like P(s′∣s,a))<br>Like learning by <em>actually playing the game</em>, not reading the rulebook</li><li><strong>No bootstrapping<br></strong>Uses <strong>real outcomes (returns)</strong>, not guesses<br>Like judging a movie after watching it fully, not midway through</li><li><strong>Unbiased estimates<br></strong>Given enough episodes, values become correct<br>Like averaging many honest reviews → true rating emerges</li><li><strong>Works in complex/unknown environments<br></strong>Doesn’t rely strictly on the Markov property<br>Just uses full experience, no assumptions about “perfect memory”</li></ol><h4>Disadvantages</h4><ol><li><strong>Must wait until the episode ends<br></strong>No learning until the full sequence is finished<br>Like waiting till the end of a movie to decide if it’s good</li><li><strong>High variance<br></strong>Returns can be very different across episodes<br>Same starting point → sometimes jackpot, sometimes disaster</li><li><strong>Slow learning<br></strong>Needs many episodes to stabilise<br>Like needing lots of trials to build confidence</li><li><strong>Only works for episodic tasks<br></strong>Requires a clear end (terminal state)<br>Doesn’t fit situations that never end (like stock trading loops)</li><li><strong>Inefficient exploration<br></strong>Depends on random experiences<br>It might take a long time to discover important paths</li></ol><h4>The Variance Problem Illustrated</h4><p>From state A1, three episodes:</p><pre>Episode           Path                  G_t<br>1                 A1→A2→Goal            +8.0<br>2                 A1→B1→C1→Trap         -10.0<br>3                 A1→A2→A1→A2→Goal      +4.5</pre><p>G_t jumps from +8 to -10 to +4.5. The updates swing wildly. That’s high variance — and it’s exactly what motivates <strong>Temporal Difference</strong> methods, which use smaller, more frequent updates.</p><h4>Now that you’ve learned :</h4><p>Monte Carlo = learning from full experience</p><p>Like:</p><blockquote><em>Watching a full movie before judging it</em></blockquote><h4>What’s next?</h4><p>Now we ask a very important question:</p><p>“Can we learn <em>without waiting till the end</em>?”</p><p>That leads us to… Temporal Difference Learning</p><p>Where we:</p><ul><li>Learn step-by-step</li><li>Update continuously</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=704952e84bb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning(Part 2: Markov Decision Processes)]]></title>
            <link>https://7799sujit.medium.com/reinforcement-learning-part-2-markov-decision-processes-3cdf2c35bfa4?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cdf2c35bfa4</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[markov-property]]></category>
            <category><![CDATA[mdp-in-reinforcement]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 15:11:30 GMT</pubDate>
            <atom:updated>2026-04-25T16:22:40.986Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Let&#39;s use these terms to understand how to train </em>Reinforcement Learning<em>.</em></p><p>The Markov Property</p><h4><strong>In this section, we’re going to go deeper</strong></h4><blockquote>We’ll explore how decisions are actually structured using something called <strong>Markov Decision Processes (MDPs)</strong>.</blockquote><h3>The Markov Property</h3><p>Now, we are going to learn <strong>how decisions depend on states</strong>.</p><p>First thing is that if an agent wants to move to the next state, it depends on:</p><ul><li>the <strong>current state</strong></li><li>The <strong>action taken now</strong></li></ul><h4>Markov Property</h4><p>Before moving to the core of MDP, let&#39;s understand what the Markov property and the Non-Markov property are :</p><p>Now, under the <strong>Markov property</strong>, the next state depends only on the current state and the action taken. It does <strong>not</strong> depend on how you reached that state.</p><p>You can think of yourself driving and see a <strong>red light</strong>:</p><ul><li>You stop because the light is red <strong>right now</strong></li><li>You don’t care how long it’s been red or what happened before</li></ul><blockquote>Decision depends only on the <strong>current state (red light)</strong></blockquote><h4>Non-Markov Property</h4><p>In a <strong>non-Markov process</strong>, the next state depends not only on the current state, but also on the entire history of past states and actions.</p><p>A doctor doesn’t just look at your current symptoms:</p><ul><li>They ask about <strong>past illnesses, habits, and history</strong></li><li>The treatment depends on your <strong>entire history</strong>, not just now</li></ul><blockquote>Decision depends on <strong>current state + past information</strong></blockquote><p>Let&#39;s look at the equation for the Markov Property and the Non-Markov Property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIdDXExYXDoG_KXzJ1rfCQ.jpeg" /></figure><p>How to read an equation:</p><p>In Markov, the new state “<em>S_t+1</em>” depends only on the action “<em>A_t</em>” taken on the current state “<em>S_t</em>”, and in non-Markov, the new state “<em>S_t+1</em>” depends on all the states <em>S_1, S_2, ….. S_t</em> and actions <em>A_1, A_2, ….. A_t</em> taken on that state.</p><p>Now, once we understand the Markov, let&#39;s understand the Bellman Equation</p><h3>The Bellman Equation</h3><blockquote>Now that we understand how states work,<br> <strong>We will learn how to measure how good a state is</strong></blockquote><blockquote>This is where the <strong>Bellman Equation</strong> comes in.</blockquote><p>In this, the <strong>next state depends only on the current state</strong>, not on the full history. This allows us to define value functions recursively.</p><h4>Bellman Equation(V_π)</h4><p>My value = average over all actions I might take of (reward now + discounted value of where I end up)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl9QP6W1V5zhBhChycnvEw.jpeg" /></figure><p><strong>Don’t get scared with this formula, let&#39;s break it piece by piece:</strong></p><ul><li>∑ₐ π(a|s): For each action, weighted by how likely I am to take it</li><li>∑ₛ′ P(s′|s, a): For each possible next state, weighted by transition probability</li><li>R(s, a, s’) : The reward I get for this transition</li><li>γVπ(s′): Discounted value of the state I land in</li></ul><h4>Intuition</h4><p>Think of it like planning your day:</p><p>“My current happiness =<br> What I get now + how good my future will be”</p><ul><li><strong>Immediate reward (r)</strong> → like getting paid today</li><li><strong>Future value </strong>γVπ(s′) → like future salary growth</li><li><strong>Discount factor (γ)</strong> → how much you care about the future</li></ul><h4>Final Idea</h4><p>The value of a state under a policy “π” is the <strong>expected (average) sum of:</strong></p><ul><li>the <strong>reward you get now</strong>, and</li><li>the <strong>discounted value of the next state</strong></li></ul><p>Now look at this tree. Let’s suppose the agent starts from state “s”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNrFNQzrMVrqPwOUgw59bA.jpeg" /></figure><p>How to read the above formula. Now read it like a sentence from <strong>left to right</strong>, but interpret it in layers:</p><blockquote>The value of state s under policy π…</blockquote><p>Now go inside:</p><h4>Step 1: Choose an action</h4><p>At state<strong>s</strong>, the agent can take either action <strong>a₁ or </strong>action <strong>a₂</strong></p><p>This is: <strong>∑ₐ π(a|s)</strong></p><blockquote>“Consider all actions, weighted by how likely I choose them”</blockquote><p>Example:</p><ul><li>π(a₁|s) = 0.8</li><li>π(a₂|s) = 0.2</li></ul><h4>Step 2: See where you might land</h4><p>After taking an action, you might go to <strong>s₁</strong> or <strong>s₂</strong></p><p>This is: <strong>∑ₛ′ P(s′|s,a)</strong></p><blockquote>“Consider all possible next states, weighted by transition probability”</blockquote><p>Example:</p><ul><li>P(s₁|s, a₁) = 0.3</li><li>P(s₂|s, a₂) = 0.7</li></ul><h4>Step 3: What do you get?</h4><p>For each possible path (like s → a₁ → s₁), you get:</p><ul><li><strong>Immediate reward</strong> → R(s,a,s′)<br>Example: R = -1 if s to s₁ or R = -10 if s to s₂</li><li><strong>Future value</strong> → γVπ(s′)</li></ul><p><strong>Let&#39;s understand how to calculate the value for deterministic and stochastic environments. </strong><em>Let for Numeric Example: [Ignore Σ_a π(a|s) for simplicity]</em></p><blockquote>so formula look like this, P(s′|s,a)[R(s, a, s’) + γVπ(s′)]</blockquote><p>Till now, we have learned:</p><ul><li>What Markov means</li><li>How to evaluate a state using the Bellman Equation</li></ul><p>Now let’s go one step ahead.</p><p>Now we will understand <strong>how the environment behaves.</strong></p><h4><strong>Deterministic:</strong></h4><p>There is only <strong>one next state</strong> for a given (state, action)</p><p>So we learn in last blog for determinitic P(s′∣s, a)=1 for one specific s′</p><pre>At A1, policy says Right with 100%. Going Right always leads to A2 with R = -1.<br><br>V(A1) = 1.0×[−1+0.9×V(A2)]V(A1) = 1.0 <br><br>If V(A2) = 9.0:<br><br>V(A1) = −1+0.9(9.0)= −1+8.1 = 7.1</pre><h4>Stochastic:</h4><p>The same action can lead to <strong>multiple next states with probabilities</strong></p><p>So we learn in last blog for Stochastic P(s′∣s, a) is distribution(not just 0 or 1)</p><pre>At A1, policy: Right=80%, Down=20%. The environment is deterministic.<br><br>V(A1) = 0.8[−1+0.9×V(A2)] + 0.2[−1+0.9×V(B1)]V(A1)<br><br>With V(A2) = 9.0, V(B1) = 3.0:<br><br>=0.8[−1+8.1]+0.2[−1+2.7]<br><br>=0.8(7.1)+0.2(1.7) = 5.68+0.34 = 6.02</pre><blockquote>Now, we have learned what the Bellman equation is, and we will now look at the optimal Bellman equation.</blockquote><p>So Far</p><p>We now understand:</p><ul><li>How to evaluate states</li><li>How environments behave</li></ul><p>Now comes the most important upgrade.</p><h3>Bellman Optimality Equation</h3><p>Till now, we were following a <strong>fixed policy (plan)</strong></p><p>Now we ask:</p><p><strong>“What is the BEST possible decision?”</strong></p><p>So the idea is instead of averaging actions, we:</p><p><strong>Choose the best action</strong></p><p>So when we move from a <strong>policy-based value</strong> “Vπ” to the <strong>best possible value</strong>, we use the <strong>Bellman Optimality Equation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QP9LXd3RydEOmgSSnrGQ7w.jpeg" /></figure><p>We have changed the <strong>∑ₐ π(a|s) </strong>to<strong> max</strong></p><h4>Simple Intuition</h4><p>Imagine you’re choosing the <strong>best route to reach home</strong>:</p><ul><li>You try all possible paths (actions)</li><li>For each path, you estimate:<br>immediate cost (fuel, time)<br>future cost (traffic ahead)</li><li>Then you pick the <strong>best option (maximum value)</strong></li></ul><p>That’s exactly what this equation does.</p><h4>What Changed from Bellman Expectation?</h4><p>Earlier (for policy Vπ):</p><ul><li>You followed a <strong>fixed strategy (policy)</strong></li><li>Took the <strong>average over actions</strong></li></ul><p>Now (for optimal V*):</p><ul><li>You choose the <strong>best action</strong></li><li>Replace average with <strong>max</strong></li></ul><p>Till now, we are aware of the Bellman equation and the optimal Bellman equation.</p><p>Now, let&#39;s look at how an agent learns the best decisions in a world with uncertainty, step by step.</p><h4><strong>1: Policy Evaluation (Finding V for a given policy)</strong></h4><p>We want to compute the value function for a <strong>given policy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl9QP6W1V5zhBhChycnvEw.jpeg" /></figure><p><strong>Intuition</strong></p><p>Imagine estimating your monthly expenses:</p><ul><li>First guess → rough estimate</li><li>Update using better info</li><li>Repeat until the numbers stop changing</li></ul><p>That’s exactly what <strong>iteration until convergence</strong> means.</p><h4><strong>2: Policy Improvement (Making the policy better)</strong></h4><p>Now that we know how good each state is, we improve the policy by choosing the <strong>best action</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2_zhmepglrZhkbjqRDrIA.jpeg" /></figure><p><strong>Intuition</strong></p><p>Now you act smarter:</p><ul><li>Earlier → you followed a fixed routine</li><li>Now → you always pick the <strong>best option available</strong></li></ul><p>Like switching from “habit” to “smart decision-making”</p><h3>Putting It Together: Policy Iteration</h3><ol><li><strong>Evaluate policy</strong> → find Vπ</li><li><strong>Improve policy</strong> → make it greedy</li><li>Repeat until policy stops changing</li></ol><p>This process guarantees finding the <strong>optimal policy</strong></p><h3>Two steps in Policy Iteration</h3><h4><strong>Policy Evaluation (Actor)</strong></h4><p>“How good is my current plan?”</p><p><strong>Intuition</strong></p><p>You <strong>fix a policy</strong> (route) and ask: “If I follow this exact plan, how good is each location? Or if I stick to this route, how long will it take from each point?”</p><p>You’re NOT choosing better actions here.<br> You’re just <strong>measuring</strong> how good your current plan is.</p><h4><strong>Policy Improvement (Critic)</strong></h4><p>“Can I do better?”</p><p><strong>Intuition</strong></p><p>Now you say: <em>“At each location, is there a better road than what my plan says?” </em>Here, you <strong>take the max over actions</strong>.<br>Like: <em>“Wait, from here, another road is faster — let me update my route.”</em></p><h4><strong>Step to train</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydGrncpZjcirt8bQ8eF8HQ.png" /></figure><h4>1. Actor (The Decision Maker)</h4><p>The <strong>Actor</strong> decides: <em>“What action should I take?”</em></p><ul><li>It represents the <strong>policy</strong> π(a∣s)</li><li>Takes state → outputs action</li><li>Learns to choose <strong>better actions over time</strong></li></ul><p><strong>Analogy:</strong><br> Like a <strong>driver </strong>deciding which road to take</p><h4>2. Critic (The Evaluator)</h4><p>The <strong>Critic</strong> evaluates: <em>“Was that a good decision?”</em></p><ul><li>It estimates the <strong>value function</strong> V(s) or Q(s,a)</li><li>Gives feedback to the actor</li></ul><p><strong>Analogy:</strong><br> Like a <strong>driving instructor </strong>saying: <em>“Good move” or “That was a bad turn”</em></p><h4>Steps =&gt;</h4><ol><li>Start with random policy π₀</li><li>Evaluate: compute V_{π₀} using Bellman equation</li><li>Improve: make new policy π₁ greedy w.r.t. V_{π₀}</li><li>Evaluate: compute V_{π₁}</li><li>Improve: make π₂ greedy w.r.t. V_{π₁}</li><li>Repeat until policy stops changing → optimal π*</li></ol><h4><strong>Let’s do a calculation. Consider the above 3 by 3 grid.</strong></h4><pre>Policy Evaluation (Bellman Equation). For simplification ignore ∑ₐ π(a|s) and ∑ₛ′ P(s′|s,a) <br><br>So formula look like, Vπ(s) = R(s,a,s′) + γVπ(s′)<br><br>Step 1: Policy Evaluation<br><br>Suppose 1st agent follow path =&gt; A1 → B1 → C1 → C2<br><br>Calculations<br><br>1. C2 <br>V(C2) = −10<br><br>2. C1 → C2<br>V(C1)=−1+0.9×(−10)=−10<br><br>3. B1 → C1<br>V(B1)=−1+0.9×(−10)=−10<br><br>4. A1 → B1<br>V(A1)=−1+0.9×(−10)=−10<br><br>Result<br>State   Value<br>A1      -10<br>B1      -10<br>C1      -10<br><br><br>Step 2: Policy Improvement<br>π′(s)=argmax_a​*[R(s,a,s′)+γV(s′)]<br><br>Calculate All Actions at B1<br>1. Down (B1 → C1)<br>Q(B1,Down)=−1+0.9×(−10)=−10<br><br>2. Up (B1 → A1)<br>(Use updated better path via A1 → A2 → A3)<br>V(A1)=−1+0.9×8=6.2<br><br>Now:<br>Q(B1,Up)=−1+0.9×6.2=4.58<br><br>Comparison<br>Action   Value<br>Down     -10<br>Up       4.58<br><br><br>Now Policy Update<br>π′(B1)=Up<br><br><br>Step 3: Re-Evaluation (Values Get Fixed)<br>Now recompute values using improved policy.<br><br>1. A3 (Goal)<br>V(A3)=10<br><br>2. A2 → A3<br>V(A2)=−1+0.9×10=8<br><br>3. A1 → A2<br>V(A1)=−1+0.9×8=6.2<br><br>4. B1 → A1 (Improved)<br>V(B1)=−1+0.9×6.2=4.58<br><br>5. C1 → B1<br>V(C1)=−1+0.9×4.58=3.12<br><br><br>### Final Result (Corrected Values)<br><br>State    Before     After<br>A1       -10        6.2<br>B1       -10        4.58<br>C1       -10        3.12</pre><h4>Final Result</h4><p>When the policy no longer changes:</p><ul><li>You have reached the <strong>optimal policy</strong> π*</li><li>And its value function V*</li></ul><h4>Key Insight (Very Important)</h4><ul><li>Evaluation = Understanding your current strategy</li><li>Improvement = Making it smarter</li></ul><h3>Limitations of Markov Decision Processes (MDPs)</h3><p>MDPs are powerful, but they come with some <strong>important limitations</strong>. Let’s break them down in a simple way.</p><h4>1. Full Knowledge Required (Model-Based)</h4><p>MDP assumes you know:</p><ul><li>Transition probabilities P(s′∣s,a)</li></ul><p><strong>Problem:</strong><br> In real life, we usually <strong>don’t know these exactly</strong></p><p><strong>Analogy:</strong><br> Like planning a trip but already knowing:</p><ul><li>exact traffic</li><li>exact weather</li><li>exact delays</li></ul><p>Not realistic.</p><h3>2. State Explosion (Curse of Dimensionality)</h3><p>As states increase, computation becomes huge</p><ul><li>More states → more values to compute</li><li>Slower convergence</li></ul><p><strong>Analogy:</strong><br> Like a maze that keeps growing bigger — harder to solve every time</p><h3>3. Markov Assumption (No Memory)</h3><p>MDP assumes: <em>“Current state contains all necessary information”</em></p><p><strong>Problem:</strong><br> Many real-world problems need <strong>history</strong></p><p><strong>Examples:</strong></p><ul><li>Stock market (past trends matter)</li><li>Healthcare (patient history matters)</li></ul><p><strong>So far, we have learned:</strong></p><ul><li>Markov Property</li><li>Bellman Equation</li><li>Optimal Decisions</li><li>Policy Iteration</li><li>Limitations of MDP</li></ul><blockquote>Next up: What if we don’t know the transition probabilities? We’ll learn to estimate values from pure experience using Monte Carlo Methods.</blockquote><p><strong>In this, we will learn how to learn purely from experience</strong></p><p>No model.<br>No prior knowledge.</p><p>Just trial and learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cdf2c35bfa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning(Part 1: Terms used in RL)]]></title>
            <link>https://7799sujit.medium.com/reinforcement-learning-part-1-terms-used-in-rl-6563136a0710?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/6563136a0710</guid>
            <category><![CDATA[how-llm-reasoning-works]]></category>
            <category><![CDATA[llm-reasoning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 11:05:00 GMT</pubDate>
            <atom:updated>2026-04-25T16:04:08.052Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>If intelligence is a cake, the bulk of the cake is unsupervised learning, the icing on the cake is supervised learning, and the cherry on the cake is reinforcement learning.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypXztxLS5iLjtqXqdqwiHA.png" /></figure><h3>What Is Reinforcement Learning?</h3><h4>Let’s start with something familiar.</h4><p>Imagine you’re playing a video game.</p><ul><li>You move your character</li><li>You collect coins</li><li>You avoid enemies</li><li>You try to win</li></ul><p>Now think for a second…</p><p><strong>How did you actually get better at the game?</strong></p><p>You didn’t read a manual.<br> You didn’t memorise rules.</p><p>You:</p><ul><li>Tried something → got rewards (coins)</li><li>Made mistakes → lost points</li><li>Slowly improved</li></ul><p>That’s exactly how Reinforcement Learning works.</p><p>It’s learning by doing… and improving from feedback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Yzhd8DJCJoC33O82dD3Ttg.gif" /></figure><p><em>Reinforcement Learning is about learning through trial and error, where actions that lead to better outcomes are rewarded.</em></p><h4>Core Idea in</h4><ol><li>You observe the situation</li><li>You take an action</li><li>You get feedback</li><li>You improve</li></ol><p>Repeat this again and again.</p><h3><strong>Let&#39;s understand the terms used in RL</strong></h3><h4><strong>Consider 3*3 grid</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PA-aFbdnAdanpMdZT0k_g.jpeg" /></figure><p>In this 3×3 grid. Every time the agent moves from one cell to another, it will get a reward of -1 points. If it accidentally steps into a trap cell, it gets a reward of −10 points(penalty). But if it successfully reaches the goal cell, it earns a reward of +10 points.</p><h3>Agent (Who is learning?)</h3><p>Now, let’s start with the most important piece, i.e. <strong>Agent</strong></p><p>The <strong>Agent</strong> is the learner.</p><p><strong>Real-life analogy:</strong></p><ul><li>You&#39;re playing a game</li><li>A robot learning to walk</li><li>A dog learning tricks</li></ul><p><em>Agent = decision maker</em></p><h3>Environment (Where everything happens?)</h3><p>Now we know who is learning.</p><p>Next question: <em>Where is it learning?</em></p><blockquote>That’s the <strong>Environment</strong>.</blockquote><p>In our case, the 3×3 grid is the environment where the agent can move</p><p>Other example:</p><ul><li>Game world</li><li>Road (for self-driving car)</li><li>Chess board</li></ul><h3>State (Current situation)</h3><p>Now we know:</p><ul><li>Who → Agent</li><li>Where → Environment</li></ul><p>Next question: <em>What’s the current situation?</em></p><p>That’s called a <strong>State</strong>. So, the state is the current snapshot of the environment.</p><p>In our 3×3 grid: A1, A2, B3… etc are the states. If the agent moves from A1 to A2, then we will say the agent&#39;s current state is A2.</p><blockquote><strong><em>Denoted as “</em></strong><em>S</em><strong><em>”</em></strong></blockquote><p><strong>Other example:</strong></p><ul><li>Super Mario Game → Think of it like your current position in a game.</li></ul><h3>Action (What can you do?)</h3><p>Now comes “What choices do we have?”</p><p>These are <strong>Actions</strong>. So actions are all possible moves the agent can take. In short, all possible choices which agent can take on a state “s” to reach the next state.</p><p>In the above 3*3 grid, the agent can take action like {Up, Down, Left, Right}</p><blockquote><strong><em>Denoted as “</em></strong><em>A</em><strong><em>”</em></strong></blockquote><p><strong>Other example:<br></strong>Driving a car. So action could be :</p><ul><li>Move left/right</li><li>Accelerate / brake</li><li>Pick up the object</li></ul><h3><strong>Transition Probability</strong></h3><p>Till now, we know:</p><ul><li>We are in a <strong>state</strong></li><li>We take an <strong>action</strong></li></ul><p>But here’s the real question:</p><p><em>What are the chances that we actually reach the next state we expect?</em></p><p>This is where Transition Probability comes in.</p><p>It tells us: If I am in the state s and I take actiona, What is the probability that I will end up in state s′?</p><p><strong><em>Denoted as “</em></strong>P(s’|s, a)<strong><em>”</em></strong></p><p><strong>We can understand like this</strong></p><ul><li>You are here (current state)</li><li>You take an action</li><li>There are multiple possible next states</li><li>Each one has a probability</li></ul><p>That’s exactly what transition probability captures.</p><p><strong>Consider the same 3×3 grid to understand this</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2FZsdZmbakFH1msVKTHpA.jpeg" /></figure><p>The agent is currently in state <strong>A1. </strong>It has two possible actions: <strong>DOWN</strong> or <strong>RIGHT</strong></p><p>Now:</p><ul><li>If the agent chooses <strong>DOWN</strong>, it may move to <strong>B1</strong> with probability <strong>0.1</strong><br> → P(B1∣A1,DOWN)=0.1</li><li>If the agent chooses <strong>RIGHT</strong>, it may move to <strong>A2</strong> with probability <strong>0.9</strong><br> → P(A2∣A1,RIGHT)=0.9</li></ul><blockquote>So, the transition function tells us:<br>Given where you are (A1) and what you do (action), how likely is it that you end up in a particular next state?</blockquote><p><strong>Why is this important?<br></strong>Now we have learned something very powerful:</p><p>Actions don’t always guarantee results.</p><h4>Type of Transition</h4><h4>1: Deterministic Environment</h4><p><strong>Suppose we have a simple maze<br></strong>Every action leads to exactly one state.</p><p>At state A1, if I take Action Right Next, state A2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpXKoLCKNYeABHAsRI1cZw.png" /></figure><p>In this, the probability is always 1</p><h4>2: Stochastic Environment</h4><p><strong>Suppose we have a windy maze<br></strong>Actions have random outcomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmUPNYu4hkTy2J9-Cz9aOg.png" /></figure><h3>Reward (Feedback system)</h3><p>Now let’s talk about feedback.</p><p>A reward tells the agent how good or bad an action was, OR How much reward the agent will get from one state to the next state.</p><blockquote><strong><em>Denoted as “</em></strong>R(s, a, s’)<strong><em>”</em></strong></blockquote><p>In a 3 by 3 grid, the agent moves right from State A2 to State A3: R = +10</p><p>Other example :</p><ul><li>Points in a game</li><li>Treats for a dog</li></ul><p><em>Reward is the feedback signal that helps the agent learn better decisions.</em></p><h3><strong>Discount factor</strong></h3><p>How much should we value future rewards?<br>Eg =&gt; γ = 0.9</p><blockquote><strong><em>Denoted as “</em></strong>γ<strong><em>”</em></strong></blockquote><p>Why Discount?<br><strong>1. Uncertainty (Future is unpredictable)<br></strong>Imagine someone promises you ₹100 <strong>today</strong> vs ₹100 <strong>after 10 days</strong>.</p><ul><li>Today → guaranteed</li><li>After 10 days → maybe something goes wrong</li></ul><p>Just like real life, future rewards in decision-making depend on many uncertain events.<br> So, we slightly “trust” them less.</p><p><strong>Reason 2: Time preference(Sooner is better than later)<br></strong>If you get ₹100 today, you could invest it, spend it, or use it immediately.<br>But ₹100 next year? You lose all that opportunity.</p><p>Same idea here:<br><strong>Earlier rewards are more valuable than delayed ones.</strong></p><p><strong>Reason 3: Mathematical Necessity (Keeping things finite)<br></strong>Imagine a system that keeps giving rewards forever:</p><ul><li>Without discount → total reward becomes <strong>infinite</strong></li><li>With discount → future rewards shrink over time</li></ul><p>Like adding:</p><ul><li>Without discount: 1 + 1 + 1 + 1 + … = ∞</li><li>With discount: 1 + 0.9 + 0.⁹² + 0.⁹³ + … = finite</li></ul><h3><strong>Return</strong></h3><p>Now let’s combine everything.</p><p>The agent doesn’t just care about one reward.</p><p>It cares about <strong>total future reward</strong>.</p><blockquote>Return = Total future reward</blockquote><p>It is the total future reward which agent can get. In RL, the agent’s goal isn’t to maximise immediate reward, it’s to maximise <strong>total future reward</strong>.</p><blockquote><strong><em>Denoted as “</em></strong>G<strong><em>”</em></strong></blockquote><p>Think of it like planning your career:</p><ul><li>You don’t pick a job just for today’s salary</li><li>You choose something that gives better growth and rewards in the long run.</li></ul><h4>Type of Return</h4><h4><strong>1: Episodic Task</strong></h4><p>It is the sum of rewards from the current state to the goal state, which has a fixed timestamp or a finite number of timestamps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLBSkpwQ7DLXuYT00-X4XA.jpeg" /></figure><p>This is the formula. In this, you are giving equal importance to every reward.</p><p><strong>Numeric Example<br></strong>Agent takes path: A1 →(-1)→ A2 →(-1)→ B3 →(-1)→ A3(+10)</p><p>G0​ = (−1) + (−1) + (−1) + (+10) = 7</p><h4><strong>2: Continuous Task</strong></h4><p>It is the sum of all the rewards ever obtained by the RL agent, but the discount factor determines how far future rewards need to be accounted for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqlq5yq-LUepF1Ws1gKOGw.jpeg" /><figcaption>Where 0≤γ&lt;10</figcaption></figure><p>This is the formula. In this, you are giving more importance to the current one as compared to the future reward.</p><p>Think of it like <strong>earning money over your lifetime</strong>:</p><ul><li>Money today is more valuable than money far in the future</li><li>So future rewards are “discounted”</li></ul><p><strong>Numeric Example<br></strong>Agent takes path: A1 →(-1)→ A2 →(-1)→ B3 →(-1)→ A3(+10)</p><p><strong>With γ = 0.9:<br></strong>G0​ = −1 + 0.9(−1) + 0.81(−1) + 0.729(+10)<br>=−1 − 0.9 − 0.81 + 7.29=4.58</p><p><strong>With γ = 0.5:<br></strong>G0 = −1 + 0.5(−1) + 0.25(−1) + 0.125(+10)<br> =−1 −0.5 −0.25 + 1.25 = −0.5</p><h3><strong>Policy</strong></h3><p>Now comes a very important idea.</p><p>How does the agent decide what to do?</p><p>That’s called a <strong>Policy (π)</strong>. So, policy is the agent’s <strong>complete strategy. </strong>It tells the agent what to do in EVERY state.</p><blockquote><strong><em>Denoted as “</em></strong>π<strong><em>”</em></strong></blockquote><p>Think of it like a <strong>personal rulebook or habit</strong>:</p><ul><li>“When I’m in this situation, I do this.”</li></ul><h4>Type of policy</h4><h4><strong>1: Deterministic Policy: π(s)</strong></h4><p>In state “s”, always take action “a”.<br>For example: Policy will be like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*h3GSDvLKRRkvlirx0x3x_Q.png" /></figure><p>You can think of a fixed rule while driving:</p><ul><li>“If the light is red → STOP”</li><li>No randomness, always the same decision</li></ul><blockquote>Same state → same action every time</blockquote><h4><strong>2: Stochastic Policy: π(a|s)</strong></h4><p>In state “s”, take each action with some probability.<br>For example: Policy will be like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ip2xmh5cdZhFsY4oboecpA.png" /></figure><p>You can think about deciding what to eat:</p><ul><li>70% chance → eat healthy</li><li>30% chance → eat junk</li></ul><p>You don’t always make the same choice, but you follow a pattern of probabilities.</p><blockquote>Same state → different actions possible (with probabilities)</blockquote><h3><strong>Value Functions(</strong>The core of RL<strong>)</strong></h3><p>Now we reach the heart of Reinforcement Learning.</p><p>Until now, we have learned:</p><ul><li>States</li><li>Actions</li><li>Rewards</li></ul><p>Now, at every moment, the agent faces a question</p><p>“How good is this situation?”<strong><br></strong>So if you’re one step from the goal, things are great. If you’re surrounded by traps, things are terrible. The value function quantifies this intuition with a single number.</p><h4>Type of value function</h4><h4><strong>1: State Value Function:</strong></h4><p>It tells how good it is to be in state “s” if we follow policy “π”? Or we can say, if I start here and follow my usual strategy, how good will my future be?</p><blockquote><strong><em>Denoted as “</em></strong>V_π(s)<strong><em>”</em></strong></blockquote><p>Imagine you’re standing at a bus stop.<br>* If this stop is <strong>close to your destination</strong>, it’s a <em>good</em> place → high value<br>* If it’s <strong>far or unsafe</strong>, it’s a <em>bad</em> place → low value</p><p><strong>In short,</strong> =&gt; If I’m in state “s” and I follow policy “π” from now on, what total reward do I EXPECT to collect?<br><strong>Why “Expected”?<br></strong>Because the future is uncertain. From state A1, the agent might:</p><ul><li>Go Right → A2 → Goal (+8.0 return)</li><li>Go Right → A2 → A1 → A2 → Goal (+4.5 return, took a detour)</li><li>Go Down → B1 → C1 → Trap (-10.0 return)</li></ul><p>V_π(A1) is the <strong>average</strong> of all these possible futures, weighted by their probabilities under policy π.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFNKG2RKgKgy2hEhxaQkGg.jpeg" /></figure><p><strong>Break it piece by piece:</strong></p><ul><li><strong>Vπ(s) </strong>→ Value of state “<em>s”</em> when following policy π</li><li><strong>Eπ </strong>→ “Expected” (average outcome if you repeat many times using policy π) <a href="https://www.geeksforgeeks.org/maths/expected-value/">[1]</a></li><li><strong>∑ </strong>→ Add all future rewards (from now to forever)</li><li><strong>γ </strong>→ Discount factor. Future rewards matter less than immediate ones</li><li><strong>R </strong>→ Reward you get in the future</li><li><strong>“/ S_t=s” </strong>→ “Given that I am currently in state s”</li></ul><p><strong>How to read this formula:<br></strong><em>“Start here → follow your strategy → add all future rewards (slightly discounted) → take average”</em></p><h4><strong>2: Action Value Function</strong></h4><p>How good is it to TAKE action in states “s”, then follow policy “π”? Or we can say, if I take this action now, and then follow my strategy, how good will things be?</p><blockquote><strong><em>Denoted as “</em></strong>Q_π(s, a)<strong><em>”</em></strong></blockquote><p>Now you’re at that same bus stop, but thinking:</p><ul><li>“Should I take bus A or bus B?”<br>Each choice leads to different outcomes.</li></ul><p><strong>In short,</strong> =&gt; If I’m in state s, take action a, THEN follow policy π afterwards, what total reward do I expect?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOtZKb_JCnmlbh8auAKiKw.jpeg" /></figure><p><strong>Break it:</strong></p><ul><li><strong>Qπ(s, a) </strong>→ Value of taking action <em>a</em> in state <em>s</em></li><li><strong>E </strong>→ Expected (average over many runs)</li><li><strong>G</strong> → Total future reward (same as the big sum above)</li><li><strong>“/ St=s, At=a”</strong> → “Given I am in state s AND I take action a now”</li></ul><p><strong>How to read this formula:<br></strong><em>“Start here → take this action → then follow your strategy → total up rewards(slightly discounted) → average it”</em></p><h3>Let’s pause and reflect……….</h3><p>So far, we have learned:</p><ul><li>What RL is</li><li>Agent &amp; Environment</li><li>State &amp; Action</li><li>Rewards &amp; Return</li><li>Discount factor</li><li>Policy</li><li>Value functions</li></ul><h4>What’s next?</h4><p>Now that we understand all the building blocks…</p><blockquote>Next step: <strong>How do we actually USE these concepts to train models?</strong></blockquote><p>That’s where things get really exciting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6563136a0710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Should I Trust You?]]></title>
            <link>https://7799sujit.medium.com/why-should-i-trust-you-f743903678b0?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/f743903678b0</guid>
            <category><![CDATA[lime-machine-learning]]></category>
            <category><![CDATA[lime-and-shap]]></category>
            <category><![CDATA[lime]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 04:41:31 GMT</pubDate>
            <atom:updated>2021-09-06T04:45:00.686Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this blog, we will discuss the LIME concept. LIME basically help us to Interpret any Machine Learning and Deep Learning Models. LIME provides local model interpretability.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*whmHXmCOZIwHEAKc.gif" /></figure><h3>Why LIME was Introduce?</h3><p>There was one major issue, as the Machine Learning model is getting complex(SVM with the kernel, Deep Learning, etc) we are losing the interpretability of the model. Which mean we are not able to know on what basis the model is predicting output as class 1, 2 or etc.</p><p>For eg, If you had trained a model to classify a horse and dog and the model is working really good on the train and test dataset but after deploying the model it’s got failed. There could a possibility that all horse’s images contain grass background and the model had learned that where ever grass will come it will predict as a horse. That’s why we need an Interpretable model to look at why the model is saying particular output.</p><p><strong>Other eg</strong> which I have taken from LIME <a href="https://arxiv.org/pdf/1602.04938.pdf">paper</a>.</p><p>eg 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MnmWp3fHF84b5RMBR3VDg.png" /><figcaption>The bar chart represents the importance given to the most relevant words, also highlighted in the text. Colour indicates which class the word contributes to (green for “Christianity”, magenta for “Atheism”)</figcaption></figure><p><em>In this, you can see that model is predicting correct but Christianity is learned in the wrong way because Christianity is dependent on some stopwords like “this”, “by”, “in” etc.</em></p><p>eg 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Kj5-l7b9Xcil0f-rJBXlKA.png" /><figcaption>Explaining an image classification prediction made by Google’s Inception neural network. The top 3 classes predicted are “Electric Guitar” (p = 0.32), “Acoustic guitar” (p = 0.24) and “Labrador” (p = 0.21)</figcaption></figure><p><em>In this, you can see the model is working in a good sense because the model can learn where is “labrador” or “guitar”.</em></p><p><em>NOTE — This interpretation is very useful while making a case study belong from medical or finance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*eFzKgoOoTzqdBR4k.gif" /></figure><p><strong>REACTIONS</strong></p><p>WOW!!</p><p>NACE!!</p><p>AWESOME!!</p><p>COOL!!</p><h3>Interpretability IMPORTANCE</h3><ul><li>We can trust our model predictions.</li><li>We can know exactly how our AI system behaves.</li><li>We can understand the behaviour of the model. Is our data behaving as expected?</li><li>We can do improvement and enhancement of the model.</li><li>Better decision making by interpretation.</li></ul><p><em>Read more importance of interpretability </em><a href="https://theblue.ai/blog/lime-models-explanation/"><em>here</em></a></p><h3>Let digest LIME slowly slowly</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*REQ9uams7JNBudy1.gif" /></figure><p>Let first ask a basic question what is <strong>Local </strong>in <strong>LIME</strong>(<strong>Local Interpretable Model-agnostic Explanations).</strong></p><p>To understand Local we have to understand, what <strong>Global</strong> is?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*A6h7eaFTleDjIiMcT1AlUA.png" /></figure><p>If we make a linear model to classify two classes then the model will give a global feature importance score. Now suppose we give a test query ‘x_q’ to a linear model then the interpretation of ‘x_q’ will be based on a global hyperplane or global feature importance score. In global, it doesn&#39;t matter where my ‘x_q’ will be the feature importance score will be the same.</p><p>Similarly, in the tree-based model, we are looking globally to decide the output of the test query.</p><p><strong><em>Note — Linear and Tree-based models are highly interpretable.</em></strong></p><p>Now let’s understand, what <strong>Local </strong>is?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxuCUmPoAAzmfY_21mWFcg.png" /></figure><p>Let <strong>f()</strong> be any function that makes this type of boundary. The key point is if we get test case <strong>x_q </strong>then we will not look at the whole plane we will only look at a small area to know why the model had given x_q as a particular class. That’s why it is called a <strong>local interpretable. </strong>As shown in fig.</p><p>.</p><p><strong><em>NOTE — It can work for Regression and Classification. Output i.e. ‘y’ will real number</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*o84qJL-F1Y1Fo1m2kWIisQ.png" /></figure><h3>Intuition behind LIME</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_B95xPyKzh61S6jS_ZlfsA.png" /><figcaption>F() is a black-box model which helps us to classify two classes and g() is a surrogate model.</figcaption></figure><p><em>NOTE — Big and small red plus similarly blue big and small dot is telling that we are giving less weightage as point are far from the LINE.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*liPeeYwWnopD6N7U.gif" /></figure><p><strong>REACTIONS</strong></p><p>What the heck!!</p><p>What is this!!</p><p>Is this Amoeba?</p><p>Ok!! Just for now see as there will be one line or hyperplane which will classify two classes in the local region. This linear model + regularisation is called a surrogate model which is represented by g().</p><p>The surrogate model is almost equivalent to the black-box i.e. f() model but the input i.e ‘x’ for the surrogate model is not the same input on which f() had been trained. In the surrogate model, we give ‘x_dash’ where ‘x_dash’ is an interpretable vector. ‘x_dash’ interpretable means that we are converting ‘x’ into the binary vector using OHE or BOW because these vectors are highly interpretable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29qKNRKWcpXil1GbqLCcjQ.png" /></figure><p>NOTE — ‘x’ dim != ‘x_dash’ dim because ‘x_dash’ is a binary vector.</p><p>Now Let’s see how we will convert data into the interpretable form in different datasets for eg TEXT, NUMERICAL, IMAGE.</p><p><strong>TEXT :</strong></p><p>To make text data in interpretable form we can convert the text into a bag of words. In BOW we know easily understand how many times words repeat or which words had come so it is very interpreted.</p><p><strong>NUMERICAL:</strong></p><p>To convert the value into interpretable format then we can make a bin and then do OHE(one-hot encoding).</p><p>Eg. ==&gt;</p><p>Input : [1.1, 2.1, 2.7, 7, 8.4, 9.1, 9.7, 10]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*IhgbGc6LB_RH-vL0Pfdj_w.png" /></figure><p>Approach :</p><p>Now we will get A, B, C…….</p><p>After this, we can convert categorical input into OHE</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p><strong>IMAGE :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*OQQkTyOTAGgcmET3tHOpHw.png" /></figure><p>To convert the image into the interpretable format we break the image into <strong>superpixel </strong>and then make a vector by looking pixel present or not.</p><p><em>Read more about superpixel </em><a href="https://cran.r-project.org/web/packages/OpenImageR/vignettes/Image_segmentation_superpixels_clustering.html"><em>here</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*lXqErD_sktOE07VP.gif" /></figure><p>.</p><p>.</p><p>.</p><p><strong>REACTION</strong></p><p>Nice hack!! for image</p><p>.</p><h3>Before going on maths let’s clear some terms</h3><ol><li><strong>Surrogate Model :</strong></li></ol><ul><li>g() = It is an approx of f() neighbor of x_q</li><li>Model g<strong>∈</strong>G = class of easily interpretable model. {Linear model with regularisation or Decision tree}</li><li>Ω(g) = Comeplexity of g (eg depth of DT model or number of non zero weight in Linear model)</li><li>g(x_dash) != g(x) because x_dash is interpretable representation and x is original feature vector.</li></ul><p><strong>2. Proximity Function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0yrmuZfdyBL9Q5ljeo1qQ.png" /></figure><p><strong>3. Local Fidelity and Interpretability</strong></p><ul><li>Our goal is to make g() model be very same as f() in the region π_x because g() is interpretable. g() is interpretable because we have converted x into x_dash and because of x_dash now we can interpret our model.</li></ul><p><strong>COOOOOOL!!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*w2aK3MaBcaKHPEgf29AKXA.png" /></figure><h3>Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*iYMpSNu02cf3OgUQrIE5oQ.png" /></figure><ul><li>π_x(z) is equal to the exponential kernel because it will help us to look at the local region. Local region area depends on <a href="https://en.wiktionary.org/wiki/%CF%83">σ</a>². <strong>As </strong><a href="https://en.wiktionary.org/wiki/%CF%83"><strong>σ</strong></a>²<strong> increase kernel will take more points like KNN.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*PKHqJds_rieU8_fTghXHWw.png" /></figure><ul><li>Capital Z is set or local region area and small z and small z_dash should lie in set i.e. capital Z.</li><li>We are doing the same thing as we do in regression optimization i.e. is square loss. π_x(z) is giving more weightage to that point which is closer to line or plane.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*EksY9W97gukmZrdTlVgLAQ.png" /></figure><ul><li><strong>Ω(g) </strong>is taken as a K lasso so that we can reduce the complexity of the linear model because in a linear model the complexity is dependent on non-zero weights so if we use L1 reg. then L1 reg. will make our non-important feature weight to be zero.</li></ul><p><strong>POWER of L1 reg!!</strong></p><p><strong>Advantage:</strong></p><ul><li>Work with Image, Text and Tabular data.</li><li>Lasso or low depth tree for G is highly interpretable.</li></ul><p><strong>Disadvantage:</strong></p><ul><li>Kernal width(<a href="https://en.wiktionary.org/wiki/%CF%83">σ</a>) — What is the right value?</li><li>‘x_dash’ may not be straightforward to convert into an interpretable vector.</li><li>Lack of robustness.</li></ul><p><strong>NOTE — LIME CODE is 4–6 lines. Read this </strong><a href="https://lime-ml.readthedocs.io/en/latest/"><strong>documentation</strong></a><strong>.</strong></p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>import lime<br>from lime import lime_tabular</pre><pre>##Loading Data<br>data = pd.read_csv(&#39;wine.csv&#39;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-IFMJ-HXU9X8eqqanbqOw.png" /></figure><pre>##Data spliting<br>X = data.drop(&#39;Wine&#39;, axis=1)<br>y = data[&#39;Wine&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><pre>##Model <br>rf_model = RandomForestClassifier()<br>rf_model.fit(X_train, y_train)<br>score = rf_model.score(X_test, y_test)</pre><pre>##LIME<br>explainer = lime_tabular.LimeTabularExplainer(training_data=np.array(X_train),<br>                        feature_names=X_train.columns,<br>                        class_names=[1,2,3],mode=&#39;classification&#39;)</pre><pre>exp = explainer.explain_instance(data_row=X_test.iloc[3],<br>                                predict_fn=rf_model.predict_proba)</pre><pre>exp.show_in_notebook(show_table=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug27Ax3CtWw-U__W_CQmhQ.png" /></figure><p><strong>Observation </strong>— It is saying class = 1 because the Proline level is greater than 932.75, colour int is between 4.6 and 6.12, Alcohol is greater than 13.68.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*6TchIbHErEJlpwSK.gif" /></figure><blockquote><strong><em>References</em></strong></blockquote><ol><li><a href="https://www.youtube.com/watch?v=d6j6bofhj2M">https://www.youtube.com/watch?v=d6j6bofhj2M</a></li><li><a href="https://www.youtube.com/results?search_query=lime+code">https://www.youtube.com/results?search_query=lime+code</a></li><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com</a></li><li><a href="https://arxiv.org/pdf/1602.04938.pdf">https://arxiv.org/pdf/1602.04938.pdf</a></li><li><a href="https://lime-ml.readthedocs.io/en/latest/">https://lime-ml.readthedocs.io/en/latest/</a></li><li><a href="https://towardsdatascience.com/lime-how-to-interpret-machine-learning-models-with-python-94b0e7e4432e">https://towardsdatascience.com/lime-how-to-interpret-machine-learning-models-with-python-94b0e7e4432e</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f743903678b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where and what type of defect is present in steel]]></title>
            <link>https://7799sujit.medium.com/where-and-what-type-of-defect-is-present-in-steel-5e96da7e480?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e96da7e480</guid>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 14:28:54 GMT</pubDate>
            <atom:updated>2020-12-29T16:57:52.126Z</atom:updated>
            <content:encoded><![CDATA[<h3>Severstal Steel defect detection</h3><h4>Can you detect and classify defects in steel?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*fH9EK_nY_LmNqxu_ncLtjw.png" /></figure><p>LinkedIn <a href="http://www.linkedin.com/in/sujit-kumar-29a11b1a6">profile</a> and GitHub <a href="https://github.com/sujitpso77/Severstal-Steel-Defect-Detection-">profile</a></p><p>Before going deep. See this <strong>Deployment Video of this Project </strong>on YouTube<strong>. </strong>It will increase <strong>curiosity </strong>to know internal of this Case-Study.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6xcJ1a-d5mk%3Fstart%3D19%26feature%3Doembed%26start%3D19&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6xcJ1a-d5mk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6xcJ1a-d5mk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/da599cf5103fe203d08a1ab6f0be9aec/href">https://medium.com/media/da599cf5103fe203d08a1ab6f0be9aec/href</a></iframe><h3>Content</h3><ol><li>Business Problem</li><li>Problem Statement</li><li>Prerequisites</li><li>Performance Metrics</li><li>Business Constraints</li><li>About Data</li><li>Data Collection</li><li>Objective</li><li>Strategic plan to find a defect and segment</li><li>Data Loading</li><li>Let’s find some pattern in the data</li><li>Binary Classification</li><li>Multi-Label Classification</li><li>Segmentation</li><li>Approach to the predict queries</li><li>Future Scope</li></ol><h3>1. Business Problem</h3><p>Steel is one of the most important building materials of modern times. Steel buildings are resistant to natural and man-made wear which has made the material ubiquitous around the world. To help make a production of steel more efficient, this competition will help identify defects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gLkE7_e0XmJUWe3S.JPG" /><figcaption>fig 1</figcaption></figure><p><a href="https://www.severstal.com/eng/"><strong>Severstal</strong></a><strong> </strong>is leading the charge of inefficient steel mining and production. They believe the future of metallurgy requires development across the economic, ecological, and social aspects of the industry — and they take corporate responsibility seriously. The company recently created the country’s largest industrial data lake, with petabytes of data that were previously discarded. Severstal is now looking to machine learning to improve automation, increase efficiency, and maintain high quality in their production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*Pr2gX_5JwIq_doLZXpE2Ng.png" /><figcaption>fig 2</figcaption></figure><p>.</p><p>The production process of flat sheet steel is especially delicate. From heating and rolling, to drying and cutting, several machines touch flat steel by the time it’s ready to ship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*Og7HAvRnm3P5d_jn.png" /><figcaption>fig 3</figcaption></figure><p>.</p><p>.</p><p>Today, Severstal uses images from high-frequency cameras to power a defect detection algorithm.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><h3>2. Problem Statement</h3><p>The objective is to predict the location and type of defects present in steel using the images provided.</p><p>Ie this, 1st by the help of roller, steel sheet will move forward and simultaneously high-frequency cameras will take a photo. Then those images will be sent to the system and system will check if there is any defect or not. If the system finds any major defect then it will alert. as shown in fig 3.</p><h3>3. Prerequisites</h3><p>This post assumes familiarity with basic Deep Learning concepts like Multi-layered Perceptrons, Convolution Neural Networks, Segmentation, Transfer Learning, Optimisation, Backpropagation, Overfitting, Probability, Python syntax and Keras library, etc.</p><h3>4. Performance metrics</h3><ol><li>F1 score</li><li>Dice_coef</li></ol><p><strong><em>Short Note on Dice Metric</em></strong></p><p>The Dice coefficient can be used to compare the pixel-wise agreement between a predicted segmentation and its corresponding ground truth. The formula is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*BUY1znOTQef-HDopm1rr8w.png" /></figure><p>where X is the predicted set of pixels and Y is the ground truth. The Dice coefficient is defined to be 1 when both X and Y are empty.</p><h3>5. Business Constraints</h3><p>There is no such constraint mention in this competition but in the real world, it is important to detect whether steel has a defect or not and if it has a defect then which type of defect does steel have and where the defect is present. This is important because if Severstal knows all 3 answers then their quality of product will be great because if company know which type of defect steel has then that type of machining can be done to remove the defect and if they also know the region of the defect then we can do machining on that particular region. If we do not remove defect then it will affect the strength of steel and increase the chances of rusting also.</p><p>So when we are making a classification model, at that time we have to keep in mind that <strong>F1 score</strong> should be high and there should be no overfitting.</p><h4>Some type of defect</h4><p>To know in-depth <a href="https://www.ispatguru.com/metallurgical-processes-and-defects-in-steel-products/">here</a></p><p>There are main 4 types of defect.</p><ul><li><strong>Casting defects</strong></li><li><strong>Rolling defects</strong></li><li><strong>Forging defects</strong></li><li><strong>Welding defects</strong></li></ul><p>Subcategories of the defect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*2jyWj_5Xki092t0C1tBx_g.png" /><figcaption>fig 4</figcaption></figure><h3>6. About data</h3><ul><li>Each Image may have <strong><em>no defects</em></strong>, a defect of a <strong><em>single class</em></strong>, or <strong><em>defects of multiple classes </em></strong>(ClassId = [1, 2, 3, 4]).</li><li>For each class image i.e. [1,2,3,4], there will be a segmented image which is encoded.</li><li>Total train images and test images are 12571 and 5506 respectively.</li></ul><h3>7. Data Collection</h3><p>Kaggle provides a ZIP file which contains 2 folders and 2.csv file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*RPwVNDntfHVZhjOQZQleHA.png" /><figcaption>fig 5</figcaption></figure><p>The first folder contains train images and the second folder contain test images.</p><p>1st CSV file contains ImageId and it’s encoded pixel and 2nd CSV file contains formate of submission. Data <a href="https://www.kaggle.com/c/severstal-steel-defect-detection/data"><em>here</em></a><em>.</em></p><h3>8. Objective</h3><p>For any query image, we have to classify the defect and locate the segmentation of the defect. For each image, you must segment the defects if it belongs to each of the class (ClassId = [1, 2, 3, 4]).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*aYHgO0V5PlwuEE_6sU4phw.png" /><figcaption>fig 6</figcaption></figure><p>In this competition, we have to maximise the <strong>Dice coefficient</strong> for segmentation and for classification we have to maximise <strong>F1 score</strong>.</p><p>.</p><p>.</p><p>.</p><p><strong><em>Note- </em></strong><em>Segmented image is present in encoded form. E.g. if an image is in this format ‘aaabbccccddd’ then encode formate will be ‘a3b2c4d3’. We can observe length has decreased in encode formate i.e. 12 to 8, you can see video for more info </em><a href="https://www.youtube.com/watch?v=ssn7gjgljXQ"><em>here</em></a><em>.</em></p><p><strong>Reason of tf.data API</strong></p><p>tf_data improves the performance by prefetching the next batch of data asynchronously so that GPU need not wait for the data. You can also parallelize the process of preprocessing and loading the dataset. Read <a href="https://www.tensorflow.org/guide/data_performance">this</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*_uZQhjQbZP3p2oJQtSYNJw.png" /></figure><p>Tf.data API train model fastly.</p><p><strong>Let’s get started with data……….</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*efQj0cxwkDi2tJBX.gif" /></figure><h3>9. Strategic plan to find defect and segment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91vnDnQaKAJF4ZLlInClIA.png" /><figcaption>fig 7</figcaption></figure><p><strong><em>Let’s execute our plan step by step……..</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*3aVVDBpISM1tbAY5fH5h7g.gif" /></figure><h3>10. Data Loading</h3><p>According to our planning, 1st we will load Dataframe which Kaggle had provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*1Jd20Y1o6O6UoX52skey4w.png" /></figure><p><strong>DataFrame.</strong></p><ul><li>Read ‘<strong><em>train.csv</em>’ </strong>by the help of pandas.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*CrT0q1oju1oL2ppWRF693A.png" /></figure><h3>11. Let’s find some pattern in the data</h3><ol><li><strong>Count plot</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*uUXkIFQqazymp3YNjV1WPA.png" /><figcaption>fig 8</figcaption></figure><ul><li>Data is much balance to classify whether steel has a defect or not</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*SEfiIcm25im-LHTGSadmyA.png" /><figcaption>fig 9</figcaption></figure><ul><li>Data is very unbalanced. In the dataset, 3rd class defect is much more than the others.</li><li>Due to unbalance data we cannot much rely on accuracy metric.</li></ul><p>2. L<strong>et’s check encoded pixel</strong></p><p>Before going further we will make a function to calculate the Sum of encoding of a pixel. (fig)</p><p>eg. if suppose this is encoded pixel <strong><em>‘a3b2c4d3’ than the sum of encoding of the defect pixel will 3+2+4+3=12.</em></strong></p><pre>def sum_enc(i):<br>    return sum([int(k) for k in i.split(&#39; &#39;)[1::2]])</pre><p><strong>a. Sum of encoding class 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*cEEAl0LoIZpft1YL6sEoNg.png" /></figure><p>The distplot plot looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*_0UqtzV87JTJFwuN9WNZHQ.png" /><figcaption>fig10</figcaption></figure><p>Let’s see value from 0 to 100 percentile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*Zr29f5SchIFVT88giwmraw.png" /><figcaption>fig11</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*DqURwPjET6O62ZZmjxBT6A.png" /><figcaption>fig12</figcaption></figure><ul><li>In class 1, the sum of encoding start from 163 i.e. zero percentile.</li><li>We can observe that after 99.5 percentile there is a sudden increase for 2K.</li></ul><p><strong>This how the defect image and its segmentation looks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*2MrkmeUg3PyBOWtTHqUaXw.png" /><figcaption>fig13</figcaption></figure><p><em>Note — These value will help us to make a threshold for doing classification and segmentation. It means if it belongs to class 1 then it’s the sum of the pixel of the defect should lie between [163,17983].</em></p><p><strong>b. Sum of encoding class 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*h8Rv_TwrtnRJHOiZuF6How.png" /><figcaption>fig15</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*7qBuiZwHVXmqk5D60FwQbQ.png" /><figcaption>fig16</figcaption></figure><ul><li>In class 2, the sum of encoding starts from 316 (zero percentile)</li><li>We can observe that after 98 percentile there is a sudden increase for 2k(approx).</li><li>For defect 2 the sum of the pixel of the defect should lie between [316,8163].</li></ul><p><strong>This how the defect image and it’s segmentation looks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*XWdtuPB47BP2NcMLEU6CjA.png" /><figcaption>fig17</figcaption></figure><p><strong>c. Sum of encoding class 3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*OhSGjuF0cYDcwWO7_4sVhw.png" /><figcaption>fig18</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*nOZaxXmT4TVzfqbavXP__w.png" /><figcaption>fig19</figcaption></figure><ul><li>The plot is very skewed. Which means there are only some images whose sum_encoding is greater than 100k.</li><li>In class 3, the sum of encoding starts from 115.</li><li>We can observe that after 98 percentile there is a sudden increase for 3k(approx).</li></ul><p><strong>This how the defect image and it’s segmentation looks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*TBK5HssLh2sjHl-JrJdF6A.png" /><figcaption>fig20</figcaption></figure><p><strong>d. Sum of encoding class 4</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*vTJiaF6xGfMx6HkYX6c_Qw.png" /><figcaption>fig 21</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*6Q6vrrtwtMGyq2yA1gQG9w.png" /><figcaption>fig 22</figcaption></figure><ul><li>The plot is skewed.</li><li>In class 4, the sum of encoding starts from 491.</li><li>We can set a threshold of 128k.</li></ul><p><strong>This how the defect image and it’s segmentation looks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*KqO3_8aJjfGAgAItjrBqGg.png" /><figcaption>fig 23</figcaption></figure><p><em>Note- We will use this sum of the defect pixel as a threshold after segmentation model predicts mask.</em></p><p><strong>Observation</strong></p><p>By visualisation of all the defect image, we had concluded that</p><ol><li>Steel having defect 1 has small pinholes on the steel as shown in (fig4)</li><li>Steel having defect 2 has a little transverse crack on it.</li><li>Steel having defect 3 has a large transverse crack on it.</li><li>Steel having defect 4 has a large patch on it.</li></ol><p>5. No defect steel does not mean that it has no defect. T here is some sort of defect into the steel but that defect is other than 1,2,3, and 4th defect, no defect also contain that some design also and it also contain that steel which does not have any type of defect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*KS48iH3egSgEBGgEq2zWPA.png" /></figure><p><strong><em>Note — defect4&gt;Defect3&gt;Defect2&gt;Defect1</em></strong></p><h3>12. Binary Classification</h3><p>We will follow this flowchart to find whether steel has a defect or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*zlvThPCjuVrqLeIc4vT3CQ.png" /></figure><ul><li><strong>Data preparation for binary classification</strong></li></ul><p>For this, we will take all the images names from ‘train_images’ folder. If filename is present ‘train.csv’ then Image has defect otherwise image does not have a defect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*W8g2spHHq0axWBgYhNkfFw.png" /><figcaption>fig 24</figcaption></figure><ul><li><strong>Splitting the data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_tHJTQnEpTomv_gqPVrPw.png" /></figure><ul><li><strong>Data distribution in train and validation</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*u_ttQa6tJU6gAIPHZEpD0Q.png" /><figcaption>fig 25</figcaption></figure><p>Observation — Data is almost balanced.</p><ul><li><strong>Model Architecture</strong></li></ul><p>In our case study, we have used a pre-trained <strong>Xception</strong> model.</p><p><em>Note we had used Xception model because it had less computation. In this we use Depthwise separable convolution instead of simple convolution and it also a benefits of ResNet. Read </em><a href="https://towardsdatascience.com/a-basic-introduction-to-separable-convolutions-b99ec3102728"><strong><em>this </em></strong></a><em>for Depthwise separable convolution and read </em><a href="https://towardsdatascience.com/review-xception-with-depthwise-separable-convolution-better-than-inception-v3-image-dc967dd42568"><strong><em>this </em></strong></a><em>for Xception structured.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/862e214a03a41242a898f601e97e696b/href">https://medium.com/media/862e214a03a41242a898f601e97e696b/href</a></iframe><p>Save the weight into a disk if f1 test score increase from previous epoch f1 score and also make tensorboard so that we can analysis how loss is changing at every epoch.</p><ul><li><strong>Training Procedure</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*8u_eQOevM_9-y9FokOterA.png" /><figcaption>fig 25</figcaption></figure><ul><li><strong>Plot for F1score and loss</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*qrwESo4OpsmZS7wDpN2BXw.png" /><figcaption>fig 26</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*_sKP9kH-JDFRaDwiUNQX4A.png" /><figcaption>fig 27</figcaption></figure><p>We can observe that at blue F1-score(red curve) is increasing and loss is decreasing. By doing this we get a confirmation that the model is not overfitting on train data.</p><ul><li><strong>Choosing the best threshold</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Lli6HTw6BwADZpHDkPHJpw.png" /><figcaption>fig 28</figcaption></figure><p>We had taken threshold value as 0.4,0.45,0.5,0.55,0.6,0.7 to check which threshold will give max value for F1 score on training data. So the best score I when threshold value was 0.45. Total data in training was 9731 as shown in fig 28.</p><p>Now we check how 0.45 threshold value performs on test data. At 0.45 we get 0.984 f1 score&amp; total data in testing was 1509.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*TTWDKISTgjaGfwRfrfo_bw.png" /><figcaption>fig 29</figcaption></figure><ul><li><strong>Some prediction on testing data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWWFVuMk_Sufm5TXkm0AdQ.png" /><figcaption>fig 30</figcaption></figure><p>We had taken some random sample from the testing dataset and we can see the actual and prediction is the same. Model is working very well on the testing dataset.</p><h3>13. Multi Classification</h3><p>This flowchart to help to find which types of defect steel has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*wzZh8B1BT_HLtqe6aiOrpg.png" /></figure><ul><li><strong>Data preparation for Multi-label classification</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*DnWKN7kDpRomlUbuZKt59A.png" /><figcaption>fig 31</figcaption></figure><p><strong><em>Note</em></strong><em>- In the above figure, ImageLabel is just helping to do stratified sampling while splitting into train, test and validation.</em></p><p>While splitting data into train/test/ validation we must do a stratified sampling so that class distribution should same in train, test and validation.</p><ul><li><strong>Data distribution in train and validation</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*t6v7aKGVzCavh8qihVccCg.png" /><figcaption>fig 32</figcaption></figure><p>By looking train and validation class distribution we can see there is a class imbalance. Type 3 images contain very much as compare to other classes.</p><ul><li><strong>Model Architecture</strong></li></ul><p>In this also have taken a pre-trained model i.e. Xception.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa24e70a525c5a32b0c60d131e9485fc/href">https://medium.com/media/aa24e70a525c5a32b0c60d131e9485fc/href</a></iframe><p><em>Note- We had used sigmoid as an activation function for the last layer so that we can get the probability for each defect individually and for multi-label classification, we need individual probability for each class because one image can have more than one class. Eg. [0.001,0.005,0.98,0.93]</em></p><p>Save the weight into a disk if f1 score increase from previous epoch and also make tensorboard to analysis how loss is changing at every epoch.</p><p><strong>d. Plot for F1score and loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*yOh414qG0FnVYmQmsFFPAQ.png" /><figcaption>fig 33</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*3yki1nWX9SFNw7e1yp_NNg.png" /><figcaption>fig 34</figcaption></figure><p>When all training gets completed we have checked our model by test image and even on train and validation image and F1 score.</p><ul><li><strong>Choosing the best threshold</strong></li></ul><p>We had taken threshold value as 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.75, 0.8, 0.85, 0.9 to check which threshold will give max value for F1 score on training data. So the best score I when threshold value for Class 1, Class 2, Class 3, Class 4 was [0.8, 0.5, 0.65, 0.35] . Total data in training was 4759.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*3BUy1kWEwtOcc_-iRdcBLQ.png" /><figcaption>fig 35</figcaption></figure><p>Now we check how [0.8, 0.5, 0.65, 0.35] threshold value performs on test data. Total data in testing was 1000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*TeO2e2p6STxsQktmTOsuxQ.png" /><figcaption>fig 36</figcaption></figure><ul><li><strong>Some prediction on testing data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHlEqabCxyjqLl4mf3FMrg.png" /><figcaption>fig 37</figcaption></figure><h3><strong>14. Segmentation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*I8LClVn4a1HbGQ00ZRkuHg.png" /><figcaption>fig 38</figcaption></figure><p>This is how multi-label segmentation looks like. In this, we can see how one image has multiple masks i.e. class 0,1,2,3, 4 and 5. Similarly, in our case, steel can contain either 1,2,3 or all 4 defects. So we will also do multi-label segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*5zcGf75nm2RQ56-26xg2ww.gif" /></figure><p>.</p><p><strong><em>We know the type of defect but how the system knows where the defect is present on steel. For this, we will discuss below.</em></strong></p><p>.</p><p>.</p><p>This flow chart will help us to find where the defect is present in the steel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*Ldq2qkYNqWerlcEa7kqfGg.png" /></figure><h3>a. Model for Defect 1</h3><ul><li><strong>Making Dataframe</strong></li></ul><p>In DataFrame there will be only two columns, 1st will Image_Id and 2nd will be EncodedPixels for class 1.</p><pre>seg_type_1_data=df[df.ClassId==1]</pre><pre>seg_type_1_data[&#39;ImageId&#39;]=[&#39;train_images/&#39;+i for i in seg_type_1_data.ImageId]</pre><ul><li><strong>Metrics and loss</strong></li></ul><p><strong>a. Dice Coefficient</strong></p><p>Dice coefficient, which is essentially a measure of overlap between two samples. This measure ranges from 0 to 1 where a Dice coefficient of 1 denotes perfect and complete overlap. Check this video <a href="https://www.youtube.com/watch?v=AZr64OxshLo"><em>here</em></a></p><p>Dice coefficient is roughly equal to the harmonic mean of precision and recall. Dice coeff = F1 score. Read <a href="https://en.wikipedia.org/wiki/F1_score">this</a></p><p><strong>b. Dice Loss</strong></p><p>Dice loss = 1- dice coefficient.</p><p>Read to know loss <a href="https://arxiv.org/abs/2006.14822">this</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*prML99aiCFQugoTm.png" /><figcaption>fig 39</figcaption></figure><ul><li><strong>Model Architecture</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9zLYfPX-hEJTYt6p.png" /><figcaption>fig 40</figcaption></figure><p>In this case study, we have used Unet with pre-trained EfficientnetB0 encoder architecture.</p><p><em>Note — We had use Efficientnet because it reduce the number computation in model because it do efficient scaling between depth, channel and resolution. Read </em><a href="https://ai.googleblog.com/2019/05/efficientnet-improving-accuracy-and.html"><strong><em>this</em></strong></a><strong><em> </em></strong><em>and see </em><a href="https://www.youtube.com/watch?v=fC39F8AqPo0"><strong><em>this </em></strong></a><em>video</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8fbe1c8cbe9005ea084a5c06937745/href">https://medium.com/media/1f8fbe1c8cbe9005ea084a5c06937745/href</a></iframe><ul><li>Training procedure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*kcBq5_3pFjWU2SY9ZO_6mQ.png" /><figcaption>fig 41</figcaption></figure><ul><li><strong>Plot for Dice and loss</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*myS2rI6JE5TtJi3qpOOomQ.png" /><figcaption>fig 42</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*Mt980EpgX-KGGJPEn-FjZA.png" /><figcaption>fig 43</figcaption></figure><p>We can see the dice coefficient is increasing and loss is decreasing at every epoch.</p><ul><li><strong>Some prediction on testing data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*sOyvsM76EirsII5qChuVeg.png" /><figcaption>fig 44</figcaption></figure><p><em>Note- Model output will be a Mask we have to convert into RLE</em></p><h3>b. Model for Defect 2</h3><ul><li><strong>Making DataFrame</strong></li></ul><p>In DataFrame there will be only two columns, 1st will Image_Id and 2nd will be EncodedPixels for class 2</p><pre>seg_type_2_data=df[df.ClassId==2]</pre><pre>seg_type_2_data[&#39;ImageId&#39;]=[&#39;train_images/&#39;+i for i in seg_type_2_data.ImageId]</pre><ul><li><strong>Model</strong></li></ul><p>we have used the same Unet with pre-trained EfficientnetB0 encoder architecture.</p><ul><li><strong>Plot for Dice and loss</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*qCQMR2UF4CYniP4K6ExwPA.png" /><figcaption>fig 45</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*9ZLOOmhx4qAl1uGnwK5YZw.png" /><figcaption>fig 46</figcaption></figure><p>We can see the dice coefficient is increasing and loss is decreasing at every epoch.</p><ul><li><strong>Some prediction on testing data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*_w4lGT1IXf3zWo7H-e3j8A.png" /><figcaption>fig 47</figcaption></figure><p><em>Note- Model output will be a Mask we have to convert into RLE</em></p><h3>c. Model for Defect 3</h3><ul><li><strong>Making DataFrame</strong></li></ul><p>In DataFrame there will be only two columns, 1st will Image_Id and 2nd will be EncodedPixels for class 3.</p><pre>seg_type_3_data=df[df.ClassId==3]</pre><pre>seg_type_3_data[&#39;ImageId&#39;]=[&#39;train_images/&#39;+i for i in seg_type_3_data.ImageId]</pre><ul><li><strong>Model</strong></li></ul><p>we have used the same Unet with pre-trained EfficientnetB0 encoder architecture.</p><ul><li><strong>Plot for Dice and loss</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*to_JtwLnqVMEg7Ju2jOkDQ.png" /><figcaption>fig 48</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*WkVUnJDtZ6IG2n5RRAXqqw.png" /><figcaption>fig 49</figcaption></figure><p>We can see the dice coefficient is increasing and loss is decreasing.</p><ul><li><strong>Some prediction on testing data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*0FoAL4fRzpAeslcQgFKIfQ.png" /><figcaption>fig 50</figcaption></figure><p><em>Note- Model output will be a Mask we have to convert into RLE</em></p><h3>d. Model for Defect 4</h3><ul><li><strong>Making DataFrame</strong></li></ul><p>In DataFrame there will be only two columns, 1st will Image_Id and 2nd will be EncodedPixels for class 4.</p><pre>seg_type_4_data=df[df.ClassId==4]</pre><pre>seg_type_4_data[&#39;ImageId&#39;]=[&#39;train_images/&#39;+i for i in seg_type_4_data.ImageId]</pre><ul><li><strong>Model</strong></li></ul><p>we have used the same Unet with pre-trained EfficientnetB0 encoder architecture.</p><ul><li><strong>Plot for Dice and loss</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*KJRw6DpBMHUpZcXo5KXhnw.png" /><figcaption>fig 51</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*hJyW3arjhcOUJpB-oYL3iQ.png" /><figcaption>fig 52</figcaption></figure><p>We can see the dice coefficient is increasing and loss is decreasing at every epoch.</p><ul><li><strong>Some prediction on testing data</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*sr4AUyEtiVM9z1AFcLhZIA.png" /><figcaption>fig 53</figcaption></figure><p><em>Note- Model output will be a Mask we have to convert into RLE</em></p><h3>Oh yeah!! All models are ready…….</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*wdCzdjz_0j-Qq3TduTyGcQ.gif" /></figure><h3>15. Time to put the model in this sequence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iALY9csdPHhSc_kARJyNvA.png" /><figcaption>fig 54</figcaption></figure><ol><li>Take a query steel image of any shape (a,b,3)</li><li>Give a query image will convert (a,b,3) into (1,299,299,3) size. Then this image will pass to the binary model.</li></ol><p>The binary model will give a probability value as an output e.g. [[0.98]]. Then will check if prob. value is greater than 0.45. If it’s greater than then steel has a defect(label=1) otherwise no defect(label=0).</p><p>3. If the steel has a defect then that image of size(1,299,299,3) will pass into a multi-label model.</p><p>The multi-label model will give a 4 probability value as an output e.g. [[0.99,0.88,0.001,0.002]]. This probability will signify that 99% chance is that it belongs to class 1 defect, 88% chance is it has class 2 defect also, 0.1% chance is it has class 3 defect also, 0.2% chance is it has class 4 defect also.</p><p>4. Let a=[[0.99,0.88,0.001,0.002]]</p><p>Now,</p><pre>if a[0][0]&gt;=0.8:<br>       pass same image of size (1,256,800,1) to segmentation model which detect type 1 defect. Output of this model will be (256,1600,1). Convert image size into (256,1600).</pre><pre>if a[0][1]&gt;=0.5:<br>       pass same image of size (1,256,800,1) to segmentation model which detect type 2 defect. Output of this model will be (256,1600,1). Convert image size into (256,1600).</pre><pre>if a[0][2]&gt;=0.65:<br>       pass same image of size (1,256,800,1) to segmentation model which detect type 3 defect. Output of this model will be (256,1600,1). Convert image size into (256,1600).</pre><pre>if a[0][3]&gt;=0.35:<br>       pass same image of size (1,256,800,1) to segmentation model which detect type 4 defect. Output of this model will be (256,1600,1). Convert image size into (256,1600).</pre><p>Finally, concatenate all the 4 masks and we will get the output of shape (256,1600,4)</p><ul><li><strong>Code</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a8a1b008e45300ad73e323b8cfa1dbf/href">https://medium.com/media/1a8a1b008e45300ad73e323b8cfa1dbf/href</a></iframe><p>LinkedIn <a href="http://www.linkedin.com/in/sujit-kumar-29a11b1a6">profile</a> and GitHub <a href="https://github.com/sujitpso77/Severstal-Steel-Defect-Detection-">profile</a></p><ul><li><strong>Prediction of new data results</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N53oFK89ScJM0FCbUInpFg.png" /></figure><blockquote>Deployment <strong>Video using StreamLit of this Project on YouTube</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6xcJ1a-d5mk%3Fstart%3D19%26feature%3Doembed%26start%3D19&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6xcJ1a-d5mk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6xcJ1a-d5mk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/da599cf5103fe203d08a1ab6f0be9aec/href">https://medium.com/media/da599cf5103fe203d08a1ab6f0be9aec/href</a></iframe><h3>16. Future Scope</h3><ul><li>We can use a different pipeline, which may perform better than this Faster RCNN</li><li>We can try another pipeline which is better than this.</li><li>We can try some other loss also like a focal loss.</li><li>Try a different threshold.</li><li>Increase the batch size if you have good computation resources.</li><li>Use some more augmentation also.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*5lSINV_G915AAPvH.gif" /></figure><blockquote><strong><em>References</em></strong></blockquote><ol><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com</a></li><li><a href="https://www.kaggle.com/ekhtiar/defect-area-segments-eda-with-plotly-fp-mining">https://www.kaggle.com/ekhtiar/defect-area-segments-eda-with-plotly-fp-mining</a></li><li><a href="https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode">https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode</a></li><li><a href="https://arxiv.org/abs/2006.14822">https://arxiv.org/abs/2006.14822</a></li><li><a href="https://udibhaskar.github.io/practical-ml/debugging%20nn/neural%20network/overfit/underfit/2020/02/03/Effective_Training_and_Debugging_of_a_Neural_Networks.html">https://udibhaskar.github.io/practical-ml/debugging%20nn/neural%20network/overfit/underfit/2020/02/03/Effective_Training_and_Debugging_of_a_Neural_Networks.html</a></li><li><a href="https://www.tensorflow.org/guide/data">https://www.tensorflow.org/guide/data</a></li><li><a href="https://stackoverflow.com/questions/58693261/create-a-rle-run-lenth-encoding-mask-with-tensorflow-datasets">https://stackoverflow.com/questions/58693261/create-a-rle-run-lenth-encoding-mask-with-tensorflow-datasets</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e96da7e480" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mercedes-Benz Greener Manufacturing]]></title>
            <link>https://7799sujit.medium.com/mercedes-benz-greener-manufacturing-419c4eefe2f8?source=rss-9a1fde120311------2</link>
            <guid isPermaLink="false">https://medium.com/p/419c4eefe2f8</guid>
            <dc:creator><![CDATA[SUJIT]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 18:01:06 GMT</pubDate>
            <atom:updated>2020-11-03T06:26:07.000Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mercedes-Benz Car Testing Time</strong></h3><blockquote>Speedier testing will contribute towards lowering emissions and a more efficient manufacturing line</blockquote><p>GitHub <a href="https://github.com/sujitpso77/Mercedes-Benz-Greener-Manufacturing-">link </a>of the project. LinkedIn <a href="http://www.linkedin.com/in/sujit-kumar-29a11b1a6">profile</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Wwh2bKjHnynN5OEw0Mmg5g.png" /></figure><h3>Content</h3><ol><li>Business Problem</li><li>Problem Statement</li><li>Prerequisites</li><li>Performance Metrics</li><li>Business Constraints</li><li>About Data</li><li>Data Collection</li><li>Data Loading</li><li>Let’s find some pattern in the data</li><li>Preprocessing — X0 feature(Clustering)</li><li>Train the model</li><li>Important features</li><li>Model implementation</li><li>Final Prediction Function</li><li>My final approach summary</li><li>Thing’s that didn’t work for me</li><li>Conclusion</li><li>Future work</li></ol><h3>1. Business Problem</h3><p>The first automobile, the Benz Patent Motor Car in 1886, Mercedes-Benz has stood for important automotive innovations. These include, for example, the passenger safety cell with crumple zone, the airbag and intelligent assistance systems. Mercedes-Benz applies for nearly 2000 patents per year, making the brand the European leader among premium carmakers. Daimler’s Mercedes-Benz cars are leaders in the premium car industry. With a huge selection of features and options, customers can choose the customized Mercedes-Benz of their dreams.</p><p>To ensure the safety and reliability of each and every unique car configuration before they hit the road, Daimler’s engineers have developed a robust testing system. But, optimizing the speed of their testing system for so many possible feature combinations is complex and time-consuming without a powerful algorithmic approach. As one of the world’s biggest manufacturers of premium cars, safety and efficiency are paramount on Daimler’s production lines.</p><h4>Other aspect of this case study will be also this</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*epxFUDJ1auHMLvCu" /></figure><p>If a car takes more time on testing then it will affect the price of the car because Daimler’s is spending their electricity, man-power, warehouse cost and other material. So more the test time more will be the cost of the car.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*MPrBh_OLHz2jHHrz.jpg" /></figure><p>The more time car spend during testing, the more CO2 will produce. If we compare CO2 emission of the whole world w.r.t Daimler’s testing machine then Daimler’s contribution of CO2 is less. If whole testing industries will adapt this then it will somehow decrease the CO2 emission on large scale.</p><p>The objective of the Mercedes-Benz Greener Manufacturing competition is to develop a machine learning model that can accurately predict the time a car will spend on the test bench based on the vehicle configuration. The vehicle configuration is defined as the set of customization options and features selected for the particular vehicle. The motivation behind the problem is that an accurate model will be able to reduce the total time spent testing vehicles by allowing cars with similar testing configurations to be run successively.</p><h3>2. Problem Statement</h3><ul><li>The motivation behind the problem is that an accurate model will be able to reduce the total time spent testing vehicles by allowing cars with similar testing configurations to be run successively.</li><li>In this problem, we have to predict a continuous value(time in sec) for a given query (Regression type problem). Continuous value is how much time a car needs to pass the testing.</li></ul><h3>3. Prerequisites</h3><p>This post assumes familiarity with basic Machine learning concepts like Regression algorithm, Clustering algorithm ,Optimisation, Probability, Python syntax and pandas, numpy, seaborn and matplotlib library, etc.</p><h3>4. Performance metrics</h3><ul><li>R² (Coefficient of determination)</li></ul><h3>5. Business Constraints</h3><p>Company has no given constraint related to testing time prediction but still predicting queries should not take much seconds.</p><p><em>If it takes 1 to 2 sec to predict single test data then the model will be a waste because if we have more data to predict then company are wasting there time just getting a result. For eg. total input data has 100k points and model takes 2 sec to predict each quries then total time model will take to predict will be 26+hr. This time will be much much longer for manufacturing companies.</em></p><h3>6. About data</h3><ul><li>The dataset contains an anonymized set of variables, each representing a custom feature in a Mercedes car. For example, a variable could be 4WD, added air suspension, or a head-up display.</li><li>There is 8 categorical feature, 1 ID feature, 368 are binary feature and y column which is time in sec.</li></ul><h3>7. Data Collection</h3><p>Kaggle provides a ZIP file which contains Train.csv, Test.csv and Submission.csv. <a href="https://www.kaggle.com/c/mercedes-benz-greener-manufacturing/data">Data</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*qckoDIgIApASgciF.gif" /></figure><h3><strong>8. Loading data</strong></h3><pre>train_data=pd.read_csv(&#39;train.csv&#39;)<br>print(&#39;Train data shape : &#39;,train_data.shape)<br>train_data.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRkayqC8mWxUi-09OLf95g.png" /><figcaption>fig 1</figcaption></figure><ol><li>8 categorical data</li><li>370 binary data</li><li>1 ID feature</li><li>Target value</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*PtJze4o2IxCgWn2Y.gif" /></figure><p><em>By looking data we cannot judge anything because it contained an only a binary number and some categorical value without any labels.</em></p><h3>9. Let’s find some pattern in the data</h3><h4><strong>a. Analysis of target variable y</strong></h4><ul><li><strong>Histogram</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*pGRC86FNPKSLpFgH29EOsg.png" /><figcaption>fig 2</figcaption></figure><ol><li>Maximum number of y lies between 80 to 120</li><li>Plot is skewed</li></ol><ul><li><strong>Scatter plot</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*fDvIdeSNf-IXXgBeoOl8Jg.png" /><figcaption>fig 4</figcaption></figure><p>1. We can notice in boxplot and scatter plot that there is one point which is very far away. This point must be an outlier.</p><ul><li><strong>CDF</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*rlU3Eh_gj4cm1HPcAH-BSA.png" /><figcaption>fig 5</figcaption></figure><ol><li>We can consider that y&gt;150 to be an outlier.</li></ol><p>2. Almost 99.83368% of data cover before 150.</p><p><em>Remove all the ‘y’ which is greater than 150</em></p><h4><strong>b. </strong>Analysis of <strong>categorical feature</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*PgItGK4VwI0wm3GF4FpcOA.png" /><figcaption>fig 6</figcaption></figure><p><em>I checked the official website of Daimler’s so that I can understand, what</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyKfVDLnF4YLX5b3tanCGg.png" /></figure><p><em>the categorical value represents but it was not much use full for me. I only get to knows that Mercedes gives multiple options to there customer such as the selection of wheel, Trim, Wireless charging, Online navigation system, ventilation, brake system, airbag etc.</em></p><p>.</p><p>.</p><h4>Let’s make a strip plot for categorical feature one by one</h4><ul><li><strong>X0 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*WesCOOYs1_lru6NDB4qHlw.png" /><figcaption>fig 7</figcaption></figure><ul><li>This feature is well spread. It means that all unique item’s lies in some specific range. e.g. all ‘a’ have time greater than 110, similarly ‘aa’ have time greater than 135, similarly ‘az’ time lie below 110. By this information, we can guess or predict approx time easily. E.g. if my query point has ‘a’ then I don’t know the exact value but I know that will be more than 110 sec.</li></ul><p>We can put each unique item’s into sets by looking at all unique item’s median.</p><p>You can think in this way that all the item’s whose median come above the red line will get one set, all the item’s which comes between green and red will get the same set and all the item’s which comes below green will get the same set as shown in fig 7.</p><p>For finalizing threshold we had use different different threshold values which can maximize correlation between target variable and independent variable. So finally we got this as show in below code.</p><p>Make a new feature</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b62a2609d82b179e4204d86f631156f/href">https://medium.com/media/2b62a2609d82b179e4204d86f631156f/href</a></iframe><ul><li><strong>X2 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*hmjNgAQaItqP8fKVkDDqQA.png" /><figcaption>fig 8</figcaption></figure><p>Item’s ‘ak’, ’as’, ‘ae’ is the unique value which does not have a specific range of time and ‘ak’,’as’,’ae’ cover 69% of total X2 feature as shown in fig 8.</p><p>we can also make set’s as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*HMuzh6PW7lPpdPydUtJJ0w.png" /><figcaption>fig 9</figcaption></figure><ul><li><strong>X3 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*DEG17lwejAfg_B3tw4XMtQ.png" /><figcaption>fig 10</figcaption></figure><ul><li><strong>X5 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*EwzN9yZuqF735Zl2iu85NQ.png" /><figcaption>fig 11</figcaption></figure><ul><li><strong>X6 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*WuiPxAAxlBzgG2GwgXVnHQ.png" /><figcaption>fig 12</figcaption></figure><ul><li><strong>X8 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*R41pu_Ov19vYsh0cf4qpHw.png" /><figcaption>fig 13</figcaption></figure><ul><li><strong>X1 feature</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*qjGzbXoG2gmnYwjM_r1d6A.png" /><figcaption>fig 14</figcaption></figure><p>1. The feature X3, X1, X5, X6, X8, X4 can not be converted into a different set because the unique value does not lie into a specific range. It means there is no set pattern. For eg in plot X1: ‘b’ value can lies from 83 to 140+ similarly ‘c’ value can lies from 86 to 138 that’s why we cannot put an item’s into sets according to there median.</p><p>2. The feature X3, X1, X5, X6, X8, X4 are less informative as compare to X0.</p><h4>Label encoding of categorical feature</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b60da463cb656d59efa197600180ab2/href">https://medium.com/media/1b60da463cb656d59efa197600180ab2/href</a></iframe><ul><li><strong>Checking correlation</strong></li></ul><p>Model based approach</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*_Dm-1gP0pRQHudg3NJRtRQ.png" /></figure><p>In this we took linear regression model and than fitting all feature one by one. After fitting we check what is the ‘mean square error’ we got for all individual feature. By looking above plot we observed that X0_n is much correlated with target variable because it has low MSE value as compare to other feature.</p><p>Correlation order is like this</p><p>X0_n&gt;X0_n&gt;X0&gt;X3&gt;X2&gt;X5&gt;X4&gt;X1&gt;X6&gt;X8</p><h4>c. Analysis of Binary feature</h4><p>Total no. of binary feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*MlYRJoyk-YL27TdewpBTvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*zCI9CgB2cKIP80EWMhe1kw.png" /><figcaption>fig 16 where blue=0 and orange=1</figcaption></figure><p>There are 13 features which have all-zero value. Which means no customer has used those products for there car. So we can remove all zero feature because it do not contain any information.</p><ul><li>The features which contain only zero’s.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*ELtXbwPfVyV7OlxmRFWfHQ.png" /></figure><p><em>Remove all the Zero’s column which exists in training data.</em></p><h4>d. Analysis of ID feature</h4><p>Plot b/w ID and y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*5d6M_g4wzRa6WEgsUb__Qw.png" /><figcaption>fig 17</figcaption></figure><p>The linear fitting line(dark blue line) is going down as ID value increase, Which means as ID increase than time taken by a car is also reducing(slightly).</p><p><strong>Other way to look this</strong></p><p>We know we can use avg. method to smooth the zig-zag curve. So if we smooth plot b/w target variable and ID it will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*hBvLy3lrhQLU6WJkIBfajw.png" /></figure><p>By looking this plot we can get better intuition that as my ID is increasing there is slight decrease in time.</p><p>So by observing this we can make a new column in which we will give less weightage to the new id. Which means ID 1st will get more weightage in compare to 10th ID.</p><p>One way of doing this (1/x) where x will be the ID number.</p><p><em>I had taken log just because when ID will increase then my (1/x) decrease significantly. Just because of this there will a chance of rounding the value and when this thing happens then my current value and next value might become similar.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a64a5f5825b456eebd2f912fb886cb8/href">https://medium.com/media/1a64a5f5825b456eebd2f912fb886cb8/href</a></iframe><h3>10. Preprocessing — X0 feature</h3><p>We can also try to make a cluster of X0 by following steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*BjUgnhcoJF6HKs7NodtUgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*sfzKBsCP-yx2ffrRGMy5AA.png" /><figcaption>fig 18</figcaption></figure><p>code</p><ul><li>for training data</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f83396ff3899774a408029db39d2b3f/href">https://medium.com/media/5f83396ff3899774a408029db39d2b3f/href</a></iframe><p>Finding best k</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*jQcqzwaUHhXqPpQhyBD6gQ.png" /></figure><p>We can see best k=4</p><ul><li>for testing data</li></ul><pre>dc=clust(train_data)<br>data_te[&#39;X0_clus&#39;]=test[&#39;X0&#39;].map(dc.groupby(&#39;X&#39;)[&#39;label&#39;].median())</pre><p>After making cluster we will see Percentage distribution of data in each cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*iDdx3UYHque3_xWXoC9-NQ.png" /></figure><p>We can see maximum number point belongs to cluster 0 with 49.7%.</p><h3>11. Train the model</h3><p>Train the model by all the pre-processed data(whatever we have done above).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4004df7f825ec2cda5029edd0b1467ce/href">https://medium.com/media/4004df7f825ec2cda5029edd0b1467ce/href</a></iframe><h3>12. Important features</h3><p>Let see both model important features in order.</p><ul><li>XG boost feature importance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WDPDUSIH-dCWrDk8heHgAA.png" /><figcaption>fig 19</figcaption></figure><ul><li>Random Forest feature importance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*ngkm3K3WUr_kVp8P2E13eA.png" /><figcaption>fig 20</figcaption></figure><h4>Now let’s do some Feature Engineering using the interaction variable:</h4><p>we can make a new feature by doing this [‘X314_plus_X315’], [‘X118_plus_X314_plus_X315’].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4820130532d8e289cbb36bd8c4a7d556/href">https://medium.com/media/4820130532d8e289cbb36bd8c4a7d556/href</a></iframe><h3>13. Model Implementation</h3><blockquote><strong>Note:</strong> There are certain hyper-parameter in this code that can be fine tuned according to ones requirements. I have tuned them to find a sweet spot between speed and accuracy.</blockquote><p>We had made 4 models</p><ol><li>Simple Linear Regression</li><li>Ridge Regression</li><li>Decision Tree</li><li>XG Boost</li></ol><p><strong>Simple Linear Regression</strong></p><p><strong><em>Note</em></strong><em>- We have not use all the feature in Linear regression because linear regression has an assumption that there should be some relationship between target variable and independent variable. So to do this we had first most correlation independent feature by using linear regression model. If my independent variable fit more on training data and increase the metrics value then we can conclude that there is some relationship between independent variable and dependent variable.</em></p><ul><li>Before making model we find the combination of features which help to fits more on training data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*89r63Buxf0A3Cm1qNEvuEw.png" /></figure><p>We can see there are 7 which help to gives max metrics value. So we will take these feature to make our linear regression model.</p><p>Result of linear regression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*g61D-Rp3s3MPY-u2ZDYAbA.png" /></figure><p><strong>Ridge Regression</strong></p><ul><li>Before making model we find the combination of features which help to fits more on training data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*xm4dcWeToRx-uXryFo4cQw.png" /></figure><p>We can see there are 18 which help to gives max metrics value.</p><ul><li>After this we had done a grid search cv to find best alpha parameter. And after fitting we got best alpha = 6. So we will take these feature to make our Ridge regression model.</li></ul><p><em>Note — In this we took zero value which are not present in cluster because maximum point lies in zero only.</em></p><p>Result of Ridge regression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*Ro0duGzIoE9L3oAT31EVAg.png" /></figure><p><strong>Decision Tree</strong></p><p>Before making we had found best ‘depth’ hyper parameter value for decision tree. And we got best depth value as 3. So now we will make a model.</p><p>Result of Decision Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*wOQnQzWAZ0nBg9K1KS_URA.png" /></figure><p><strong>XG Boost</strong></p><ul><li>First we had done grid search cv to find best parameter.</li><li>Second we made a model.</li></ul><pre>X=data_tr.drop(&#39;y&#39;,axis=1)<br>y=data_tr.y<br>xg=XGBRegressor(learning_rate=.01,max_depth=3,n_estimators=600,colsample_bytree=.55,subsample=.85,gamma=.65,colsample_bylevel=.95)</pre><pre>#fitting X and y<br>xg.fit(X,y)</pre><p>After making the model we saved into local drive and then we test the model on X_test data and we got R2-score as 0.605.</p><p>but after adding small value in predict value and we notice that at 0.4 value we got max R2 score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*KW2O9fv3SyX_yU7dpN1Sug.png" /></figure><p><strong>Note</strong>: After getting a result,<strong> </strong>add 0.4 seconds. E.g. if my model predicts 98.2 then add 0.4 into. So now my final y_pred will be 98.6 sec. as shown in fig 21</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*riI8EB2TQOj82F1RDPv7Iw.png" /><figcaption>fig 21</figcaption></figure><p><strong>Final all model summary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VuWHgNueraDwnhkuuCFtg.png" /></figure><p>We can see linear regression model had worked quiet well.</p><h3>14. Final Prediction Function</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/506a434ab6afe8f2de9abead2ce959de/href">https://medium.com/media/506a434ab6afe8f2de9abead2ce959de/href</a></iframe><h3>15. My final approach summary:</h3><ul><li><strong>Step 1: </strong>Remove all the ‘y’ whose value is greater than 150.</li><li><strong>Step 2: </strong>Made two set’s for X0, X2 feature.</li><li><strong>Step 3: </strong>Label encoded these feature X0,X1,X2,X3,X4,X5,X6,X8.</li><li><strong>Step 4: </strong>Made new ID by doing : (1/(log(x)+3))</li><li><strong>Step 5: </strong>Removed all columns which contain only zero.</li><li><strong>Step 6: </strong>Made cluster for X0 feature.</li><li><strong>Step 7: </strong>Interacting variable [‘X314_plus_X315’], [‘X118_plus_X314_plus_X315’].</li><li><strong>Step 7: </strong>Finally used XGboost regressor with the tuned parameter.</li></ul><h3>16. Thing’s that didn&#39;t work for me</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*gqJ8pHYfxu4LdSRGjsOFzQ.png" /><figcaption>fig 22</figcaption></figure><ul><li>Removing only the last value.</li><li>Made sets for X1,X3,X4,X5,X8 feature.</li></ul><p>.</p><p>.</p><p>.</p><p><strong>This is my final Kaggle score</strong></p><blockquote><strong>My kaggle score:- private = 0.55329 and public = 0.55621</strong></blockquote><p><strong><em>By this solution, I got 42nd position.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*YS85gJANl767ul0AuZ6igQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*dZCAbuL0j1EErZ3S" /></figure><h3>17. Conclusion</h3><ol><li>Data is very anonymous.</li><li>Data contain outlier.</li><li>Making simple set’s of X0 was good because</li></ol><p>a. We notice that in train data whose car testing time was less than 80 in that 95.77% have X0 feature value as ‘az’, 100% have X27,X10 feature value as 1,0 resp.</p><p>Similarly in prediction whose car testing time was less than 80 in that 96.15% have X0 feature as ‘az’, 100% have X27,X10 feature value as 1,0 resp.</p><p>b. We notice that in train data whose car testing time between 90 and 100 in that 72.1 % have X0 feature value as [‘y’, ’z’, ’t’, ’o’, ’f’, ’n’, ’s’, ’al’, ’e’].</p><p>Similarly in prediction whose car testing time between 90 and 100 in that 84.4 % have X0 feature value as [‘y’, ’z’, ’t’, ’o’, ’f’, ’n’, ’s’, ’al’, ’e’].</p><p>c. We notice that in train data whose car testing time between 100 and 120 in that 79.4 % have X0 feature value as [‘ak’, ’x’, ’ay’, ’w’ , ’j’, ’aj’, ’ap’, ’h’, ’d’, ’v’].</p><p>Similarly in prediction whose car testing time between 100 and 120 in that 89.3 % have X0 feature value as [‘ak’, ’x’, ’ay’, ’w’ ,’j’, ’aj’, ’ap’, ’h’, ’d’, ’v’].</p><p>4. Simple feature engineering like with interaction variable was also good.</p><h3>18. Future Work</h3><p>Thanks a lot if have reached here. This is my first attempt in blogging so I expect the readers to be a bit generous and might ignore the minor mistake I might have.</p><p>We can do a lot of modification to improve the solution. Some of them are here.</p><ol><li>There is some duplicate binary column which we can remove.</li><li>We can try some other algorithm. If this business idea saves lot of money for the company, then we also try to make our model based on the Neural Network.</li><li>We can also try to remove those features which are highly correlated among each other.</li><li>There can be another way to modify the ID column. Instead of using the log in the denominator, we can use a weighted exponential moving average.</li><li>Using Neural network.</li></ol><blockquote><strong>References</strong></blockquote><ol><li><a href="https://www.kaggle.com/c/mercedes-benz-greener-manufacturing/discussion/37700">https://www.kaggle.com/c/mercedes-benz-greener-manufacturing/discussion/37700</a></li><li><a href="https://www.kaggle.com/c/mercedes-benz-greener-manufacturing/discussion/36242">https://www.kaggle.com/c/mercedes-benz-greener-manufacturing/discussion/36242</a></li><li><a href="https://www.kaggle.com/sudalairajkumar/simple-exploration-notebook-mercedes">https://www.kaggle.com/sudalairajkumar/simple-exploration-notebook-mercedes</a></li><li><a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419c4eefe2f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>