<?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 Utkarsh Ankit on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Ankit on Medium]]></description>
        <link>https://medium.com/@utkarsh-ankit?source=rss-5e573e9d7364------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nIrONn0W2SH4TlbvTPXU7g.png</url>
            <title>Stories by Utkarsh Ankit on Medium</title>
            <link>https://medium.com/@utkarsh-ankit?source=rss-5e573e9d7364------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:58:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utkarsh-ankit/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[RLCD: Reinforcement Learning for Calibrated Decisions]]></title>
            <link>https://pub.towardsai.net/rlcd-reinforcement-learning-for-calibrated-decisions-e528daf3591d?source=rss-5e573e9d7364------2</link>
            <guid isPermaLink="false">https://medium.com/p/e528daf3591d</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Utkarsh Ankit]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 12:08:21 GMT</pubDate>
            <atom:updated>2026-09-28T10:14:06.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>RLCD : Reinforcement Learning for Calibrated Decisions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NS88BGk8ur0LdgNN" /><figcaption>Photo by <a href="https://unsplash.com/@dmey503?utm_source=medium&amp;utm_medium=referral">Dan Meyers</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A new post-training method devised by TypeSafe AI for their model Jev. Post-training methods are generally an amalgamation of multiple aspects of machine learning systems, and I have observed a lot of creative experiments researchers are doing to make LLMs more robust.</p><p>So, let’s explore the newest member of this family: RLCD. But before we jump, let’s understand Typesafe’s first public model, “Jev”, and how it differs from a general LLM.</p><p>Jev focuses more on automation (software decision-making) rather than generative text generation.</p><p>What they did differently:-</p><ul><li>A new architecture</li><li>Parallel Sampler</li><li>A new training method (RLCD)</li></ul><p>And they claimed that their architecture is faster and more efficient than state-of-the-art architectures. You can learn more about the Jev architecture <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">here</a>.</p><h3>Jev’s Output</h3><p>The output of Jev is not text or unstructured data but a JSON object that contains calibrated decision values and probability distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*MA1TsEQUmvDaeja34rKqgw.png" /><figcaption>Schema-guaranteed output structure. Source: Chrome for Developers</figcaption></figure><p>Jev returns one of the three mathematical objects (Choice, Score, or Noul) for a decision:-</p><ol><li><strong>Choice</strong> Output for Multi-Class Selection</li></ol><p>While evaluating a discrete set of categories, it outputs the winning category with a fully calibrated probability vector across all candidates and an overall confidence score.</p><pre>{<br>  &quot;type&quot;: &quot;choice&quot;,<br>  &quot;selection&quot;: &quot;fraud_review&quot;,<br>  &quot;confidence&quot;: 0.884,<br>  &quot;probabilities&quot;: {<br>    &quot;approve&quot;: 0.042,<br>    &quot;fraud_review&quot;: 0.884,<br>    &quot;decline&quot;: 0.074<br>  },<br>  &quot;latency_ms&quot;: 84<br>}</pre><p>2. <strong>Score</strong> Output (Ordinal Scale)</p><p>Let’s say we have to check the urgency on a 1–5 scale; it returns the probability-weighted expected score with the distribution.</p><pre>{<br>  &quot;type&quot;: &quot;score&quot;,<br>  &quot;value&quot;: 4.2,<br>  &quot;confidence&quot;: 0.912,<br>  &quot;distribution&quot;: {<br>    &quot;1&quot;: 0.01,<br>    &quot;2&quot;: 0.03,<br>    &quot;3&quot;: 0.12,<br>    &quot;4&quot;: 0.43,<br>    &quot;5&quot;: 0.41<br>  },<br>  &quot;latency_ms&quot;: 92<br>}</pre><p>3. <strong>Noul</strong> Output (Binary)</p><p>When we are dealing with binary conditions (T/F or Y/N), it returns a calibrated probability between 0.0 and 1.0 representing likelihood.</p><pre>{<br>  &quot;type&quot;: &quot;noul&quot;,<br>  &quot;value&quot;: true,<br>  &quot;probability&quot;: 0.941,<br>  &quot;latency_ms&quot;: 76<br>}</pre><p>So, if we observe the outputs, we see that schema-based errors, missing key hallucinations, or invalid JSON syntax are out of scope because the output is generated by a non-autoregressive output head rather than some sampled text.</p><p>Along with that, we are also getting calibrated probabilities that correspond to true ground-truth accuracy.</p><p>But here is a catch: we first need to understand what calibration is (skip if you know ECE).</p><h3>Calibration</h3><p>Calibration basically means the model’s confidence matches how often it’s actually right. For example, we built a spam email classification model that says how likely an email is spam. It assigns an 80% spam probability to 100 emails. And when we check:-</p><ul><li>If 80 of 100 are actually spam, we say our model is <strong>perfectly calibrated</strong>.</li><li>If 50 of 100 are actually spam, we say our model is <strong>overconfident</strong>.</li><li>If 95 of 100 are spam, we say our model is <strong>underconfident</strong>.</li></ul><p>So, basically, we check if our model is lying or not. We aim that if our model says X%, it should be right X% of the time.</p><p>We should not confuse calibration with confidence and accuracy, as they say different things, but are related:-</p><ul><li><strong>Accuracy</strong>: How often is the model right? (wrt ground truth)</li><li><strong>Confidence</strong>: How sure does the model claim to be? (The final Sigmoid/Softmax output)</li><li><strong>Calibration</strong>: Does the model know how often it is right? (How much the model’s confidence matches real-world accuracy)</li></ul><p>The problem with standard neural networks or LLMs is that, trained on Cross-Entropy loss, they tend to push softmax probabilities to extreme values (0.999 or 0.001), which makes the model severely overconfident even when it is hallucinating or predicting incorrect values.</p><blockquote>We measure calibration by <strong><em>Expected Calibration Error </em></strong>(ECE) and evaluate overall probabilistic quality using <strong>Brier Score</strong>:-</blockquote><p><strong><em>Expected Calibration Error </em></strong>(ECE):-</p><ul><li>Grouping predictions into bins: eg. Bin 1: 50–60% confidence, Bin 2: 60–70% confidence, …, Bin 10: 90–100% confidence.</li><li>Calculate accuracy per bin.</li><li>Compute the gap.</li></ul><pre>ECE = ∑ ( |B_m| / N ) * | acc(B_m) - conf(B_m) |<br><br>Where:<br> M = Total number of confidence bins<br> |B_m| = Number of samples in bin m<br> N = Total number of samples<br> acc(B_m) = Actual accuracy of predictions in bin m<br> conf(B_m) = Average confidence assigned to predictions in bin m</pre><p>Then we can plot a <strong>reliability diagram</strong> for better observation.</p><figure><img alt="Reliability diagram illustrating the Expected Calibration Error (ECE = 47.69%) on the final task of the CIFAR-100 dataset. The large gap (olive-green) between confidence and actual accuracy (blue) demonstrates significant model overconfidence." src="https://cdn-images-1.medium.com/max/328/0*lIjN9xJNELNoTIfB" /><figcaption><strong>Reliability Diagram</strong> where the yellow-shaded area represents the calibration gap. <em>Source: Kang et al. (2020), licensed under CC BY 4.0.</em></figcaption></figure><p><strong><em>Brier Score:-</em></strong></p><p>It is used to evaluate calibration (it measures the overall quality of probabilistic predictions: MSE between predicted probabilities and real binary outcomes); lower is better. It leads to maximising the model’s score if and only if its reported probability matches its true likelihood of being correct. So, it is a Proper Scoring Rule. Calibration is one component of it, as the Murphy decomposition shows.</p><pre>Brier Score (Mean Squared Error):<br>  BS = (1 / N) * ∑ (f_i - o_i)^2<br><br>where:-<br>predicted probabilities (fᵢ)<br>actual binary outcomes (oᵢ ∈ {0, 1})<br>N is the number of samples<br><br>---<br><br>Murphy Decomposition:<br>  Brier Score = Reliability - Resolution + Uncertainty<br><br>Definitions:<br>  - Reliability (Calibration)  : Discrepancy between predicted probabilities and outcome frequencies. Lower is better.<br>  - Resolution                 : How much the outcome frequencies for different forecasts differ from the base rate, i.e., whether the model separates cases. Higher is better.<br>  - Uncertainty (Base Noise)   : Irreducible variance of the target variable.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*zhX8yCDSoBo97z5trJJu4A.png" /><figcaption>Comparison of Brier Score, Log-Loss, and ECE on a reliability plot. Source: MetricGate, licensed under CC BY 4.0.</figcaption></figure><blockquote><strong>Three methods to fix a model’s calibration:-</strong></blockquote><ol><li><strong>In Training Regularisation</strong> (During Training):-</li></ol><ul><li><strong><em>Label Smoothing</em></strong>: Modify the one-hot labels with a uniform distribution across all classes.</li><li><strong><em>Focal Loss</em></strong>: It replaces the cross-entropy with a modulated loss function.</li><li><strong><em>Weight Decay/L2 Regularisation</em></strong>: Works by penalising large parameter weights.</li></ul><p><strong>2. Post-Hoc Recalibration</strong> (After Training):-</p><ul><li><strong><em>Temperature Scaling</em></strong>: As softmax is <strong>shift-invariant</strong>, we divide the raw logits by a scalar parameter before softmax (p̂ = Softmax(z / T)). It basically flattens the distribution. It is the multi-class extension of <strong>Platt Scaling</strong>. If it is required to learn a separate scale per class, <strong>Vector Scaling</strong> is used.</li><li><strong><em>Isotonic Regression</em></strong>: It is a non-parametric method that basically learns a function that maps uncalibrated probabilities to calibrated ones. Works best with binary classifiers and requires a larger validation set. Not suitable for neural network-based models/LLMs.</li></ul><p><strong>3. RL and Objective-Based Calibration:-</strong></p><ul><li><strong><em>ECE Penalty Integration</em></strong>: It works by directly adding a penalty for ECE (which we already discussed above) into the policy gradient reward function during fine-tuning.</li></ul><pre>R_total = R_accuracy - λ · ECE<br><br>Where:<br> R_total = Total combined reward signal<br> R_accuracy = Accuracy or task reward signal<br> λ (lambda) = Calibration penalty weight<br>ECE = Expected Calibration Error</pre><ul><li><strong><em>RLCD</em></strong>: Based on “Proper Scoring Rules as rewards”. We are going to discuss this part in detail.</li></ul><h3>RLCD</h3><p>Let’s first theoretically understand what RLCD does.</p><blockquote><strong>The problem:-</strong></blockquote><p>In a general RLVR-based system, the model gets a point for a correct answer (+1) and nothing for an incorrect one (0). We can observe that there is no penalty for bluffing; the model always shows 100% certainty for every question. This leads to a situation where the model outputs extreme scores on the answers where it is actually uncertain or guessing, because the reward function does not penalise false confidence (bluff).</p><p>Let’s understand it with an example:-</p><p>Let’s assume there are two models, A and B. Both are designed for multiclass classification with 4 classes (i, j, k, l). And we have a standard RLVR that gives +1 for a correct option and 0 for an incorrect option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQ8Ju9Az-vVGX3itCxgbsQ.png" /></figure><p>We can observe that the environment gives the same reward (+1) to 25% (model A), which might be a random guess or when it claims 99% certainty (model B).</p><p>Then, using policy gradient algorithms like PPO and GRPO, the optimiser updates the weights using the log-prob gradient. So whenever the model gives a correct answer (R = +1), the policy-gradient update (gradient ascent on expected reward) increases the logits of that choice (towards +∞) over multiple training steps, which eventually leads to higher probabilities after softmax.</p><p>This leads to the model saying 99% confident, yielding max rewards, and yet it never checks whether the probability matches the historical accuracy.</p><blockquote><strong>The solution:-</strong></blockquote><p>In RLCD, the model must give its answer and place a confidence score (0%-100%).</p><ul><li><strong>Correct Answer + High Bet (95%):</strong> Big Reward (+10 points)</li><li><strong>Correct Answer + Low Bet (60%):</strong> Small Reward (+3 points)</li><li><strong>Wrong Answer + Low Bet (60%):</strong> Small Penalty (-2 points)</li><li><strong>Wrong Answer + High Bet (95%):</strong> <strong>MASSIVE PENALTY (-100 points)</strong></li></ul><h4><strong>Steps of RLCD pipeline:-</strong></h4><pre>[ Input State ]<br>       │<br>       ▼<br>1. Make a Decision + State Confidence (e.g., Option A at 85%)<br>       │<br>       ▼<br>2. Check Outcome &amp; Score Individual Bet (Brier Score / Proper Scoring Rule)<br>       │<br>       ▼<br>3. Audit Historical Honesty Across 1,000 Decisions (Batch ECE Penalty)<br>       │<br>       ▼<br>4. Update Weights (Force the model to soften or sharpen its bets)</pre><p>So, by repeating these steps multiple times during training, the model develops a calibrated score, so when it says it&#39;s 88.4% sure, it means that across thousands of real-world cases, it will be 88.4% correct.</p><p>In simple language, RLCD replaces the binary (+1/0) rewards with Proper Scoring Rules (like the Brier Score) and a batch calibration penalty. That gives us a properly aligned and calibrated model.</p><h3><strong>Architecture</strong></h3><ol><li><strong>The Actor/Policy Network (π_θ)</strong></li></ol><p>The Jev model acts as the Actor Network, that ingest the context and outputs the decision ŷ along with the calibrated probability distribution p̂.</p><pre>Input State (s) ──► Transformer Encoder ──► Latent Vector h(s) ──► Schema Head ──► P_θ(y|s)</pre><p>2. <strong>The Critic Network (V_ϕ)</strong></p><p>The main role of a Critic Network is to provide advantage estimation (which can differ if PPO or GRPO is used during training). It is trained alongside the Actor network. The actor produces the decision probabilities; the critic predicts the expected calibrated return for state s.</p><ul><li>If PPO:-</li></ul><pre>A(s, y) = R_calibrated(P, y*) - V_ϕ(s)<br><br>Where:<br>  A(s, y)           = Calibrated Advantage Function<br>  R_calibrated(...) = Proper Scoring Reward minus Batch ECE Penalty<br>  V_ϕ(s)            = Critic&#39;s Expected Baseline Value for state s</pre><ul><li>If GRPO:-</li></ul><p>Here we remove the critic network altogether to save GPU memory during training. So, to calculate the advantage, the model samples a group of G decisions for the same state and takes the average, which acts as the baseline.</p><pre>A_i = (R_i - mean(R_1, ..., R_G)) / std(R_1, ..., R_G)<br><br>Where:<br>  A_i                 = Group-relative advantage for sample i<br>  R_i                 = Calibrated reward for sample i<br>  mean(R_1, ..., R_G) = Mean reward across sample group G<br>  std(R_1, ..., R_G)  = Standard deviation of rewards across group G</pre><p>3. <strong>The Reward Function</strong></p><p>This is the interesting part: traditional RLHF trains a reward model (a neural network) that approximates human preferences (which is prone to reward hacking, where the generator usually tricks the reward model using a certain type of answer to get a better reward, even if the answer is bad).</p><p>In RLCD, there is <strong>no learned reward model</strong>. The reward engine is designed to be <strong>deterministic</strong> (a closed-form mathematical verifier), which evaluates the Actor’s response against the ground truth using the Proper Scoring Rule. Because the objective truth already exists, we don’t need a separate NN to guess the score. Then we evaluate the prediction directly against the ground truth.</p><pre>R_Brier = 1 - ∑_(k=1)^K (p_k - y_k*)^2<br><br>Where:<br>  K                = Total number of schema options<br>  p_k              = Predicted probability for option k<br>  y_k*             = Ground-truth binary target (1 if correct, 0 otherwise)<br>  ∑ (p_k - y_k*)^2 = Brier Loss (Mean Squared Error)<br>  1 - Brier Loss   = Final Calibrated Reward Signal</pre><p>It gives better alignment; if the Actor is only 60% certain, claiming 90% will lower its expected mathematical payoff over multiple training steps</p><p>Also, there is no reward-hacking problem since the reward mechanism is a fixed equation that depends entirely on the objective ground truth, so it can&#39;t trick the evaluator.</p><p>FYI: TypeSafe hasn’t publicly disclosed their exact reward mechanism; this is my reconstruction based on the standard calibration methods.</p><p>Let&#39;s take an example. Assume a binary classification with 2 outcomes, Option A (K=1) and Option B (K=2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsmhCcSs-YSPoRXKGC2cvQ.png" /></figure><p>4. <strong>The Batch Calibration (Global Monitor)</strong></p><p>It acts as a supervisor during training:</p><ul><li>Observes a mini-batch of N trajectories.</li><li>Does the binning (predictions by reported confidence eg. 80%–90%)</li><li>Computes the <strong>Expected Calibration Error (ECE)</strong> across the batch.</li></ul><pre>1. Average Bin Confidence:<br>   conf(B_m) = (1 / |B_m|) * ∑_(i ∈ B_m) p̂_i<br><br>2. Empirical Bin Accuracy:<br>   acc(B_m)  = (1 / |B_m|) * ∑_(i ∈ B_m) 1(ŷ_i = y_i*)<br><br>3. Expected Calibration Error (ECE):<br>   ECE(B)    = ∑_(m=1)^M (|B_m| / N) * |acc(B_m) - conf(B_m)|<br><br>Interpretation:<br>   - ECE ≈ 0.0 : Model confidence perfectly matches empirical accuracy.<br>   - ECE &gt; 0.0 : Presence of systemic miscalibration across the batch.</pre><ul><li>After that, it turns the calibration gap into a per-sample reward adjustment. And just subtracting a single −λ·ECE from every sample would not work (λ is a scaling variable). RL learns from how each sample compares to the average; therefore, a penalty that is shared by everyone cancels out. So instead of that, each sample is adjusted based on the bin it falls in:</li></ul><pre>R_i ← R_i − λ · (conf(B_m) − acc(B_m))     for sample i in bin m</pre><ul><li>Overconfident bin (conf &gt; acc): reward goes down → the model lowers its confidence on those predictions.</li><li>Underconfident bin (conf &lt; acc): reward goes up → the model raises its confidence.</li></ul><p>After many updates, it pulls each confidence level toward the actual accuracy it achieves.</p><p>So, this is about the architecture.</p><h4>TypeSafe’s claim:-</h4><ol><li>PERFECT CALIBRATION (No Bluffing)</li><li>SUB-MILLISECOND (No token-by-token decoding loops)</li><li>SCHEMA GUARANTEE (Outputs bounded, typed tensors)</li><li>NO REWARD HACKING (Closed-form Proper Scoring Rules)</li><li>COMPUTE EFFICIENCY (Compact specialised models outperform 70B+ LLMs on structured enterprise decision tasks.)</li></ol><h3>Conclusion</h3><p>I tried to sum up the concepts according to my understanding, since the full technical specifications from TypeSafe remain proprietary.</p><p>RLCD is a step towards the kind of models “that know what they don’t know”, which is exactly what is needed in automation.</p><h3>Acknowledgements &amp; Let’s Connect</h3><p>I hope you enjoyed this breakdown. I tried to simplify things and connect the dots.</p><p>A special thanks to Corgi Cafe, SF, for providing a beautiful workplace and late-night fuel (Espresso shots) that made this writing possible.</p><p>Connect with me on <a href="https://www.linkedin.com/in/utkarsh-ankit/">LinkedIn</a> and <a href="https://x.com/UttsPutts">X</a> here.</p><p>I would love to hear your thoughts, and I am always open to discussion.</p><h3>References &amp; Further Reading</h3><h4>Official TypeSafe AI Resources</h4><ul><li><a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">Introducing System One Models and Jev</a> — <em>TypeSafe AI Blog (Sept 2026)</em></li><li><a href="https://typesafe.ai/blog/bitterest-lesson">The Bitterest Lesson</a> — <em>TypeSafe AI Blog</em></li><li><a href="https://docs.typesafe.ai/introduction">TypeSafe AI Technical Documentation</a> — <em>Official API &amp; Schema Specs</em></li><li><a href="https://evals.typesafe.ai/">TypeSafe Benchmarks &amp; Evaluation Suite</a> — <em>Official Calibration &amp; Performance Metrics</em></li></ul><h4>Academic Papers</h4><ul><li><a href="https://arxiv.org/abs/2609.26550">JEV-as-a-Judge: Accept When Confident, Escalate When Unsure</a> — <em>Li et al. (arXiv:2609.26550, Sept 2026)</em></li><li><a href="https://arxiv.org/abs/1706.04599">On Calibration of Modern Neural Networks</a> — <em>Guo et al. (ICML 2017)</em></li><li><a href="https://doi.org/10.1175/1520-0493(1950)078%3C0001:VOFEIT%3E2.0.CO;2">Verification of Forecasts Expressed in Terms of Probability</a> — <em>Brier (Monthly Weather Review, 1950)</em></li></ul><h4>Industry Technical Overviews</h4><ul><li><a href="https://you.com/resources/what-is-jev">What Is Jev? TypeSafe AI’s System One Model Explained</a> — <em>You.com Technical Resources</em></li><li><a href="https://www.sanity.io/glossary/rlcd-reinforcement-learning-for-calibrated-decisions">RLCD: Reinforcement Learning for Calibrated Decisions</a> — <em>Sanity AI Architecture Glossary</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e528daf3591d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/rlcd-reinforcement-learning-for-calibrated-decisions-e528daf3591d">RLCD: Reinforcement Learning for Calibrated Decisions</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification of PCBs and its Web Application (Flask)]]></title>
            <link>https://medium.com/data-science/image-classification-of-pcbs-and-its-web-application-flask-c2b26039924a?source=rss-5e573e9d7364------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2b26039924a</guid>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Utkarsh Ankit]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 13:23:06 GMT</pubDate>
            <atom:updated>2021-09-15T09:26:47.159Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating an Image Classification Model for PCBs and designing a Web Application using Flask.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9L0jst2QWPVOAmO-XRFkQ.jpeg" /><figcaption>source: <a href="https://alutritos.vercel.app/index/view-29-simple-circuit-board-art/">alutriots</a> (CC0).</figcaption></figure><p>Hello, This blog is about creating an Image Classification model for PCBs(Printed Circuit boards) to detect defective PCBs and classify them as Good or Bad. So for that, we will create a Deep Learning Model and try to get the best possible results along with proper visualisation of each step. After creating the working model, we will create a Web Application for the same using Flask. You can find the code for this project on my GitHub along with the setup instruction file below. So, let’s go ahead and flex.</p><blockquote><strong>Requirements</strong></blockquote><ol><li>Jupyter Notebook</li><li>Python 3.5 or Later. (3.7 preferable)</li><li>Libraries — Tensorflow, Keras, Pandas, Numpy, Matplotlib, OpenCV, Pillow, Flask. [<em>all latest version</em>]</li></ol><blockquote><strong>Understanding the Dataset</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bpK_lgPS0sm47Aki7aBurw.jpeg" /><figcaption>source: <a href="https://pcbways.blogspot.com/1969/12/pcb-layout-altium-designer.html">pcbways</a>(CC0).</figcaption></figure><p>PCBs (Printed Circuit Boards) is a widely used electronic component, used almost in any electronic device. Sometimes during its mass production in factories leads to some anomalies which lead to a defective product. Electronic companies have to bear that loss. So this deep learning Image Classification model helps to identify Good and Bad Circuits at production time only.</p><p>So, the dataset we are using is a binary image of PCB, in which the Black part denotes the circuit and the white parts signify the empty circuit areas. The dots or noise in the image shows the anomalies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*j15CXf3rL0YBeJlsyV4olA.jpeg" /><figcaption>Fig. Binary Image of a PCB with “no defect”.</figcaption></figure><p>As we can see the image has no anomalies and defects in it. Now, we will see another image of a PCB with defects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*lUJLv-cT3nTbgplr6NM4-Q.jpeg" /><figcaption>Fig. Binary Image of a PCB “with defects” (I edited the image and marked the defects).</figcaption></figure><p>As here the defects are marked, it is an example of a defective PCB. You can download the dataset from <a href="https://github.com/tangsanli5201/DeepPCB"><strong><em>here</em></strong></a>.</p><blockquote><strong>Data Preparation/Preprocessing</strong></blockquote><p>Now after we download the dataset, we can see the dimension of each image is 640x640. It will be better if we reduce the dimension of them so that it will be easy for training the data, but to make sure the quality of the image didn’t get affected, we will compress the image using the Anti-Aliasing technique.</p><p>Here is my <a href="https://github.com/utk-ink/Image-Operation-Tools"><strong><em>link</em></strong></a> to my GitHub repo which helps to do the same. Use the Image Resizer tool there and you will get the desired result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*t8y7DIho-6CwC7w9-LRnvA.jpeg" /><figcaption>Fig. Processed 224x224 image.</figcaption></figure><p>So, after resizing the image to 224x224, we save them into a different folder. I saved 1,095 images of somewhat equally mixed good and bad PCBs. So, that folder is going to be your Training Data set. Pick some other images (different from the training set) and put them into a separate folder to work as your Test Data set. Make sure the test folder is a good mixture of good and bad images with a proper ratio maintained.</p><p>Now I will check my training dataset that it has a proper ratio of both types of images or in other words, to check the possible “class imbalance”. Well for my reference, I named the good PCB image as Good().jpeg and bad as Bad().jpeg. Then I labelled the good images as ‘0’ and bad images as ‘1’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d69d52ac1f6ef49a6a1b5bb4e644c88/href">https://medium.com/media/4d69d52ac1f6ef49a6a1b5bb4e644c88/href</a></iframe><p>And then we plot their graph:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*bFBm5ukRZDeSf_g2MjN4Dg.png" /></figure><p>So, we can observe from the graph that our classes are pretty balance. Now for Cross-Validation, we will split out the training dataset into training and validation sets. As I mentioned earlier I took 1,095 images. I split them as 80% training data and 20% validation set.</p><pre>train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)</pre><pre>train_df = train_df.reset_index(drop=True)<br>validate_df = validate_df.reset_index(drop=True)</pre><p>And then we plot both training and testing image ratios:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*jLJ0DJgPjJPgs8QGB8EuYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*z3772t6wAPIs7A2AwDUbqQ.png" /></figure><p>⇙</p><ul><li>This is the plotted graph of the final “training dataset”, i.e. approximately 400+ images in both classes.</li></ul><p>⇖</p><p>⇙</p><ul><li>This is the plotted graph of the “validation dataset”, i.e. approximately 100+ images in both classes.</li></ul><p>⇖</p><p>___</p><p>Now I am going to apply one of the greatest tools according to me i.e. Keras ImageDataGenerator. It is a very useful tool as it helps to do Data Augmentation in real-time while training the model. As we know our training data is already less, so applying augmentation not only helps us to make our model robust but also saves memory.</p><p>Now, we add the path and load the images in the generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dt1-fCKHdHXzoS44Yej8HA.png" /></figure><p>So, now we can say that our Data Preparation/Preprocessing part is complete.</p><blockquote><strong>Model Implementation</strong></blockquote><p>Now it’s time to design the brain. Here I used the <em>“</em><strong><em>MobileNet</em></strong><em>” </em>model which is pre-trained on the ImageNet dataset. Well, MobileNet is a Deep Learning based Convolution Neural Network Architecture. It is a lightweight architecture and uses depthwise separable convolutions. You can learn more about it from its paper <a href="https://arxiv.org/abs/1704.04861"><strong><em>here</em></strong></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igdU_PkuLUq8EvQ-whLiTw.jpeg" /><figcaption>Fig. MobileNets Architecture. source: <a href="https://www.hindawi.com/journals/misy/2020/7602384/fig1/">hindawi</a>(CC0).</figcaption></figure><p>As I mentioned we are using the MobileNet model pre-trained of ImageNet Dataset, so here we are using the concept of Transfer Learning. Therefore instead of training the whole model, we will freeze the base layer and add some other layers according to our requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a88402d713568b98cbcfe1ffaab0bf1d/href">https://medium.com/media/a88402d713568b98cbcfe1ffaab0bf1d/href</a></iframe><p>As we are using pre-trained weights, we will make sure that all the weights are non-trainable except the last few dense layers. Well, I set the first 20 layers to be non-trainable.</p><pre>for layer in model.layers[:20]:<br>    layer.trainable=False<br>for layer in model.layers[20:]:<br>    layer.trainable=True</pre><p>But if you want to set all layers to be non-trainable, you can use this instead.</p><pre>for layer in model.layers:    <br>    layer.trainable=False</pre><p>So, we are done with the Model Implementation part now.</p><blockquote><strong>Training</strong></blockquote><p>So, our data preparation is done along with model implementation. Now, it’s time to train our model. Before I proceed further, I want to mention that I used two Callbacks named “<em>Early Stopping</em>” and “<em>Learning Rate Reduction</em>”.</p><p>We need to consider the number of Epochs carefully as too many of them lead to overfitting the data, whereas too few leads to underfitting. Early Stopping allows you to specify an arbitrarily large number of training epochs and stop training when the model stops improving on a hold out validation dataset. Here is a <a href="https://machinelearningmastery.com/how-to-stop-training-deep-neural-networks-at-the-right-time-using-early-stopping/"><strong><em>link</em></strong></a> if you want to learn more about it.</p><p>ReduceLROnPlateau reduces the Learning Rate when a metric is stopped improving. Models often benefit from reducing the learning rate by a factor of 2–10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced. You can check this from <a href="https://keras.io/api/callbacks/reduce_lr_on_plateau/"><strong><em>here</em></strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b69227a8b5fc81e0efd913086c61432/href">https://medium.com/media/7b69227a8b5fc81e0efd913086c61432/href</a></iframe><p>Now, we will start training our model. Well, I trained my model on Google Colab as it gives certain advantages, I will advise everyone to try to use Google Colab, you just need to upload or link the dataset on google drive and then mount it on colab using this simple call by giving right folder location:-</p><pre>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)</pre><p>Now we will set all the variables in the model.fit.generator() and then we will start to train our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLcjvkMaipzbF1GYGp6YEQ.png" /></figure><p>Well, I set my epoch as 50 but it stopped it at 42 as it stops improving. I plotted two graphs from the data we extracted while training the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*q3GdQbzakoT5s_M2Pb7A4w.png" /></figure><p>.</p><p>⇙</p><ul><li>“Loss vs Epochs” graph.</li></ul><p>⇖</p><p>.</p><p>⇙</p><ul><li>“Accuracy vs Epochs” graph.</li></ul><p>⇖</p><p>.</p><p><em>Note:- The Blue line denotes the training and Red line denotes the validation variable respectively in both the graphs.</em></p><p>So, after training the model, I got a <strong>Validation Accuracy of 95.71%</strong><em>.</em></p><p>Now, we save the trained weights in the .h5 or .hdf5 file (both are the same).</p><pre>model.save_weights(&quot;model.h5&quot;)</pre><p>If you trained it via Google Colab, you can save the weights in the drive directly like this:-</p><pre>model.save(&#39;/content/drive/My Drive/folder (1)/model.h5&#39;)</pre><p>Therefore our training is complete, now it’s time to check the results.</p><blockquote><strong>Prediction and Results</strong></blockquote><p>So first, we will load our model.</p><pre>model = load_model(r&#39;C:/Users/nEW u/Flask/model.h5&#39;)</pre><p>Then we will use ImagedataGenerator to get to the test folder and call the image files collectively. And will call the predict function and set it with the image generator function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd86a29aa7fde01ab4d87d93a6d89cda/href">https://medium.com/media/dd86a29aa7fde01ab4d87d93a6d89cda/href</a></iframe><p>Now, we will plot our results along with the images. I took the help of the Matplotlib library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/064539ca80ca5ecb2573bae0ff328e76/href">https://medium.com/media/064539ca80ca5ecb2573bae0ff328e76/href</a></iframe><p>And here comes our result:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*AagOOvAUxGUXuOmEor9kvQ.png" /></figure><p><strong><em>Note</em></strong><em>:- As I mentioned earlier, I named the images files as good and bad for my reference. So, the initial part is the name of the image file and the result is in the Bracket. Therefore you can compare the Result with the actual Image quality as per the image name.</em></p><p>So, here our Image Classification model is complete successfully. Now, it&#39;s time to create a Web Application. I am going to use Flask for it.</p><h3><strong>Web Application Using Flask</strong></h3><p>Flask is a Python’s API used to create web applications. So, for start, I am gonna give you a basic code snippet that we usually follow while using Flask.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff67a22effb308fca696544174daabae/href">https://medium.com/media/ff67a22effb308fca696544174daabae/href</a></iframe><p>Hope you got a bit idea, Now let’s start implementing.</p><blockquote><strong>Functions</strong></blockquote><p>First, we must write functions to call the model, for processing the image before we pass it to our model and prediction function which let our image pass the model and return the result.</p><ul><li>For calling the model:-</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bb2650519183ee86876e4d381bf35e1/href">https://medium.com/media/2bb2650519183ee86876e4d381bf35e1/href</a></iframe><ul><li>For processing the image:-</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7458a78ecd1a8f310c6350bdccb95e34/href">https://medium.com/media/7458a78ecd1a8f310c6350bdccb95e34/href</a></iframe><ul><li>Prediction function (it uses the<em>“load_image”</em> function):-</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a45110e5085a7f81f9f8b9485e895ed0/href">https://medium.com/media/a45110e5085a7f81f9f8b9485e895ed0/href</a></iframe><blockquote><strong>Design</strong></blockquote><p>As we are done with our functions, we will proceed forward to design our web pages. So, here we will need two pages, On the first page, it will ask to select and upload the image. The second page will show the image along with the result.</p><p><strong><em>Important Note</em></strong><em>:- While using Flask we must be very attentive as we need to create a separate folder. In that folder, we will create our python file in which we use flask, and we also need to create two subfolders named “Templates” and “Static”. Templates are where we save our HTML files, and in the Static folder, we save images and other stuff. You must follow this convention if you want to save yourself from the error cycle.</em></p><p>So, as we need two pages, I designed two HTML pages accordingly. For design purposes, I used <em>“Bootstrap”</em>. Well, Bootstrap is an open-source Front-End framework used to create websites and web apps. It contains various HTML, CSS and JavaScript-based design templates for UI interface elements such as Buttons and Forms etc.</p><p>So, here is my first web page HTML file named home.html:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c2a946bc2e61ad0625228127ced0a83/href">https://medium.com/media/4c2a946bc2e61ad0625228127ced0a83/href</a></iframe><p>Notice on the third line, bootstrap link for the design is used (CSS based template).</p><p>And here is the second page HTML file, saved as predict.html:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddc44cd13adb254165520d3e61a6f3e/href">https://medium.com/media/4ddc44cd13adb254165520d3e61a6f3e/href</a></iframe><p>Here both CSS and JavaScript templates are used.</p><blockquote><strong>Compilation and Deployment</strong></blockquote><p>Our model is ready, functions are ready, templates are also ready. Now it’s time to compile all those things and enjoy the magic.</p><p>First, we run the Flask:-</p><pre>app = Flask(__name__)</pre><p>Then we load the model by calling the function:-</p><pre>get_model()</pre><p>And now we call both the pages along with functions and templates:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b35ed0732beb165fae60ab9f7ffaf0dd/href">https://medium.com/media/b35ed0732beb165fae60ab9f7ffaf0dd/href</a></iframe><p>Well, now its time for the final step i.e. to run everything and to generate URL:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xHq8xzxmHkLMqumfiuY8w.png" /></figure><p>Now a URL is generated (notice in blue). Click on it and we will get our first page like this:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpgyF9T_a3nJYGDmIyMa1Q.png" /></figure><p>Then we choose the image file which we want to check and then click upload. After pressing the upload button, it redirects to the next page with url+”/predict”. It will show the image with the result:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EOZl71sjRHyrvu3lc9LFQ.png" /></figure><p>Here we are with the final result. So, the implementation of a Deep Learning model-based Web Application for defect detection in PCB is hereby successful.</p><p><strong>You can clone the repository by:-</strong></p><pre>git clone <a href="https://github.com/utk-ink/Defect-Detection-of-PCB.git">https://github.com/utk-ink/Defect-Detection-of-PCB.git</a></pre><p>Or</p><p><strong>Here is my GitHub’s link for the whole code</strong>:-</p><p><a href="https://github.com/utk-ink/Defect-Detection-of-PCB">GitHub - utk-ink/Defect-Detection-of-PCB: A repository or creating a Deep Learning model for Defect Detection in PCB and to design a Web Application for it.</a></p><p><em>Hope you liked it!!!</em></p><blockquote><em>Well, this blog is not monetized, I just wanted to share my knowledge in the best possible way. Please do give Claps, Follow and Share as it motivates me to write more. Thank You!!</em></blockquote><p><em>References:-</em></p><ol><li><a href="https://deeplizard.com/learn/video/XgzxH6G-ufA">https://deeplizard.com/learn/video/XgzxH6G-ufA</a></li><li><a href="https://github.com/Charmve/Surface-Defect-Detection/tree/master/DeepPCB">https://github.com/Charmve/Surface-Defect-Detection/tree/master/DeepPCB</a></li><li><a href="https://arxiv.org/abs/1704.04861">https://arxiv.org/abs/1704.04861</a></li><li><a href="https://machinelearningmastery.com/how-to-stop-training-deep-neural-networks-at-the-right-time-using-early-stopping/">https://machinelearningmastery.com/how-to-stop-training-deep-neural-networks-at-the-right-time-using-early-stopping/</a></li><li><a href="https://towardsdatascience.com/transfer-learning-using-mobilenet-and-keras-c75daf7ff299">https://towardsdatascience.com/transfer-learning-using-mobilenet-and-keras-c75daf7ff299</a></li><li><a href="https://keras.io/api/callbacks/reduce_lr_on_plateau/">https://keras.io/api/callbacks/reduce_lr_on_plateau/</a></li><li><a href="https://www.kaggle.com/uysimty/get-start-image-classification">https://www.kaggle.com/uysimty/get-start-image-classification</a></li><li><a href="https://getbootstrap.com/docs/5.0/getting-started/introduction/">https://getbootstrap.com/docs/5.0/getting-started/introduction/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2b26039924a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-classification-of-pcbs-and-its-web-application-flask-c2b26039924a">Image Classification of PCBs and its Web Application (Flask)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer Neural Network: Step-By-Step Breakdown of the Beast.]]></title>
            <link>https://medium.com/data-science/transformer-neural-network-step-by-step-breakdown-of-the-beast-b3e096dc857f?source=rss-5e573e9d7364------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e096dc857f</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nmt]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Utkarsh Ankit]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 22:57:06 GMT</pubDate>
            <atom:updated>2021-09-15T10:19:17.429Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Transformer Neural Network: Step-By-Step Breakdown of the Beast</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHEDS7vGKgSEUcxIsuwnDg.jpeg" /><figcaption>source: <a href="https://unsplash.com/@tetrakiss">arseny togulev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">unsplash</a>.</figcaption></figure><p>The Transformer Neural Network is a novel architecture that aims to solve sequence-to-sequence tasks while handling long-range dependencies with ease. It was proposed in the paper <em>“Attention Is All You Need”</em> 2017 [1]. It is the current state-of-the-art technique in the field of NLP.</p><p>Before directly jumping to Transformer, I will take some time to explain the reason why we use it and from where it comes into the picture. (If you want to skip this part then directly go to the Transformer topic, but I suggest you read it sequentially for better understanding).</p><p>So, the story starts with RNN (Recurrent Neural Networks).</p><h3><strong>RNN</strong></h3><p>What is RNN? How is it different from simple ANN? What is the major difference?</p><p>RNNs are the Feed Forward Neural Networks that are rolled out over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jqTs74Y4p0RFGqLu" /><figcaption>source: <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">colah’s</a> (CC0).</figcaption></figure><p>Unlike normal Neural Networks, RNNs are designed to take a <strong>series of inputs</strong> with <em>no predetermined limit on size</em>. “Series” as in any input of that sequence has some relationship with their neighbour’s or have some influence on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QzEB7hFdwO6GcoWe" /><figcaption>Architecture of RNN. source: <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">colah’s</a> (CC0).</figcaption></figure><p>Basic feedforward networks “remember” things too, but they remember the things they learnt during training. While RNNs learn similarly while training, in addition, they remember things learnt from prior input(s) while generating output(s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*86jAcbFokk9CIhI0" /><figcaption>Image illustrating long-term dependencies. source: <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">colah’s</a> (CC0).</figcaption></figure><p>It is used in different types of models-</p><p>1. ) <strong>Vector-Sequence Models-</strong> They take fixed-sized vectors as input and output vectors of any length, for example, in image captioning, the image is given as an input and the output describes the image.</p><p>2. ) <strong>Sequence-Vector Model-</strong> Take a vector of any size and output a vector of fixed size. Eg. Sentiment analysis of a movie rates the review of any movie as positive or negative as a fixed size vector.</p><p>3. ) <strong>Sequence-to-Sequence Model-</strong> The most popular and most used variant, take input as a sequence and give output as another sequence with variant sizes. Eg. Language translation, for time series data for stock market prediction.</p><p><strong>Its disadvantages-</strong></p><ol><li>Slow to train.</li><li>Long sequence leads to vanishing gradient or, say, the problem of long term dependencies. In simple terms, its memory is not that strong when it comes to remembering the old connection.</li></ol><p>For <strong>Eg</strong>. “The clouds are in the ____.”</p><p>It is obvious that the next word will be sky, as it is linked with the clouds. Here we see the distance between clouds and the predicted word is less so RNN can predict it easily.</p><p><em>But, for another example,</em></p><p>“I grew up in Germany with my parents, I spent many years and have proper knowledge about their culture, that’s why I speak fluent ____.”</p><p>Here the predicted word is German, which is directly connected with Germany, but the distance between Germany and the predicted word is more in this case, so it is difficult for RNN to predict.</p><p><em>So, Unfortunately, as that gap grows, RNNs become unable to connect, as their memory fades with distance.</em></p><h3><strong>LSTM</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDMcH86nqNsizWSyJ5AhTg.png" /><figcaption>source: <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">colah’s</a> (CC0).</figcaption></figure><p><strong>Long Short Term Memory-</strong> Special kind of RNN, specially made for solving vanishing gradient problems. They are capable of learning Long-Term Dependencies. Remembering information for long periods of time is practically their default behaviour, not something they struggle to learn!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CocZ-4V4nNQ7bSE124praQ.png" /><figcaption>This branch allows to pass info and skip long processing of the cell. source: <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">colah’s</a> (CC0).</figcaption></figure><p>The LSTM Neurons have unlike normal neurons have a branch that allows to pass information and to skip the long processing of the current cell, this allows the memory to be retained for a longer period of time. It does improve the situation of the vanishing gradient problem but not that amazingly, like it will do good till 100 words, but for like 1,000 words, it starts to lose its grip.</p><p>But like simple RNN it is also very slow to train, or even slower.</p><p><strong>They take input sequentially one by one, which is not able to use up GPU’s very well, which are designed for parallel computation.</strong></p><p><strong>How can we parallelize sequential data?? </strong><em>(I will get back on this question.)</em></p><p>For now, we are dealing with two issues-</p><ul><li>Vanishing gradient</li><li>Slow training</li></ul><p><em>Solving the vanishing gradient issue:</em></p><h3><strong>Attention</strong></h3><p><em>It answers the question of what part of the input we should focus on.</em></p><p>I am going to explain attention in a slightly different way. Let’s take a situation-</p><p>Suppose someone gave us a book of machine learning and asked us to give information about categorical cross-entropy. There are two ways of doing it, first, read the whole book and come back with the answer. Second, go to the index, find the ‘losses’ chapter, go to the cross-entropy part and read the part of Categorical Cross Entropy.</p><p><em>What do you think is the faster method?</em></p><p>Like in the first method, it may take a whole week to read the entire book. While in second, it will hardly take 5 mins. Furthermore, our information from the first method will be more vague and diverse as it is based on too much information, while the information from the second one will be accurate to the requirement.</p><p><em>What did we do differently here?</em></p><p>In the former case we didn’t focus on any part of the book specifically, whereas in the latter case, we focused our attention on the chapter of losses and then further focused our attention on the cross-entropy part where the concept of Categorical Cross Entropy is explained. Actually, this is the way most of us humans will do.</p><p>Attention in neural networks is somewhat similar to what we find in humans. They focus on the high resolution in certain parts of the inputs while the rest of the input is in low resolution [2].</p><p>Let’s say we are making an NMT(Neural Machine Translator),</p><p>Check out this animation, this shows how a simple seq-to-seq model works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*RcAVEDw95NqRyDLG" /><figcaption>Working of a classic Seq-to-Seq model. source: <a href="https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">jalammar’s</a> (CC BY-NC-SA 4.0).</figcaption></figure><p>We see that for each step of the encoder or decoder, RNN is processing its inputs and generating output for that time step. In each time step, RNN updates its hidden state based on inputs and previous outputs it has seen. In the animation, we see that the hidden state is actually the <strong>context vector </strong>we pass along to the decoder.</p><p><em>Time for “Attention”</em>.</p><p>The <strong>context vector</strong> turned out to be problematic for these types of models. Models have a problem while dealing with long sentences. Or say they were facing the vanishing gradient problem in long sentences. So, a solution came along in a paper [2], Attention was introduced. It highly improved the quality of machine translation as it allows the model to focus on the relevant part of the input sequence as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hDtXaKPpgwe_u5h3" /><figcaption>Working of a Seq-to-Seq Model with Attention. source: <a href="https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">jalammar’s</a> (CC BY-NC-SA 4.0).</figcaption></figure><p>This attention model is different from the classic seq-to-seq model in two ways-</p><ul><li>As compared to a simple seq-to-seq model, here the encoder passes a lot more data to the decoder. Previously only the last, final hidden state of the encoding part is sent to the decoder, but now the encoder passes all the hidden states (even the intermediate ones) to the decoder.</li><li>The decoder part does an extra step before producing its output. Explained below-</li></ul><p>The last step of decoders proceed as follow-</p><ol><li>It checks each hidden state that it received as every hidden state of the encoder is mostly associated with a particular word of the input sentence.</li><li>I give each hidden state a score.</li><li>Then each score is multiplied by their respective softmax score, thus amplifying hidden states with high scores, and drowning out hidden states with low scores. <em>(Refer to the image below for clear visualization.)</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvYljx-LQqKDKLXN0njscw.png" /><figcaption>source: <a href="https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">jalammar’s</a> (CC BY-NC-SA 4.0).</figcaption></figure><p>This scoring exercise is done at each time step on the decoder side.</p><p>Now when we bring the whole thing together:</p><ol><li>The attention decoder layer takes the embedding of the &lt;END&gt; token, and an initial decoder hidden state, the RNN processes its inputted and produces an output and a new hidden state vector(h4).</li><li>Now we use encoder hidden states and the h4 vector to calculate a context vector C4 for this time step. This is where the attention concept is applied, that’s why it’s called the Attention Step.</li><li>We concatenate (h4) and C4 in one vector.</li><li>Now, this vector is passed into a feed-forward neural network, the output of the feed-forward neural networks indicates the output word of this time step.</li><li>These steps get repeated for the next time steps. <em>(Refer to the slide below for clear visualization.)</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*YQVijtlIDzJZp4EZaOJPiQ.gif" /><figcaption>The Final Step. source: <a href="https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">jalammar’s</a> (CC BY-NC-SA 4.0).</figcaption></figure><p>So, this is how <strong>Attention</strong> works.</p><p><em>Eg. Working of Attention In an Image Captioning Problem:-</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRkkcLzdicqmazHmGW4qDA.png" /><figcaption>Working of attention in an Image Captioning Problem. source: <a href="https://www.youtube.com/channel/UC5_6ZD6s8klmMu9TXEB_1IA">CodeEmporium</a> (CC0).</figcaption></figure><p>Now, remember the question which I stated earlier-</p><p><strong>How can we parallelize</strong> <strong>sequential data??</strong></p><p><em>So, here comes our ammunition-</em></p><h3><strong>Transformers</strong></h3><p>A paper called <em>“Attention Is All You Need”</em> published in 2017 comes into the picture, it introduces an encoder-decoder architecture based on attention layers, termed as the transformer.</p><p>One main difference is that the input sequence can be passed parallelly so that GPU can be utilized effectively, and the speed of training can also be increased. And it is based on the multi-headed attention layer, vanishing gradient issue is also overcome by a large margin. The paper is based on the application of transformer on NMT(Neural Machine Translator).</p><p>So, here both of our problems which we highlighted before are solved to some level here.</p><p>Like for example in a translator made up of simple RNN we input our sequence or the sentence in a continuous manner, one word at a time to generate word embeddings. As every word depends on the previous word, its hidden state acts accordingly, so it is necessary to give one step at a time. While in transformer, it is not like that, we can pass all the words of a sentence simultaneously and determine the word embedding simultaneously. So, how it is actually working, let’s see ahead-</p><h3>The architecture:-</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*57LYNxwBGcCFFhkOCSnJ3g.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><blockquote><strong>1. Encoder Block -</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_S-hDPoTrro9jVEaQ9QGg.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>It’s a fact that computers don’t understand words, it works on numbers, vectors or matrices. So, we do need to convert our words to a vector. But how this can be possible. So, here the concept of <strong>Embedding Space</strong> comes. It’s like an open space or dictionary where words of similar meanings are grouped together or are present close to each other in that space. This space is termed as embedding space, and here every word, according to its meaning, is mapped and assigned with a particular value. So, here we convert our words to vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXmQpyCLRg9LvVrl5t4r0w.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>But one other issue we will face is that every word in different sentences has different meanings. So, to solve this issue, we take the help of <strong>Positional Encoders</strong>. It is a vector that gives context according to the position of the word in a sentence.</p><p>Word → Embedding → Positional Embedding → Final Vector, termed as Context.</p><p>So, our input is ready, now it goes to the encoder block.</p><blockquote>Multi-Head Attention Part -</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCkUHvHKXqSrjhHDIeFJcg.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now the main essence of the transformer comes in, “Self Attention”.</p><p>It focuses on the part that how relevant a particular word is w.r.t to other words in that sentence. It is represented as an attention vector. For every word, we can have an attention vector generated, which captures the contextual relationship between words in that sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4_5Ko6KF7mpAkMddl0xTQ.png" /><figcaption>source: <a href="https://www.youtube.com/channel/UC5_6ZD6s8klmMu9TXEB_1IA">CodeEmporium</a> (CC0).</figcaption></figure><p>The only problem it faces is that for every word it weighs its value much higher on itself in the sentence, be we are inclined towards its interaction with other words of that sentence. So, we determine multiple attention vectors per word and take a weighted average, to compute the final attention vector of every word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfZ_wwjgBWc1oVT4rjgvtg.png" /><figcaption>source: <a href="https://www.youtube.com/channel/UC5_6ZD6s8klmMu9TXEB_1IA">CodeEmporium</a> (CC0).</figcaption></figure><p>As we are using multiple attention vectors, it is called the <strong>Multi-Head Attention Block</strong>.</p><blockquote>Feed Forward Network -</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fR29iavEh9mUTpsrSM5jsg.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now, the second step is the Feed Forward Neural Network. This is the simple feed-forward Neural Network that is applied to every attention vector, it’s the main purpose is to transform the attention vectors into a form that is acceptable by the next encoder or decoder layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFh7JcoT4OV92I5yK_rSEw.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Feed Forward Network accepts attention vectors “one at a time”. And the best thing here is unlike the case of RNN, here each of these attention vectors is <em>independent</em> of each other. So, <strong>parallelization</strong> can be applied here, <em>and that makes all the difference</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-MZxgrhow4FN6KwOZ7Pzg.png" /><figcaption>Encoder’s Output. source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now we can pass all the words at the same time into the encoder block, and get the set of Encoded Vectors for every word simultaneously.</p><blockquote><strong>2. Decoder Block -</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fz_La3lCDLl6LEfyMdqSxg.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now, like if we are training a translator for English to the French language, so for training we need to give an English sentence along with its translated French sentence for the model to learn. So, our English sentences pass through Encoder Block, and French sentences pass through the Decoder Block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tFNp4C2PBagioCYjncQ5A.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>At first, we have the Embedding layer and Positional encoder part which changes the words into respective vectors, It is similar to what we have seen in the Encoder part.</p><blockquote>Masked Multi-Head Attention Part -</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzOY4tcBltlSbaaOQK_rwQ.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now it will pass through the self-attention block, where attention vectors are generated for every word in French sentences to represent how much each word is related to every word in the same sentence. (Just like we saw in Encoder Part).</p><p>But this block is called the <strong>Masked Multi-Head Attention Block</strong>, and I am going to explain in simple terms-</p><p>For that, we need to know how the learning mechanism works. First, we give an English word, it will translate in its French version itself<em> </em>using previous results, then it will match and compare with the actual French translation (which we fed in the decoder block). After comparing both, it will update its matrix value. This is how it will learn after several iterations.</p><p>What we observe is that we need to hide the next French word, so that at first it will predict the next word itself using previous results, without knowing the real translated word. For learning to take place, it will make no sense if it already knows the next French word. Therefore, we need to hide (mask) it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtMxxJk_U9-LpY_B_kebmw.png" /><figcaption>This is an example of English-French Translation. source: <a href="https://www.youtube.com/channel/UC5_6ZD6s8klmMu9TXEB_1IA">CodeEmporium</a> (CC0).</figcaption></figure><p>We can take any word from the English sentence, but we can only take the previous word of the French sentence to learn. So, while performing the parallelization with matrix operation, we make sure that the matrix should <strong>mask</strong> the words appearing later by transforming them into 0’s so that the attention network can’t use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIvtcMbsjDZoa-v1_4Po7g.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now, the resulting attention vectors from the previous layer and the vectors from the Encoder Block are passed into another <strong>Multi-Head Attention Block</strong>. (<em>this part is where the results from the encoder block also come into the picture. In the diagram also it is clearly visible that the results from the Encoder blocks are coming here.</em>). That’s why it is called <strong>Encoder-Decoder Attention Block</strong>.</p><p>As we have one vector of every word for each English and French sentence. This block actually does the mapping of English and French words and finds out the relation between them. So, this is the part where the main English to French word mapping happens.</p><p>The output of this block is attention vectors for every word in English and French sentences. <em>Each vector represents the relationship with other words in both languages</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zB4o7DxUQn3hAP5OTDm6xA.png" /><figcaption>source: <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a><strong> [cs.CL].</strong></figcaption></figure><p>Now we pass each attention vector into a feed-forward unit, it will make the output vectors form into something which is easily acceptable by another decoder block or a linear layer.</p><p>A linear layer is another feed-forward layer. It is used to expand the dimensions into numbers of words in the French language after translation.</p><p>Now it is passed through a Softmax Layer, which transforms the input into a probability distribution, which is human interpretable.</p><p><em>And the resulting word is produced with the highest probability after translation.</em></p><p>Below is the example that was illustrated in <em>Google’s AI Blog [6]</em>, I put it here for your reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*AZIQTo-OeAzuAIXm" /><figcaption>Overview - Working of Transformer Network. source: <a href="https://ai.googleblog.com/2017/08/transformer-novel-neural-network.html">Google AI</a> (CC0).</figcaption></figure><p>The Transformer starts by generating initial representations, or embeddings, for each word. These are represented by the unfilled circles. Then, using self-attention, it aggregates information from all of the other words, generating a new representation per word informed by the entire context, represented by the filled balls. This step is then repeated multiple times in parallel for all words, successively generating new representations.</p><p>The decoder operates similarly, but generates one word at a time, from left to right. It attends not only to the other previously generated words but also to the final representations generated by the encoder.</p><p>So, this is how the transformer works, and it is now the state-of-the-art technique in NLP. It is giving wonderful results, using a <strong><em>self-attention mechanism</em></strong> and also solves the parallelization issue. Even Google uses <strong>BERT</strong> that uses a transformer to pre-train models for common NLP applications.</p><blockquote><strong>References -</strong></blockquote><ol><li><a href="https://arxiv.org/abs/1706.03762"><em>Attention is all you need</em>; Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin.</a></li><li><a href="https://arxiv.org/abs/1508.04025"><em>Effective Approaches to Attention-based Neural Machine Translation</em>; Minh-Thang Luong, Hieu Pham, Christopher D. Manning.</a></li><li><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">Colah’s Blog.</a></li><li><a href="https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/">Jay Alammar’s Blog.</a></li><li><a href="https://www.youtube.com/channel/UC5_6ZD6s8klmMu9TXEB_1IA">CodeEmporium : Youtube.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e096dc857f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transformer-neural-network-step-by-step-breakdown-of-the-beast-b3e096dc857f">Transformer Neural Network: Step-By-Step Breakdown of the Beast.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple guide for creating Virtual Environment in Jupyter Notebook(Python) for Windows.]]></title>
            <link>https://utkarsh-ankit.medium.com/a-simple-guide-for-creating-virtual-environment-in-jupyter-notebook-python-for-windows-1649041aaae1?source=rss-5e573e9d7364------2</link>
            <guid isPermaLink="false">https://medium.com/p/1649041aaae1</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[anaconda]]></category>
            <category><![CDATA[installation]]></category>
            <dc:creator><![CDATA[Utkarsh Ankit]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 11:06:20 GMT</pubDate>
            <atom:updated>2021-09-15T10:18:10.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>A simple guide for creating Virtual Environment in Jupyter Notebook(Python) for Windows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGVHRIgWa-nZQafFpABupA.jpeg" /><figcaption>source: <a href="https://unsplash.com/@markusspiske">markus spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">unsplash</a>.</figcaption></figure><p>Sometimes there are situations where we need to develop our code in some different conditions according to certain requirements. Like for example, we are working on Python3 but in some cases, we need to use Python2. Or we need to use some library that only supports certain python versions. We can also make our customized environment for particular needs and put all the required libraries installed in that environment only. Sometimes this turns out to be very helpful.</p><p>But creating it on jupyter notebook is not a smooth process that can work without error. This guide will help you to create your virtual environment in a simple way:-</p><p><em>(I am assuming that you have already using Anaconda based Jupyter Notebook environment, if not download it from </em><a href="https://www.anaconda.com/distribution/#download-section"><em>here</em></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tp1H8OTwmsKArqv0qQ3lbA.png" /></figure><p>Now for creating a virtual environment:-</p><ol><li>Make sure you have to have good internet connectivity.</li></ol><p>2. Open Anaconda Prompt (let’s assume we are making a virtual environment for python 3.5.0, naming it as ‘NewEnv’) and write-</p><blockquote>conda create--name NewEnv python=3.5.0</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lY3OjGOn6j8NaT0-noM-2Q.png" /></figure><p>let it download for some time.</p><p>3. After that write:-</p><blockquote>conda activate NewEnv</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1lOvF1tZ9c_8tK_jxmmww.png" /></figure><p>Now your new environment is successfully created and activated, its name is ‘NewEnv’.</p><p>4. Now after activating it, write:-</p><blockquote>pip install ipykernel</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ctHug3zCRU16H9LlYyNzhw.png" /></figure><p>5. Let it download and install for some time. Then after that write:-</p><blockquote>python -m ipykernel install --user --name=NewEnv</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*hq-wZy__Tld7EanVfchqdQ.png" /></figure><p>Now the new environment has been installed in the Jupyter notebook.</p><p>6. Install all the required libraries in your new environment.</p><p>7. To deactivate or get back to the base environment, just write:-</p><blockquote>conda deactivate</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*WCyg8L6RjUrHL_nvOGFBxQ.png" /></figure><p>8. Now check that your new virtual environment is installed in Jupyter Notebook or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGGifLJi_zWwQhtl-R7r2g.png" /></figure><p>If it is showing in the New option then it is successfully installed in your Jupyter Notebook.</p><p>9. If it is not showing then check all the steps and try again.</p><p>10. If you want to install any library in that environment, then just go to anaconda prompt, activate your environment (shown in step-3), then install your required library using <em>‘pip’</em> or <em>‘conda’. </em>Then it will work fine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1649041aaae1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Segmentation of Aerial images Using Deep Learning]]></title>
            <link>https://medium.com/data-science/semantic-segmentation-of-aerial-images-using-deep-learning-90fdf4ad780?source=rss-5e573e9d7364------2</link>
            <guid isPermaLink="false">https://medium.com/p/90fdf4ad780</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <dc:creator><![CDATA[Utkarsh Ankit]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 17:29:58 GMT</pubDate>
            <atom:updated>2021-09-15T08:54:01.638Z</atom:updated>
            <content:encoded><![CDATA[<h3>Semantic Segmentation of Aerial Images Using Deep Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1bweyLpi0s5lliA0SyoNg.jpeg" /><figcaption>source: <a href="https://unsplash.com/@matheenfaiz">matheen faiz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">unsplash</a>.</figcaption></figure><p>Pixel-wise image segmentation is a challenging and demanding task in computer vision and image processing. This blog is about segmentation of Buildings from Aerial (satellite/drone) images. Availability of high-resolution remote sensing data has opened up the possibility for interesting applications, such as per-pixel classification of individual objects in greater detail. By the use of Convolution Neural Network (CNN), segmentation and classification of images has becomes very efficient and smart. Here in this paper, we have used images of very high resolution and size therefore images were cropped and their size was reduced, so that processing could be easily done in a moderate level computer with normal specifications. This model is inspired from UNET Model which is widely used for the network whose output is of same format as the input. This model is generally used in medical science fields to detect anomalies in medical images like for findings fractures or tumors. Fine-tuning or Transfer learning is also used to improve the accuracy of the model. Fine-tuning the hyperparameters can help to improve learning of the model as the encoder of previously trained model is used. To train our model for different challenging situations, so that our model can produce a more accurate result, we used Data Augmentation i.e. to take one image and make some changes in it like changing of hue, saturation, brightness values, zooming and changing angles, rotation etc to provide wide situations for training, this also helps in the situations where there is a less or inadequate number of training data. Overall this model is able to get high accuracy result after full training of data.</p><h4>What is Semantic Segmentation?? What are its Practical Applications??</h4><p>Semantic segmentation of drone images to classify different attributes is quite a challenging job as the variations are very large, you can’t expect the places to be same. And doing manual segmentation of this images to use it in different application is a challenge and a never-ending process. So, there is a requirement for automation and a smart system which automatically do our job. So, here comes the Neural Network in the play. These days the application of Neural Network and deep learning in different fields is reaching heights, the interesting and smart approach to solve the challenging problem are attracting the attention of people of different fields. So, to solve this problem through applying the concepts of neural networks is a bit challenging task because of irregularity of data.</p><p>Convolutional Neural Network (CNN), is the deep learning concept which deals with images. In normal neural network operations, every node is connected with each other, creating a complex network, but if we apply the same thing in the images (which is a large matrix in itself), things will not work so well, because each pixel acts as a node there, and when these millions of pixels get connected with another layer, there will be millions or billions of connections, so the computation is too complex in that case, so a new way is created for images, which we call as Convolutional Neural Network. Here the concept is basically we convolve the images to another layers.</p><p>This program can be implemented in various commercial purposes, for example: drones are emerging as a new widely used tech that have wide range of implementation like to inspect any area or to deliver product, so this program helps to locate the exact location and increases accuracy. By detecting the buildings automatically we can use the data to predict population density or to calculate area of residential, commercial or uninhabited lands. Online Maps are widely used technology these days, by detecting attributes like buildings automatically it becomes easy to visualize a particular area in the map, this can have multiple applications like labeling the areas or to create a 3-D model of buildings using the map. Another major application of this project is that it is very useful in disaster management, like if a place got hit by disaster like earthquake or flood then aerial vehicles are used for rescuing or delivering foods, that can be done if buildings are located with high accuracy in less time. Furthermore there are many other applications of this in practical life which can also benefit the society and also for commercial purposes.</p><p>Using a neural network to create something automates the work which changes the conventional and slow way of doing things thereby producing high accuracy results which is both time and cost-saving without any hectic work; as aerial image segmentation is an important challenge and its practical applications are huge, automating it can be a good solution. The UNET model used here for semantic segmentation is inspired from Medical Science Field. The real application of UNET is for medical images i.e. to detect the anomalies like tumor or fracture etc when compared to large dataset of normal images. As very high precision is required for these kind of sensitive jobs, so the layers of CNN are made deep to learn more important features. This point inspired us to use this model for aerial images as the differences between buildings are totally unique and there are many parameters and features to learn, high accuracy is also necessary if it is made for practical application.</p><h3>BASIC CONCEPTS/ TECHNOLOGY USED</h3><p><strong>Neural Networks-</strong> An Artificial Neural Network (ANN) is an information processing paradigm that is inspired by the way biological nervous systems, such as the brain, process information. The key element of this paradigm is the novel structure of the information processing system. It is composed of a large number of highly interconnected processing elements (neurons) working in unison to solve specific problems. ANNs, like people, learn by example. An ANN is configured for a specific application, such as pattern recognition or data classification, through a learning process. Learning in biological systems involves adjustments to the synaptic connections that exist between the neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*0Dx5J1HZNitAYxK7VZjI_A.png" /><figcaption>Fig. A Simple Neural Network Architecture.</figcaption></figure><p><strong>Convolutional Neural Network-</strong> U-Net architecture consists of a contracting path to capture context and of a symmetrically expanding path that enables precise localization . The contracting path follows the typical architecture of a convolutional network with alternating convolution and pooling operations and progressively down-samples feature maps, increasing the number of feature maps per layer at the same time. Every step in the expansive path consists of an up-sampling of the feature map followed by a convolution.</p><p>U-Net is capable of learning from a relatively small training set. In most cases, data sets for image segmentation consist of at most thousands of images, since manual preparation of the masks is a very costly procedure. Typically U-Net is trained from scratch starting with randomly initialized weights. It is well known that training network without over-fitting the dataset should be relatively large, millions of images. Networks that are trained on the Image-net data set are widely used as a source of the initialization for network weights in other tasks. In this way, the learning procedure can be done for non-pre-trained several layers of the network (sometimes only for the last layer) to take into account features of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*cDh3kfWF1ozWkmeyLgxfFA.png" /><figcaption>Fig. A Simple Convolutional Network Structure.</figcaption></figure><p><strong>UNET Model</strong>- U-Net architecture consists of a contracting path to capture context and of a symmetrically expanding path that enables precise localization . The contracting path follows the typical architecture of a convolutional network with alternating convolution and pooling operations and progressively down-samples feature maps, increasing the number of feature maps per layer at the same time. Every step in the expansive path consists of an up-sampling of the feature map followed by a convolution.</p><p>UNET is capable of learning from a relatively small training set. In most cases, data sets for image segmentation consist of at most thousands of images, since manual preparation of the masks is a very costly procedure. Typically U-Net is trained from scratch starting with randomly initialized weights. It is well known that training network without over-fitting the dataset should be relatively large, millions of images. Networks that are trained on the Image-net data set are widely used as a source of the initialization for network weights in other tasks. In this way, the learning procedure can be done for non-pre-trained several layers of the network (sometimes only for the last layer) to take into account features of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*SVRlEMUBWQXHVjuJgDfaDA.png" /><figcaption>Fig. A Simple U-NET Structure.</figcaption></figure><p><strong>Fine-Tuning with VGG-16 encoders (pre-trained on image-net)</strong>- As an encoder in our U-Net network, we used relatively simple CNN of the VGG family that consists of 11sequential layers and known as VGG16. VGG16 contains seven convolutional layers, each followed by a ReLU activation function, and five max polling operations, each reducing feature map by2. All convolutional layers have3×3kernels. The first convolutional layer produces 64 channels and then, as the network deepens, the number of channels doubles after each max pooling operation until it reaches 512. On the following layers, the number of channels does not change. To construct an encoder, we remove the fully connected layers and replace them with a single convolutional layer of 512 channels that serves as a bottleneck central part of the network, separating encoder from the decoder.</p><p>To construct the decoder we use transposed convolutions layers that doubles the size of a feature map while reducing the number of channels by half. And the output of a transposed convolution is then concatenated with an output of the corresponding part of the decoder. The resultant feature map is treated by convolution operation to keep the number of channels the same as in a symmetric encoder term. This up-sampling procedure is repeated 5 times to pair up with 5 max-poolings. Technically fully connected layers can take an input of any size, but because we have 5 max-pooling layers, each down-sampling an image two times, only images with a side divisible by 32 can be used as an input to the current network implementation.</p><h3>PROPOSED MODEL / TOOL</h3><p><strong>Dataset</strong>- I applied my model to Iniria Aerial Image Labeling Dataset. This dataset consists of 180 aerial images of urban settlements in Europe and United States, and is labeled as a building and not building classes. Every image in the data set is RGB and has 5000×5000 pixels resolution where each pixel corresponds to a 30cm×30cm of Earth surface. But we can’t put this much size image directly into our code, so we need to take crops of those images. The resolution of each cropped image must be divisible by 32. So, I took 512x512 resolution crops of those images and then use it in my algorithm. First I tried it by using Bilinear Interpolation on that images to resize it but the technique failed to keep the important details of the images, so I just cropped it normally. From the total dataset 80% of images are taken as test data and rest 20% are taken as validation set.</p><p><strong>Platform and Software Requirement-</strong></p><p>- Python 3.5 in Jupyter Notebook is used for coding purposes(Anaconda Environment).</p><ul><li>Keras with Tensorflow (backend) is used to develop the code.</li></ul><p><strong>Image Augmentation and Image Data Generator</strong>- Image augmentation artificially creates training images through different ways of processing or a combination of multiple processing, such as random rotation, shifts, shear and flips, etc. In Keras there is a predefined function called image data generator which is specifically used for that purpose only. I rotated it, taken the zoom of random images of my data set. This helps in creating a model that is smarter to recognize the buildings in different situations. And it also increases the number of images in data which directly proportional to the good prediction of result.</p><p><strong>UNET Model with pre-trained vgg16 encoder</strong>- I used the pre-trained weights for fine-tuning my model. A pre-trained model is trained on a different task than the task at hand but provides a very useful starting point because the features learned while training on the old task are useful for the new task. I have taken the encoder part of vgg16 and put the weights of it that are “pre-trained on image-net” by using the same names. Then I created the decoding layers according to the structure of encoded layers by up-sampling it correspondingly and “concatenate” the layers to their respective encoding layers. Then I have taken the activation function to be “Adam” and loss as “Binary Cross Entropy”.</p><p><strong>Iterations</strong>- The number of Iterations/Epochs is taken to be 100 by me. And step_per_epoch which is equal to test images divided by batch size taken, is used correspondingly. The same is applicable for the validation set also.</p><h3>IMPLEMENTATION AND RESULTS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*AGIUV_K9Q7v0b42dwJbyfw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*mD81nMfbrkduqiIF-g05hQ.jpeg" /><figcaption>raw image(left)………………………………………………………………………………….. processed image(right)</figcaption></figure><h3>Advantages and Disadvantages</h3><p><strong>Advantages-</strong></p><p>• It is a very efficient and easy technique to get the result with high accuracy.</p><p>• It is a latest and improving technique which is regularly updated so, that we can have a better model in future.</p><p>• You can get high accuracy in very little data.</p><ul><li>It is easy to learn and implement</li></ul><p><strong>Disadvantages-</strong></p><p>• Very high computational power is required for it, which makes it a bit costly procedure.</p><p>• High end GPU (Graphics Processing Unit) is a prerequisite otherwise it will take too much time too train.</p><p>• Boundary part sometimes of some labelled images are not too sharp, but this can solved by using large dataset or by applying CRF (Conditional Random Fields).</p><p>• Hyper-parameters tuning is a time taking process.</p><h3>Conclusion</h3><p>So, I conclude that by using UNET, pre-trained VGG-16 as a encoder we get high accuracy with very limited data-set. I tried just by taking 200 images and its accuracy reached till 98.5% after training. I also tried by taking different number of data to check the result like 2000 images, 6000 images and the results are satisfactory. As its learning is directly proportional to number of data, so providing with large data helps to get a smart learning and better results. I also applied image augmentation, which also helps to get a better result by increasing quality of training dataset. So, overall it is a very efficient technique for image segmentation to extract features like buildings in Aerial Images.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90fdf4ad780" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/semantic-segmentation-of-aerial-images-using-deep-learning-90fdf4ad780">Semantic Segmentation of Aerial images Using Deep Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>