<?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 Luhar Ayush on Medium]]></title>
        <description><![CDATA[Stories by Luhar Ayush on Medium]]></description>
        <link>https://medium.com/@ayushjluhar?source=rss-d582d50c17b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZLlCrZ2_hzHVJJtHt5pQUA.jpeg</url>
            <title>Stories by Luhar Ayush on Medium</title>
            <link>https://medium.com/@ayushjluhar?source=rss-d582d50c17b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:16:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayushjluhar/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[Why Traditional Metrics Fail in Image Binarization]]></title>
            <link>https://medium.com/@ayushjluhar/why-traditional-metrics-fail-in-image-binarization-28983e62476f?source=rss-d582d50c17b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/28983e62476f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Luhar Ayush]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 19:47:18 GMT</pubDate>
            <atom:updated>2025-04-29T19:47:18.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>OCR — Optical Character Recognition</h3><p>tech behind turning images of text into actual, editable text.<br>Best example: Google Lens!</p><p>But OCR has one annoying quirk: it’s kind of picky.</p><p>Sometimes, it will give great results, and sometimes it will turn “freedom” into “fneedom”(mainly happens when text is not machine written, and handwritten).<br>Before OCR can extract text from an image/file, there are some steps that need to be performed to clean the image, one of them is binarization.</p><h3>Binarization</h3><p>In short: It works like a clean-up crew, cleans all the messy grey area, shadows and paper texture, leaving just black text on a white background.<br>So, people starting from 1979, have been inventing different algorithms for binarization.</p><p>Now we have enough algorithms, but the real challenge is figuring out which one works best for your specific documents, it’s like how black is “black enough?”<br>That’s where evaluation metrics come in… and where things get messy again.</p><blockquote>Dilema: <strong>what looks good to a human often scores badly on the “official” metrics.</strong> And what passes the pixel test might completely fail at actually helping OCR.</blockquote><h3>So in this blog, we’ll cover:</h3><ul><li>Major Binarization Techniques</li><li>Evaluation metrics</li><li>Problems with the System of Evaluation</li></ul><h3>Binarization Techniques</h3><ul><li><strong>Otsu</strong> — “A threshold selection method from gray-level histograms”, 1979.</li><li><strong>Niblack</strong> — “An Introduction to Digital Image Processing”, 1986.</li><li><strong>Sauvola</strong> — “Adaptive document image binarization”, 1999.</li><li><strong>Wolf</strong> — “Extraction and Recognition of Artificial Text in Multimedia Documents”, 2003.</li><li><strong>NICK</strong> — “Comparison of Niblack inspired Binarization methods for ancient documents”, 2009.</li><li><strong>T.R. Singh</strong> — “A New local Adaptive Thresholding Technique in Binarization”, 2011.</li><li><strong>ISauvola</strong> — “ISauvola: Improved Sauvola’s Algorithm for Document Image Binarization”, 2016.</li><li><strong>WAN</strong> — “Binarization of Document Image Using Optimum Threshold Modification”, 2018.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yOhJSdHlpolr7AmK1i3kQ.jpeg" /><figcaption>This is the image that we want to binarize, it is called Ground Truth ImageN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-zdoF_crTTwNhiosCwuxQ.png" /><figcaption>This is the Binarization of Ground Truth Image, it is cropped to save space, it contains results from Otsu, Niblack, Sauvola,and Wolf</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*70L2lRM-ZAA6sp5tW4YkdA.png" /><figcaption>This is the Binarization of Ground Truth Image, it is cropped to save space, it contains results from NICK, T.R. Singh, ISauvola, and WAN</figcaption></figure><p>All this Techniques except Otsu, has some type of parameter, which will either increase or decrease the quality and noise in the image, like you can see in the Video below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*0mGIJJzJzUi_4beFq0vNTw.gif" /><figcaption>Effects on binarization when you change the parameter</figcaption></figure><p>Every method’s parameter has different range of parameter, and even at the same value of k-parameter every method’s result would vary.</p><p>The tricky part is that there’s no number where all these methods suddenly agree. They all behave a bit differently, even with the same parameters. So trying to evaluate them purely with math — no gut feeling, no human judgment — just doesn’t work. There’s always a bit of subjectivity sneaking in.</p><p>Still, even if they don’t always behave predictably, we can’t just throw up our hands and give up. So, let’s take a close look at evaluation techniques and observe — what they measure, what they miss, and why sometimes a “good” score doesn’t match what your eyes tell you. Let’s break it down.</p><h3>Evaluation Techniques</h3><p><strong>DRD — Distance Reciprocal Distortion</strong></p><p>DRD penalizes <em>visible mistakes</em> — like if a black pixel shows up in a white area or a gap appears in a stroke. It gives bigger penalties to errors near important visual structures (like text strokes) and smaller penalties to random noise in the background.</p><figure><img alt="DRD = \frac{1}{NUBN}\sum_{i=1}^{F}DRD_i" src="https://cdn-images-1.medium.com/max/342/1*KkVQl0ue6i1YRKzX9zqSYQ.png" /></figure><ul><li><strong>F</strong> = number of mismatched pixel</li><li><strong>DRD₍ᵢ₎</strong> = weighted distortion at pixel <em>i</em> (using a 5×5 distance map)</li><li><strong>NUBN</strong> = number of non-uniform 8×8 blocks in the ground truth (i.e., how much structure the image has)</li></ul><p><strong>PBC — Peak Signal-to-Background Classification</strong></p><p>PBC checks how clean your background is. It focuses on how many <em>false black pixels</em> you accidentally put into areas that should’ve been white.</p><figure><img alt="PBC=\frac{Number \space of \space background \space pixels \space misclassified \space as \space foreground}{Total\space number \space of \space pixels}​×100" src="https://cdn-images-1.medium.com/max/810/1*nBo2rAVA8KmW_qobD2yBKQ.png" /></figure><p>This is usually expressed as a <strong>percentage</strong> of background “leakage”.</p><p><strong>NRM — Negative Rate Metric</strong></p><p>NRM checks how many mistakes you made — both when you <strong>missed actual text</strong> and when you <strong>added fake text(or pixel).</strong></p><figure><img alt="NRM = \frac{1}{2} \cdot (\frac{\left| GT_{fg}-BW_{fg}\right|}{\left| GT_{fg}\right|} \cdot \frac{\left| GT_{bg}-BW_{bg}\right|}{\left| GT_{bg}\right|})" src="https://cdn-images-1.medium.com/max/1024/1*40wEbmpLSliujEnQ-ZXqig.png" /></figure><ul><li>GT = ground truth</li><li>BW = binarized image</li><li>fg = foreground(textual content)</li><li>bg = background(paper and blank areas)</li></ul><p><strong>MPM — Misclassification Penalty Metric</strong></p><p>MPM is like DRD’s sibling. It checks <em>how far off</em> your mistakes are. If your binarization misses a character stroke or adds noise in the wrong spot, MPM gives you a bigger penalty the farther that mistake is from where it <em>should</em> be. Some mistakes ruin character shapes more than others. MPM tries to capture how much a mistake actually damages the structure of the text.</p><p>It’s like you forget the dot on i(it’s bad), but how far have you put that dot(even worse).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnmdEE0y4CaHkPzmuHLZDQ.png" /></figure><ul><li>D = Total number of edge pixels in the ground truth.</li><li>FN = no. of False Negative(should be black → but you said white).</li><li>FP = no. of False Positive(should be white → but you said black).</li><li><strong>dFN(i)​</strong> = for each false negative pixel, distance to the nearest text edge pixel in ground truth.</li><li>dFP(j)= for each false positive pixel, distance to the nearest text edge pixel in ground truth.</li></ul><h3>Results</h3><p>And the results are…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9celYotcz3pZFw8l5fP54Q.png" /><figcaption>T.R Singh Performs best in DRD</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKB9QI5oF3y2k88t5B_PPQ.png" /><figcaption>Otsu Performs best in PBC</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9a0xcNlA6T5fozT2lv_RA.png" /><figcaption>Otsu Perform best in NRM</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eBN60-y-krFhAv4F2g-Lg.png" /><figcaption>Otsu Perform best in MPM</figcaption></figure><p>So overall Otsu performs best across all the metrics, so why is that a problem?</p><p>Take a quick look at Otsu, for example: i its DRD is 0.007209, and its MPM is 0.008349. Those numbers are pretty low, suggesting that Otsu isn’t making many big mistakes. But… does that mean it’s really the best?</p><p>Now, look at <strong>WAN</strong>. It’s a more sophisticated algorithm designed to handle complex document layouts. But, strangely, it scores much worse on DRD and PBC — <strong>0.042986</strong> and <strong>4.229428</strong>, respectively. These results suggest <strong>WAN</strong> is struggling, but in reality, it’s better at handling noisy or degraded documents. What gives? In Practice Otsu is not that great, but the metrics doesn’t penalize it for these subtleties, and on other hand WAN’s scores look worse, but it’s really just trying harder to get fine details right.</p><p>There’s more! These result can also change drastically depending on the parameters used in the binarization process. Adjusting things like window size, sensitivity, or thresholds can <em>completely shift</em> the outcome of an algorithm.The tricky part is that <strong>the “best” parameters are totally subjective</strong>. <br>What works well for one document type (say, a high-contrast text page) might completely fail on another (like a faded, handwritten page). There’s no universal formula for setting these parameters because different tasks, environments, and documents have different needs. You can’t define the “perfect” parameter combination mathematically for all situations — what’s optimal for OCR accuracy in one case might be awful in another.</p><blockquote>These pixel-based metrics treat every mistake the same, without considering the <em>context</em> of the document.</blockquote><ul><li><strong>False positives (FP)</strong> in a big area of blank space don’t matter as much to OCR accuracy as <strong>false negatives (FN)</strong> in the middle of a character. But the metrics don’t discriminate — they punish all errors equally.</li><li><strong>Background noise</strong> might look ugly on paper (pun intended), but it doesn’t always impact OCR’s ability to read text. The algorithms that deal with more complex layouts — like <strong>WAN</strong> — might get penalized for something that wouldn’t actually hurt OCR performance.</li></ul><h3>RANT</h3><p>And this — this right here… is exactly why we need a better way to measure performance.</p><p>We’ve got one metric strutting around like it’s God’s gift to thresholding,<br> another sulking in the corner because it only cares about background classification, and a couple more arguing over whether false positives are worse than false negatives.</p><p>Each of these metrics has tunnel vision.<br>DRD is obsessed with how far error are from where they “should” be.<br>PBC is like “I want a clean looking paper, that’s it!”<br>NRM doesn’t like suprises — right and left punishing every deviations.</p><p>And this is why we need a composite metric.</p><blockquote>One that doesn’t just count pixels, but <em>understands the stakes</em>.</blockquote><p>This ends the part 1 of the blog, in next part we will explore 2 composite metrics which have been researched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gS6-9mdjRxKVyxzG2Sl9bQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28983e62476f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Numerical vs. Analytical Gradients in Machine Learning]]></title>
            <link>https://medium.com/@ayushjluhar/numerical-vs-analytical-gradients-in-machine-learning-7581c33c1db1?source=rss-d582d50c17b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7581c33c1db1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neural-network-algorithm]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Luhar Ayush]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 21:29:01 GMT</pubDate>
            <atom:updated>2025-04-01T22:16:30.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a Gradient?</h3><p>Let’s say that you are a person who loves to see the sunrise, to do that, you have to climb the mountain, and it’s early morning in the dark, and the fog surrounds you, but time is of the essence, so you need to climb it as fast as possible. For that, you will take a special laser and point it to the top of the mountain to measure the steepness, and whichever has the highest steepness, you will go that way, so that you can climb the mountain before the sunrise.</p><p>Now imagine the reverse situation: you’re at the peak after enjoying the sunrise and need to descend quickly. You’d measure the steepest downward slope and follow it, allowing you to reach the bottom in the shortest time.</p><p><strong>This is exactly how gradient optimization works in machine learning:</strong></p><p>When training models, we’re trying to find the lowest point of an error function (the valley, not the peak). We want to minimize the “loss” — how wrong our predictions are.</p><p>The gradient tells us the direction of steepest increase. So, to minimize loss, we move in the opposite direction(to do that in math, we simply subtract the gradient from old weights).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/0*sjgDXoaIGUTdneqj.png" /><figcaption>Weight updation formula in backpropagation</figcaption></figure><h3>Why is the Simple (Numerical) Gradient Not Sufficient?</h3><p>It looks all perfect on paper, but in the real world, it has many limitations, even more true for deep learning.</p><ul><li><strong>Computational Cost:</strong> When the model scales to a billion parameters, the calculating cost of numerical gradient would require an enormous number of function evaluations, making training practically infeasible.</li><li><strong>Approximation Error:</strong> Numerical Gradients approximate the derivative using a finite difference, choosing a very small step size (h) to reduce error can introduce numerical instability and precision issues, making the results less reliable.</li></ul><p>More limitations would be clear as we will make a deep dive in types of gradients.</p><h3>Numerical Gradient</h3><p>Continuing with the hill analogy. You want to find the quickest way down, but you can’t see the terrain. So, you use a simple trick: take a small step in each direction (north, south, east, west), feel how much the ground slopes in each direction, and then move in the direction where the ground drops the most steeply. This is essentially what numerical gradient calculation does in neural networks.</p><p>Numerical gradients work by applying a small perturbation to each parameter and observing how much the function value changes. This gives us an approximation of the partial derivative with respect to that parameter.</p><p>Two-sided approximation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/0*bJHKF-uBhLQkQ7jV.png" /></figure><p>Where h is a small value (e.g., 1e-5).</p><pre>def numerical_gradient_multiple(f, weights, step_size=0.00001):<br>    gradients = np.zeros_like(weights)<br>    <br>    for i in range(len(weights)):<br>        weights_plus = weights.copy()<br>        weights_minus = weights.copy()<br>        <br>        weights_plus[i] += step_size<br>        weights_minus[i] -= step_size<br>        <br><br>        gradients[i] = (f(weights_plus) - f(weights_minus)) / (2 * step_size)<br>    <br>    return gradients<br></pre><p><strong>Here is a GIF created with Claude’s code where there are four side approximations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s33Koew4TyCRR2Q1a2vfwQ.gif" /><figcaption>Numerical Gradient Visualisation.</figcaption></figure><h3>Analytical Gradient</h3><p>Again with the hill analogy, but before, you didn’t know the whole path, you can know the path as you walk, but here it’s like you have special glasses that removes the need to take any experimental steps to find your way down, like with numerical gradient, your glasses instantly show you the exact steepest path downhill from your current position. This is what analytical gradients do — they provide the mathematically exact direction of steepest descent without any approximations.</p><p>Analytical gradients in neural networks are calculated using calculus, specifically through the chain rule of differentiation. Unlike numerical gradients, which approximate derivatives by taking small perturbations, analytical gradients yield exact derivatives through well-defined mathematical formulas.</p><p>In the context of a neural network with a loss function L and weights W, the analytical gradient for each weight wᵢⱼ​ is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*ofJnzIH17hmJ1WPd.png" /></figure><ul><li>aⱼ is the activation of neuron j.</li><li>zⱼ is the weighted input to neuron j.</li></ul><p><strong>For a simple neural network with:</strong></p><ul><li>Input x.</li><li>Weights w.</li><li>Activation function σ.</li><li>Output: ŷ = σ(w * x).</li><li>Loss function L(y, ŷ).</li></ul><p><strong>The analytical gradient is:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*i4T45jazS_fF31Kn.png" /></figure><p>Backpropagation is classified as an analytical gradient method.</p><pre>def analytical_gradient(X, y_true, weights, activation_derivative, loss_derivative):<br>    # Forward pass<br>    Z = X.dot(weights)  # Weighted input Z = W·X<br>    A = activation_function(Z)  # Activation output A = σ(Z)<br><br>    # Compute error<br>    dL_dA = loss_derivative(y_true, A)  # ∂L/∂ŷ<br>    dA_dZ = activation_derivative(Z)  # ∂ŷ/∂z<br>    dZ_dW = X  # ∂z/∂w = X<br><br>    # Backpropagation<br>    gradient = dZ_dW.T.dot(dL_dA * dA_dZ) / len(y_true)  # ∂L/∂w = ∂L/∂ŷ × ∂ŷ/∂z × ∂z/∂w<br>    return gradient</pre><p><strong>Here is a GIF created with Claude’s code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q_LHNT78UUWZieCUWME1Q.gif" /><figcaption>Analytical Gradient Visualisation.</figcaption></figure><h3>So which Gradient type to use?</h3><p><strong>Analytical Gradients</strong> are used for:</p><ul><li>Standard neural network training (backpropagation)</li><li>Production-level deep learning systems</li><li>Any application where computational efficiency is critical</li></ul><p><strong>Numerical Gradients</strong> are used for:</p><ul><li>Gradient checking (verifying analytical gradient implementations)</li><li>Prototyping and experimentation</li><li>Working with black-box optimization problems</li><li>Small-scale problems where implementation simplicity is preferred over speed</li></ul><p>In summary, <strong>numerical gradients are useful for debugging and validation</strong>, while <strong>analytical gradients (backpropagation) are essential for practical deep learning applications due to their efficiency and precision</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*yaI76OJ8D47DS1q4.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7581c33c1db1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>