<?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 Vineeth S Subramanyam on Medium]]></title>
        <description><![CDATA[Stories by Vineeth S Subramanyam on Medium]]></description>
        <link>https://medium.com/@vineeth2309?source=rss-4c59dbefc4cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5DGyvN0MX_oixqQJ.jpg</url>
            <title>Stories by Vineeth S Subramanyam on Medium</title>
            <link>https://medium.com/@vineeth2309?source=rss-4c59dbefc4cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:28:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vineeth2309/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[Activation Functions (Part 1)]]></title>
            <link>https://medium.com/analytics-vidhya/activation-functions-part-1-d80b0e8ee89d?source=rss-4c59dbefc4cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d80b0e8ee89d</guid>
            <category><![CDATA[neural-net]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[sigmoid]]></category>
            <category><![CDATA[tanh]]></category>
            <category><![CDATA[neural-network-algorithm]]></category>
            <dc:creator><![CDATA[Vineeth S Subramanyam]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 12:24:20 GMT</pubDate>
            <atom:updated>2021-03-15T16:10:02.201Z</atom:updated>
            <content:encoded><![CDATA[<p>An activation is a function applied to the output of a neuron that allows it to learn more complex functions as we go deeper in a neural network. They can also be thought of as mapping to modify the range of a function. For example we could use an activation function to ensure that all our outputs lie between 0 and 1, or between -1 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*2Ma2kdyPRjZ5Js59sZxjbg.png" /><figcaption>Figure 1: Expression for the output of a neuron, followed by applying an activation function</figcaption></figure><ul><li>The first equation in Figure 1 is the formula used to calculate the output of a neuron. The equation takes the form of a straight line y = mx + c</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*HFtL1iFBv1wDYAHVFBio3w.png" /><figcaption>Figure 2: Plot of the equation of y</figcaption></figure><ul><li>As we increase the number of layers of a neural network, we want to learn more complex features to better represent the data. If we were to use linear functions as activations in our neural network, learning more complex features becomes quite challenging. Looking at the figure below, it is difficult for us to split these points with a straight line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*Bs-tOAKqUl7cygXrvU_zWg.png" /><figcaption>Figure 3: Non Linear Features</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*n8okVmw6vPJ6Tytx8D48ug.png" /><figcaption>Figure 4: 2 Layer Neural Network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*6xX9BDUzBee1v_N1UeSo7Q.png" /><figcaption>Figure 5: Defining the terms used</figcaption></figure><ul><li>If we were to use a linear activation function like the equation defined in Figure 5, where f_activation = <strong>a*y</strong>, we could end up representing the entire network as a single layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*WS3MbVpuymG2DJV4S37KNQ.png" /><figcaption>Figure 6: Expanding the derivatives</figcaption></figure><ul><li>Going through the equations in Figure 6, <strong>y</strong> represents the final output of the network after the linear activation. <strong>x1</strong> represents the output of layer 1 after the linear activation.</li><li>We can now replace the <strong>x1</strong> term in the first equation with the expression for <strong>x1</strong> from the second equation, and then expand the equation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*PSuP6Pd_6JgLabiDNNLSgw.png" /><figcaption>Figure 7: Simplifying the dervatives</figcaption></figure><ul><li>After simplifying the equation, since a2 and a1 are constants, we can write <strong>a2*W2*a1*W1</strong> as a new weight matrix <strong>W3</strong>.</li><li>(<strong>a2*W2*a1*b1 + a2*b</strong>) in essence again represents a new matrix that could be a bias <strong>b3</strong>.</li><li>This would essentially mean that the last layer can be replaced by a single equation <strong>y = W3*x0 + b3</strong></li><li>This is one of the main reasons why a non linear activation function is used to break the direct linear relationship of input to output.</li></ul><h3><strong>Commonly used activations:</strong></h3><ul><li><strong>Sigmoid Function</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*YcpxHdJ2qXjtg8Xdd9cEmA.png" /><figcaption>Figure 8: Sigmoid Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*4pjjwMmt7iO0J23DHHE6dg.png" /><figcaption>Figure 9: Graph of sigmoid function, and its derivative</figcaption></figure><p><strong>Forward Pass of a Sigmoid Neuron:</strong></p><ul><li>The sigmoid function ranges from 0 to +1</li><li>If we analyze the sigmoid graph, for input values that are greater than 5, or less than -5, we get pretty much the same output. (i.e, we would nearly get the same output of 1 for an input of 10, 100, or 1000).</li><li>The presence of an exponent calculation in its formula also makes it slower to compute in comparision to some other activation functions, however that isnt a significant drawback.</li></ul><p><strong>Backward Pass of a Sigmoid Neuron:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*7zCe917iKj5YY6-TO6WbBA.png" /><figcaption>Figure 10: Derivative of Sigmoid Neuron</figcaption></figure><ul><li>This derivative can be re written as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Xkps8hAY1EyvtaMgr4z6FQ.png" /><figcaption>Figure 11: Simplified derivative of sigmoid neuron</figcaption></figure><ul><li>The graph of the derivative is represented by the backward plot in Figure 9</li><li>Looking at the graph, we can see that just how the forward pass saturates at higher values, the derivative also saturates at higher values. This is because the gradient in the function at higher values is negligible, leading to a derivative of almost 0 at higher values. This is commonly called the <strong>vanishing gradient</strong> problem.</li><li>Once the weight of a layer using a sigmoid neuron becomes too large in magnitude, its forward output saturates to either 0 or 1, and its derivative becomes 0, leading to us not updating its value by any significant amount.</li><li>Since the sigmoid function scales its output between 0 and 1, it is <strong>not zero centered</strong> (i.e, the value of the sigmoid at an input of 0 is not equal to 0, and it does not output any negative values).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*QoevW9gODYl9HoBLhUo1OQ.png" /><figcaption>Figure 12: Derivative of a weight using sigmoid neuron</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*WnmxpWqxdRkI2i1TzrcQIQ.png" /><figcaption>Figure 13: Derivative of y with respect to weights</figcaption></figure><ul><li>From Figure 12 and 13, we can see that the derivative of the loss with respect to the weights of a layer depends on the input to the layer itself <br>(i.e <strong>x</strong>).</li><li>Now for example if we have a 2 layer neural network and were to use a sigmoid activation function after layer 1, we know that the output of that layer 1 would always lie between 0 and 1.</li><li>If we were to calculate the derivative of layer 2 with respect to its weights, i.e <strong>dy/d(weight)</strong>, looking from Figure 13 we can see that it equates to <strong>x </strong>(i.e the output of layer 1). Since we used a sigmoid activation at layer 1, <strong>x</strong> would always be a positive result between 0 and 1.</li><li>This also means that the sign of the derivative of layer 2&#39;s weights would completely depend on the sign of the term <strong>d(Loss)/dy</strong>, since <strong>dy/d(weight) </strong>is always positive.</li><li>This leads to us constraining all the weights of layer 2 to be updated either positively, or negatively. Sigmoid does not allow some weights to be updated by a positive value and some by a negative value. This could lead to a lot of zig zagging, as we would first update the weights positively in the first step, and then negatively in the next step.</li><li><strong>Tanh Function</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*zsl4ToKbVoPU1bdl2Cjm5w.png" /><figcaption>Figure 14: Tanh Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*GmCydDsR1VvIdDBAfBWUwg.png" /><figcaption>Figure 15: Graph of tanh function, and its derivative</figcaption></figure><p><strong>Forward Pass of a Tanh Neuron:</strong></p><ul><li>The tanh function ranges from -1 to +1</li><li>If we analyze the tanh graph, we notice the same persisting issue from the sigmoid neuron, which is, that at values greater than 3 or less than -3, we end up with the same output of either +1 or -1, that causes <strong>saturation</strong>.</li><li>The presence of multiple exponents in its formula makes it slower than the sigmoid neuron to compute.</li></ul><p><strong>Backward Pass of a Tanh Neuron:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*I4ea4UAVX1LtuRSWHIeS4w.png" /><figcaption>Figure 16: Derivative of a function u/v</figcaption></figure><ul><li>The derivative of the tanh function takes the form in Figure 16</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*ZFXKJg8xqD-EQSqANJr-_Q.png" /><figcaption>Figure 17: Calculating the Tanh Derivative</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*K6mY1WZfkCRbmE8V1i3J3g.png" /><figcaption>Figure 18: Tanh derivative continued</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*CymwbJIRlsNpTLqHnb7E6w.png" /><figcaption>Figure 19: Tanh derivative continued</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*2LxZ9WeRzDZS3iVpmO-HGA.png" /><figcaption>Figure 20: Tanh Derivative simplified</figcaption></figure><ul><li>The graph of the equation is represented by the backward plot in Figure 15</li><li>The <strong>saturation</strong> of the tanh function at large magnitudes poses the same issues as the sigmoid neuron in terms of <strong>vanishing gradients</strong>(i.e the derivatives become nearly 0 at large positive or negative values, causing no weight updates).</li><li>The advantage the tanh function has over the sigmoid function is that it is zero centered.</li><li>Going back to the explanations for Figure 12 and 13, since the derivative of a layer’s weights (i.e <strong>dy/d(weight)</strong>) directly depend on the input to that layer itself(i.e <strong>x</strong>), using a tanh function would give us an output containing both positive and negative values.</li><li>This would allow us to get rid of the constraint of either updating all the weights by a positive value, or all the weights by a negative value, since <strong>x</strong> would lie between (-1, 1).</li></ul><h4><strong>Summary</strong>:</h4><ul><li>In the next post I will go over some more commonly used activations like Relu and Leaky Relu.</li><li>Here is the <a href="https://github.com/vineeth2309/Activation-Functions">link</a> to a simple code to implement the activation functions along with their derivatives, and visualize their output.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d80b0e8ee89d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/activation-functions-part-1-d80b0e8ee89d">Activation Functions (Part 1)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of  Vectors and Coordinate Space]]></title>
            <link>https://vineeth2309.medium.com/basics-of-vectors-and-coordinate-space-7ced1890b995?source=rss-4c59dbefc4cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ced1890b995</guid>
            <category><![CDATA[coordinate-systems]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[geometry]]></category>
            <dc:creator><![CDATA[Vineeth S Subramanyam]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 08:37:40 GMT</pubDate>
            <atom:updated>2021-02-07T08:38:17.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basics of Vectors and Coordinate Space</h3><p>Vectors and Coordinate spaces are topics often overlooked as they seem very self explanatory, and easy to understand, from a point of view of mathematical formulas. However, unless we understand intuitively the impact of various vector operations on coordinate spaces, it becomes a lot more difficult to grasp concepts like Linear Transformations or Jacobians. In this post, I hope to lay the ground with the <strong>basics of vectors, coordinate spaces </strong>and<strong> projections</strong>, and build on these concepts in future posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*Ck_ljodU26Vo_LkuRmmyqw.png" /><figcaption>Figure 1: Basic 2D coordinate system</figcaption></figure><p>The figure above is the basic 2 Dimensional coordinate system we are used to seeing. The X axis is horizontal, and gets more postive to the right, and more negative as we move left. Similarly the Y axis increases upwards, and decreases downwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*McaWc6d6cRGWbG7PisxRwQ.png" /><figcaption>Figure 2: Description of a point</figcaption></figure><p>The point shown in the figure is represented as (1, 1), which means if we move 1 unit along the +X axis, and then move +1 unit along the Y axis, we would reach (1, 1).</p><h3><strong>Vectors</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*sOcrH8uJG3G3cDd0UEboDA.png" /><figcaption>Figure 3: Representing a Vector</figcaption></figure><ul><li>A vector can be thought of as any quantity that has a magnitude, and a direction. In the figure above, the orange line pointing towards (1,1) corresponds to a vector.</li><li><strong>Representing a vector as a point</strong>: Using the example from the figure above, we could mathematically represent the vector above as:<br><strong>v = [1, 1]</strong>. The [1,1] corresponds to the point at which the vector ends. To find the direction of this vector <strong>v</strong>, we simply draw a line from the origin <br>(0, 0) to this point (1, 1). The direction in which this line points, corresponds to the direction of our vector <strong>v</strong>.</li><li><strong>Representing a vector with respect to the coordinate space:<br></strong>We can also represent a vector with respect to the axes in equation form. We can represent this vector also as <strong>v = 1x + 1y </strong>, which means we move 1 unit along the X axis, followed by 1 unit along Y axis.</li></ul><p><strong>Magnitude / Length of a Vector:</strong></p><ul><li>The magnitude of a vector is essencially its length. To find the length of a vector we need to know its starting point(x1, y1) and its ending point <br>(x2, y2). Mathematically it is represented by the modulus operator <strong>|v|</strong> .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*FuThC7KtQin0YzwVH03faA.gif" /><figcaption>Figure 4: Lenth of a Vector</figcaption></figure><ul><li>Going by the vector in Figure 3, the magnitude of the vector would be:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*8x44_cF1OD-I_Qnnle8UPw.gif" /><figcaption>Figure 5: Magnitude of Vector in Figure 3</figcaption></figure><ul><li>Our (x1,y1) in this case are (0, 0), because that is the starting point of the vector, and (x2,y2) is (1,1), because that is the ending point.</li></ul><p><strong>Unit Vectors:</strong></p><ul><li>The term unit vector is used to define a vector that has unit length; i.e length=1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*YdWEstCYcu1MJ32yUm-Ocg.png" /><figcaption>Figure 6: Defining a new vector of length 2.12</figcaption></figure><ul><li>If we have a vector, for example <strong>(1.5, 1.5)</strong>, and we calcluate its length using the formula from Figure 4, we get a length of <strong>2.12</strong> .</li><li>Now if we wish to convert this same vector to a unit vector, all we need to do, is make sure its length is 1. The way we would go about reducing the length of this vector is simply by shrinking it, till it has a length of 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*xqZZ_mzr3hv8qk0G0Z2Aew.gif" /><figcaption>Figure 7: Converting a vector to a unit vector</figcaption></figure><ul><li>Mathematically we achieve this by dividing the original vector by its length. In this case, we would divide the vector represented by the point <strong>(1.5,1.5)</strong> by its length<strong> 2.12</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*70K-ov7V7Ip9wwtylBTccg.png" /><figcaption>Figure 8: Unit vector for figure 6</figcaption></figure><ul><li>This results in a new vector that points in the same direction as the original vector, but instead has a length of 1. Unit vectors are often used just as a representation of direction.</li></ul><p><strong>Projection of Vectors</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*Ag2N0KoO96QxtjZc-v3enw.png" /><figcaption>Figure 9: Projection of a vector</figcaption></figure><ul><li>The projection of a vector onto another can be understood as the shadow cast from one vector onto another. From the figure above, it can be thought of as, how would the shadow of <strong>Vector 2 </strong>look if the person was to look down on <strong>Vector 1</strong>. It is also important to note that we must look down <strong>perpendicular</strong> to <strong>Vector 1 </strong>to view the projection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*3RFUqPTL4nI3K0qPzp8MZw.png" /><figcaption>Figure 10: Projected vector</figcaption></figure><ul><li>The projection of Vector 2 onto Vector 1 would look like the yellow arrow from the figure above.</li><li>It is clear to see that if we project Vector 2 onto Vector 1, it points in the same direction as Vector 1, but has a different length.</li><li>Now to mathematically quantify this projection, we use trignometry</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*2KtFdT4UWmmH_dU9nteHHw.png" /><figcaption>Figure 11: Trignometry for projecton</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*uCY_YvyUcFMvVDbJJI3qBQ.gif" /><figcaption>Figure 12: Formula of cosine</figcaption></figure><ul><li>From the figure above, the <strong>adjacent</strong> of the triangle, and the <strong>projected</strong> <strong>Vector</strong> <strong>2</strong> represent the same yellow line. The hypotenuse of the triangle is the <strong>Vector 2</strong>, and the opposite is the perpendicular from <strong>Vector 2</strong> drawn onto <strong>Vector 1</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*IEWTeC2L9dIBjwZZsY4_oQ.gif" /><figcaption>Figure 13: Cosine of theta represented in terms of vectors</figcaption></figure><ul><li>The cosine of the angle can be written in terms of the lengths of each vector.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*cOlLZLKxo_RuyRP1vo1k5g.gif" /><figcaption>Figure 14: Length of projected vector 2</figcaption></figure><ul><li>The length of <strong>projected vector 2 </strong>can be written in terms of the length of the actual <strong>vector 2</strong> and the cosine of the angle between <strong>vector 1</strong> and <strong>vector 2</strong>.</li><li>Now we already have the length of the projected vector 2, and only need its direction in order to represent it individually as a new vector. For this, we make use of <strong>vector 1</strong>, since it also points in the same direction as the projection. As i mentioned before, unit vectors often are used to just represent a direction, as they have a length=1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*CzQUWWs71Qh4_SoZWW4Fww.gif" /><figcaption>Figure 15: Unit vector 1</figcaption></figure><ul><li>The <strong>unit vector 1</strong> is essetially a representation of the direction of <br><strong>vector 1</strong>. Now all we need to do in order to get the <strong>projected vector 2</strong>, is to scale this unit vector 1 to the length of the projected vector 2 that we calculated earlier. (For example if the projected vector 2 has a length = 0.7, and the unit vector has a length = 1, multiplying the unit vector by this length of 0.7 has the effect of simply scaling its length in the same direction.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*WLf8R2kzfuYMM4jpB2Mq5w.gif" /><figcaption>Figure 16: Projected vector 2 calculated with respect to unit vector 1</figcaption></figure><p><strong>Points to note:</strong></p><ul><li>The cos(theta) that we calculated in Figure 13 represents the angle between the 2 vectors.</li><li>The formula for projection can be written differently to include the dot product. The definition using the dot product is more generalized, as it does not require us knowing the angle between the vectors in advance. I will go over the dot product in the next post.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/24/1*1UwflpJpFOb_GIuQhSiLQQ.gif" /><figcaption>Figure 17: Column form of a vector</figcaption></figure><ul><li>Vectors are generally represented in column form rather than <br>row form <strong>[1,1]</strong>. In the column form, each row represents each axis. (For example row 1 represents a length of 1 in the x direction, and column 2 represents a length of 1 in the y direction).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ced1890b995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a custom Dataset and Dataloader in Pytorch]]></title>
            <link>https://medium.com/analytics-vidhya/creating-a-custom-dataset-and-dataloader-in-pytorch-76f210a1df5d?source=rss-4c59dbefc4cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/76f210a1df5d</guid>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[custom-dataset]]></category>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Vineeth S Subramanyam]]></dc:creator>
            <pubDate>Fri, 29 Jan 2021 05:45:01 GMT</pubDate>
            <atom:updated>2021-01-29T16:21:56.783Z</atom:updated>
            <content:encoded><![CDATA[<p>Training a deep learning model requires us to convert the data into the format that can be processed by the model. For example the model might require images with a width of 512, a height of 512, but the data we collected contains images with a width of 1280, and a height of 720. We therefore need some way to be able to convert the available data we have, into the exact format required by the model.</p><p>A dataloader in simple terms is a function that iterates through all our available data and returns it in the form of batches. For example if we have a dataset of 100 images, and we decide to batch the data with a size of 4. Our dataloader would process the data, and return 25 batches of 4 images each.</p><p>Creating a dataloader can be done in many ways, and does not require torch by any means to work. Using torch however makes the task a lot easier. Keeping that in mind, lets start by understanding what the the Torch Dataset and Dataloder Classes contains.</p><p><strong>Torch Dataset:</strong></p><ol><li>The Torch Dataset class is basically an abstract class representing the dataset. It allows us to treat the dataset as an object of a class, rather than a set of data and labels.</li><li>The main task of the <strong>Dataset</strong> class is to return a pair of [input, label] every time it is called. We can define functions inside the class to preprocess the data, and return it in the format we require.</li><li>The class must contain two main functions:<br><strong>__len__()</strong>: This is a fuction that returns the length of the dataset.<br><strong>__getitem__()</strong>: This is a function that returns one training example.</li><li>The torch dataset class can be imported from <strong>torch.utils.data.Dataset</strong></li></ol><p><strong>Torch Dataloader:</strong></p><ol><li>The Torch Dataloader not only allows us to iterate through the dataset in batches, but also gives us access to inbuilt functions for <strong>multiprocessing</strong>(allows us to load multiple batches of data in parallel, rather than loading one batch at a time), <strong>shuffling</strong>, etc.</li><li>The torch Dataloader takes a torch Dataset as input, and calls the __getitem__() function from the Dataset class to create a batch of data.</li><li>The torch dataloader class can be imported from <strong>torch.utils.data.DataLoader</strong></li></ol><p><strong>Code:</strong></p><ul><li>I wont go into the entire process of training a model, but I will explain step by step, the process of creating the dataset class, and the dataloader.</li><li>The requirements for the code will be:<br> <strong>numpy</strong>: pip3 install numpy <br> <strong>opencv</strong>: pip3 insall opencv-python<br> <strong>torch</strong>: pip3 install torch<br> <strong>glob</strong>: pip3 install glob</li><li>I have created a sample dataset for the task of a classification model, to classify between cats and dogs. The folder structure is as follows. We have the <strong>Project </strong>folder that contains the code <strong>Main.py</strong>, and a folder called <strong>Dog_Cat_Dataset</strong>. This folder called <strong>Dog_Cat_Dataset </strong>is the dataset folder that contains 2 subfolders inside it called <strong>dogs</strong> and <strong>cats</strong>. Both the dogs and cats folders have 5 images each.</li></ul><pre>- <strong>Project</strong><br>    - <strong>Main.py</strong><br>    - <strong>Dog_Cat_Dataset</strong><br>        - <strong>dogs</strong><br>           - 1.jpg<br>           - 2.jpg<br>           - 3.jpg<br>           - 4.jpg<br>           - 5.jpg<br>        - <strong>cats</strong><br>           - 1.jpg<br>           - 2.jpg<br>           - 3.jpg<br>           - 4.jpg<br>           - 5.jpg</pre><ul><li>Lets start the code <strong>Main.py</strong> with a few imports.</li></ul><pre><em>import</em> glob<br><em>import</em> cv2<br><em>import</em> numpy as np<br><em>import</em> torch<br><em>from</em> torch.utils.data <em>import</em> Dataset, DataLoader</pre><ul><li><strong>glob:</strong> allows us to retrieve paths of data inside sub folders easily<br><strong>cv2:</strong> is used as the image processing library to read and preprocess images<br><strong>numpy:</strong> is used for matrix operations<br><strong>torch:</strong> is used to create the Dataset and Dataloader classes, and for converting data to tensors.</li></ul><pre>class CustomDataset(Dataset):<br>    def __init__(self):<br>        self.imgs_path = &quot;Dog_Cat_Dataset/&quot;<br>        file_list = glob.glob(self.imgs_path + &quot;*&quot;)<br>        print(file_list)<br>        self.data = []<br>        <em>for</em> class_path in file_list:<br>            class_name = class_path.split(&quot;/&quot;)[-1]<br>            <em>for</em> img_path in glob.glob(class_path + &quot;/*.jpeg&quot;):<br>                self.data.append([img_path, class_name])<br>        print(self.data)<br>        self.class_map = {&quot;dogs&quot; : 0, &quot;cats&quot;: 1}<br>        self.img_dim = (416, 416)</pre><pre>    def __len__(self):<br>        <em>return</em> len(self.data)</pre><pre>    def __getitem__(self, idx):<br>        img_path, class_name = self.data[idx]<br>        img = cv2.imread(img_path)<br>        img = cv2.resize(img, self.img_dim)<br>        class_id = self.class_map[class_name]<br>        img_tensor = torch.from_numpy(img)<br>        img_tensor = img_tensor.permute(2, 0, 1)<br>        class_id = torch.tensor([class_id])<br>        <em>return</em> img_tensor, class_id</pre><ul><li>Lets go through this class in detail.</li></ul><pre>class CustomDataset(Dataset):</pre><ul><li>We create a class called <strong>CustomDataset</strong>, and pass the argument <strong>Dataset</strong>, to allow it to inherit the functionality of the Torch Dataset Class.</li></ul><pre>def __init__(self):<br>    self.imgs_path = &quot;Dog_Cat_Dataset/&quot;<br>    file_list = glob.glob(self.imgs_path + &quot;*&quot;)<br>    print(file_list)</pre><ul><li>We define the init function to initialize our variables. The variable <strong>self.imgs_path</strong> contains the base path to our Dog_Cat_Dataset folder</li><li>We then use glob to retrieve the list of all folders inside the base folder we specified. In our example, the <strong>Dog_Cat_Dataset</strong> folder contains two subfolders called <strong>dogs</strong> and <strong>cats</strong>. The “ * ” term added to the <strong>self.imgs_path</strong> indicates we want to search for all folders or files inside the specified path.(Note that using the “*” operation would return every single file inside the folder, not only the folder names. So make sure there is nothing other than the dogs and cats folders in this location.)</li><li>The print statement would return the following output:<br><strong>[‘Dog_Cat_Dataset/dogs’, ‘Dog_Cat_Dataset/cats’]</strong></li><li>This file_list variable contains the list of all the classes in the dataset(dogs and cats).</li></ul><pre>self.data = []<br><em>for</em> class_path in file_list:<br>    class_name = class_path.split(&quot;/&quot;)[-1]<br>    <em>for</em> img_path in glob.glob(class_path + &quot;/*.jpeg&quot;):<br>        self.data.append([img_path, class_name])<br>print(self.data)</pre><ul><li>We now start creating the data list, that would contain the paths to all the images in our dataset.</li><li>We iterate over all the classes in our file list (dogs and cats), and for each class, we first start by extracting the actual class name. As you could see from the printed file list, each class was represented with respected to its base path; i.e Dog_Cat_Dataset/dogs. Since we would much rather refer to the class as dogs and cats, rather than with respect to its path, we create a <strong>class_name</strong> variable by splitting this <strong>class_path</strong> by “/”. (Splitting by “/” would return a list [“Dog_Cat_Dataset” , “dogs”]. Taking the [-1] index would use the last entry in the list. In this case it would be “dogs”.</li><li>Now that we are iterating through each class of the dataset(dog and cat), we want to retrieve each image in their folders (i.e 1.jpeg, 2.jpeg, etc). To do this we once again use glob to return all files in the folders with the extension “.jpeg”. The complete string we pass to glob is Dog_Cat_Dataset/dogs/*.jpeg .The “*.jpeg” indicates we want every file which has an extension of “.jpeg” .</li><li>We append the file path for each image to the list self.data, along with its corresponding class name. This gives us a way to retrieve the input image along with its corresponding label. Printing the list would return the following output.</li></ul><pre> [[&#39;Dog_Cat_Dataset/dogs/4.jpeg&#39;, &#39;dogs&#39;],    <br>  [&#39;Dog_Cat_Dataset/dogs/3.jpeg&#39;, &#39;dogs&#39;], <br>  [&#39;Dog_Cat_Dataset/dogs/5.jpeg&#39;, &#39;dogs&#39;],<br>  [&#39;Dog_Cat_Dataset/dogs/1.jpeg&#39;, &#39;dogs&#39;],<br>  [&#39;Dog_Cat_Dataset/dogs/2.jpeg&#39;, &#39;dogs&#39;],<br>  [&#39;Dog_Cat_Dataset/cats/4.jpeg&#39;, &#39;cats&#39;],<br>  [&#39;Dog_Cat_Dataset/cats/3.jpeg&#39;, &#39;cats&#39;],<br>  [&#39;Dog_Cat_Dataset/cats/5.jpeg&#39;, &#39;cats&#39;],<br>  [&#39;Dog_Cat_Dataset/cats/1.jpeg&#39;, &#39;cats&#39;],<br>  [&#39;Dog_Cat_Dataset/cats/2.jpeg&#39;, &#39;cats&#39;]]</pre><ul><li>We additionally define a class map, and an image dimension. The <strong>self.class_map</strong> dictionary that allows us to convert the string of the classes, to a number; i.e “dogs” corresponds to class 0, and “cats” corresponds to class 1, and the image dimension is the size that we will resize all the images to, so that they all have the same size.</li></ul><pre>self.class_map = {&quot;dogs&quot; : 0, &quot;cats&quot;: 1}<br>self.img_dim = (416, 416)</pre><ul><li>Now that we have created a list with all our data, we start coding the function for <strong>__len__()</strong>, which is mandatory for a Torch Dataset object.</li></ul><pre>def __len__(self):<br>    <em>return</em> len(self.data)</pre><ul><li>The size of our dataset is just the number of individual images we have, which can be obtained through the length of the <strong>self.data</strong> list. (Torch internally uses this function to understand the size of the dataset in its dataloader, to call the <strong>__getitem__()</strong> function with an index within this dataset size)</li></ul><pre>def __getitem__(self, idx):<br>    img_path, class_name = self.data[idx]</pre><ul><li>We start by defining the <strong>__getitem__</strong> function to take the object of itself as input(<strong>self</strong>), and an <strong>idx</strong>. The <strong>idx</strong> is the term that this function will be called with, that corresponds to which image needs to be returned from our <strong>self.data</strong> list.</li><li>We retrieve the image path and class name corresponding to the idx from the<strong> self.data</strong> list.</li></ul><pre>img = cv2.imread(img_path)<br>img = cv2.resize(img, self.img_dim)<br>class_id = self.class_map[class_name]</pre><ul><li>We use opencv as the image processing library to load the image and resize it to the required dimension.</li><li>We read the image using the <strong>imread</strong> function that loads an image from the given image path, and then resize it to the dimensions we specified in the <strong>self.img_dim</strong> variable.</li><li>Deep learning models for classification generally make use of a number id associated with the class, rather than a name (“dogs” -&gt; 0). The <strong>self.class_map</strong> dictionary just provides the mapping from the name to the number.</li></ul><pre>img_tensor = torch.from_numpy(img)<br>img_tensor = img_tensor.permute(2, 0, 1)<br>class_id = torch.tensor([class_id])</pre><ul><li>Once we have loaded the image, and obtained its corresponding class id, we convert the variables to tensors. Training models with torch requires us to convert variables to the torch tensor format, that contain internal methods for calculating gradients, etc.</li><li>We create the variable <strong>img_tensor</strong> that is the tensor form of the <strong>img</strong> we loaded. Opencv uses the library numpy to represent images as matrices, and the <strong>torch.from_numpy</strong> function allows us to convert a numpy array to a torch tensor.</li><li>Torch convolutions require images to be in a channel first format; i.e for example a 3 channel image(Red, Green and Blue channels) would be generally represented as: (Width, Height, Channels) in numpy, however torch requires us to convert this to: (Channels, Width, Height).</li><li>For this conversion we use the permute function of torch, that allows us to change the ordering of the dimensions of a torch tensor. The arguments we pass to it, correspond to the new ordering of dimensions we want. For example in our case, we have (Width, Height, Channels). <br>(Width -&gt; 0), (Height-&gt;1), (Channels-&gt;2)<br>We want to reorder these dimensions to make channels first, therefore, we use <strong>img_tensor.permute(2, 0, 1)</strong>, which would make the 2nd dimension first.</li><li>We then convert the integer value of <strong>class_id</strong> to a torch tensor, and also increase its dimensionality by refering to it as <strong>[class_id]</strong>. This is to ensure that the data can be batched in the dimensions torch requires it. (Torch requires labels to be in the shape [batch_size, label_dimension]. Using just <strong>class_id</strong>, rather that <strong>[class_id]</strong> woud lead to us having a final size of [batch_size], as each <strong>class_id</strong> is just a single value).</li></ul><pre><em>return</em> img_tensor, class_id</pre><ul><li>We return the <strong>img_tensor</strong> and <strong>class_id</strong>, so that anytime the <strong>__getitem__</strong> function is called with an <strong>idx</strong>, it is returned an image with its corresponding label.</li><li>Note: Additionally torch might require the tensors returned to be converted to type float. That can be done with the following modification:</li></ul><pre><em>return</em> img_tensor.float(), class_id.float()</pre><ul><li>Now that we have created the dataset, we can use this class in the torch dataloader to iterate through this data while training.</li></ul><pre><em>if</em> __name__ == &quot;__main__&quot;:<br>    dataset = CustomDataset()<br>    data_loader = DataLoader(dataset, batch_size=4, shuffle=True)</pre><ul><li>To test out the dataset and our dataloader, in the main function of our script, we create an instance of the <strong>CustomDataset</strong> we created, and call it <strong>dataset.</strong></li><li>The Torch DataLoader takes as input this <strong>dataset</strong>, along with other arguments for batch_size, shuffle, etc, which are extra terms to specify how many images we want in each batch of data, and whether we want to randomize the way in which we generate the <strong>idx</strong>, we used before.</li></ul><pre><em>for</em> imgs, labels in data_loader:<br>    print(&quot;Batch of images has shape: &quot;,imgs.shape)<br>    print(&quot;Batch of labels has shape: &quot;, labels.shape)</pre><ul><li>We can test the working of our dataloader by iterating through it, and printing the shape of our input images, and our labels.</li><li>The torch dataloader does take a lot of extra arguments like :</li></ul><ol><li><strong>no_workers</strong>: Corresponds to how many workers in parallel we want to load the data. Using more number of workers would speed up the data loading process.</li><li><strong>pin_memory</strong>: When training on a GPU device, we would want to speed up the process of passing the loaded data from CPU to GPU. Therefore setting it to true would speed up this data transfer.</li><li><strong>drop_last</strong>: It skips the last batch of data, if it has samples &lt; batch_size. For example in our case, we have 10 images in our dataset, and we specified a batch size of 4. This would mean that the last batch has only 2 images. Setting drop_last=True, would skip this last batch, as it has &lt; 4 images.</li></ol><p><strong>Note:</strong></p><ol><li>The dataset class of torch can be used like any other class in python, and have any number of sub functions in it, as long as it has the 2 required functions(<strong>__len__</strong>, and <strong>__getitem__</strong>).</li><li>The returned data can also be passed to GPU, if available. For example: <strong>img_tensor.to(“cuda”).</strong></li><li>The torch dataloader has an additional list of arguments that can be used<br><a href="https://pytorch.org/docs/stable/data.html#iterable-style-datasets">Link</a></li><li>I have uploaded the complete code for this post on github: <a href="https://github.com/vineeth2309/Custom-Dataset-and-Dataloader-in-Torch">Code</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76f210a1df5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/creating-a-custom-dataset-and-dataloader-in-pytorch-76f210a1df5d">Creating a custom Dataset and Dataloader in Pytorch</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Non Max Suppression (NMS)]]></title>
            <link>https://medium.com/analytics-vidhya/non-max-suppression-nms-6623e6572536?source=rss-4c59dbefc4cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6623e6572536</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[iou]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[non-max-suppression]]></category>
            <category><![CDATA[bounding-box]]></category>
            <dc:creator><![CDATA[Vineeth S Subramanyam]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 12:19:29 GMT</pubDate>
            <atom:updated>2024-02-07T07:00:13.106Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Non Max Suppression, and why is it used?</strong></p><p>Non <a href="https://www.analyticsvidhya.com/blog/2020/08/selecting-the-right-bounding-box-using-non-max-suppression-with-implementation/?utm_source=Backlink&amp;utm_medium=SEO">max suppression</a> is a technique used mainly in object detection that aims at selecting the best bounding box out of a set of overlapping boxes. In the following image, the aim of non max suppression would be to remove the yellow, and blue boxes, so that we are left with only the green box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*kwS8PeZKfVyf5Vv55u_MBg.jpeg" /><figcaption>Figure 1: Multiple overlapping boxes for the same object</figcaption></figure><p><strong>Procedure for calculating NMS:</strong></p><p>To get an overview of what a bounding box is, and what IOU means, I have made two posts on the same.(<a href="https://vineeth2309.medium.com/basics-of-bounding-boxes-94e583b5e16c">Bounding Box</a>, and <a href="https://vineeth2309.medium.com/iou-intersection-over-union-705a39e7acef">IOU</a>). The terms and parameters described in the two articles are carried forward in this post. I will first go ahead and describe the procedure of NMS for this particular example, and then explain a more generalized algorithm extending it for different classes.</p><p><strong>Explaining the terms used:</strong></p><ul><li>The format for each bounding box that we will use is as follows:<br>bbox = [x1, y1, x2, y2, class, confidence].</li><li>Let us assume that for this particular image we have a list 3 bounding boxes; i.e bbox_list = [blue_box, yellow_box, green_box].</li><li>green_box = [x1, y1, x2, y2, ”Cat”, 0.9]<br>yellow_box = [x5, y5, x6, y6, ”Cat”, 0.75]<br>blue_box = [x3, y3, x4, y4, ”Cat”, 0.85]</li></ul><p><strong>Stage 1 (Initial removal of boxes):</strong></p><ul><li>As the first step in NMS, we sort the boxes in descending order of confidences. This gives us:<br>bbox_list = [green_box, blue_box, yellow_box]</li><li>We then define a confidence threshold. Any box that has a confidence below this threshold will be removed. For this example, let us assume a confidence threshold of <strong>0.8</strong>. Using this threshold, we would remove the yellow box as its confidence is &lt; 0.8. This leaves us with:<br>bbox_list = [green_box, blue_box]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*4SYXQozCdfWcEXDFMIMovQ.jpeg" /><figcaption>Figure 2: Yellow box removed</figcaption></figure><p><strong>Stage 2 (IOU Comparision of boxes):</strong></p><ul><li>Since the boxes are in descending order of confidence, we know that the first box in the <a href="https://www.analyticsvidhya.com/blog/2020/08/selecting-the-right-bounding-box-using-non-max-suppression-with-implementation/?utm_source=Backlink&amp;utm_medium=SEO">list</a> has the highest confidence.We remove this first box from the list and add it to a new list. In our case we would remove the green box, and put it into a new list, say bbox_list_new.</li><li>At this stage, we define an additional threshold for IOU. This threshold is used to remove boxes that have a high overlap. The reasoning behing it is as follows: If two boxes have a significant amount of overlap, and they also belong to the same class, it is highly likely that both the boxes are covering the same object (We can verify this from Figure 2). Since the aim is to have one box per object, we try remove the box that has a lower confidence.</li><li>For our example, let us say that our IOU threshold is <strong>0.5</strong></li><li>We now start calculating the IOU of the green box with every remaining box in the bbox_list that also has the same class. In our case we would calculate the IOU of the green box only with the blue box.</li><li>If the IOU of the green box and the blue box is greater than the threshold we defined of 0.5, we would remove the blue box, since it has a lower confidence, and also has significant overlap.</li><li>This procedure is repeated for every box in the image, to end up with only unique boxes that also have a high confidence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*vLVo-ZKPUbbcNBndQYIFWQ.jpeg" /><figcaption>Figure 3: Result of Non Max Suppression</figcaption></figure><p><strong>Algorithm:</strong></p><ol><li>Define a value for Confidence_Threshold, and IOU_Threshold.</li><li>Sort the bounding boxes in a descending order of confidence.</li><li>Remove boxes that have a confidence &lt; Confidence_Threshold</li><li>Loop over all the remaining boxes, starting first with the box that has highest confidence.</li><li>Calculate the IOU of the current box, with every remaining box that belongs to the same class.</li><li>If the IOU of the 2 boxes &gt; IOU_Threshold, remove the box with a lower confidence from our list of boxes.</li><li>Repeat this operation until we have gone through all the boxes in the list.</li></ol><p><strong>Code:</strong></p><p>The code below is the basic function to perform Non Max Suppression. The IOU function used in the snippet below is the same function that was used in the previous post(Code can be found: <a href="https://github.com/vineeth2309/IOU">here</a>). The code below to calculate NMS can be optimized to improve performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*MP2HevFHS6mwhlU5xwKaRw.png" /><figcaption>Figure 4: Function to perform Non Max Suppression</figcaption></figure><pre>def nms(boxes, conf_threshold=0.7, iou_threshold=0.4):</pre><ul><li>The function takes as input the list of boxes for the particular image, and a value for confidence threshold, and iou threshold. (I have set default values for them to be 0.7, and 0.4 respectively)</li></ul><pre>bbox_list_thresholded = []<br>bbox_list_new = []</pre><ul><li>We create 2 lists called <strong>bbox_list_thresholded</strong>, and <strong>bbox_list_new</strong>. <br><strong>bbox_list_thresholded: </strong>Contains the new list of boxes after filtering low confidence boxes<br><strong>bbox_list_new</strong>: Contains the final list of boxes after performing NMS</li></ul><pre>boxes_sorted = sorted(boxes, reverse=True, key = lambda x : x[5])</pre><ul><li>We start Stage 1 by sorting the list of boxes in descending order of confidence, and store the new list in the variable <strong>boxes_sorted</strong>. The inbuilt python function called <strong>sorted</strong> iterates through our list of boxes, and sorts it according the keywords we specify. In our case, we specify a keyword <strong>reverse</strong>=True to sort the list in descending order. The second keyword <strong>key</strong> specifies the constraint we want to use for sorting. The lambda function we use provides a mapping that returns the 5th element of each bounding box(confidence). The sorted function while iterating through each box, would look at the lambda function, which would return the 5th element of the box(confidence), and this would be sorted in a reverse order.</li></ul><pre><em>for</em> box in boxes_sorted:<br>    <em>if</em> box[5] &gt; conf_threshold:<br>        bbox_list_thresholded.append(box)<br>    <em>else</em>:<br>        <em>pass</em></pre><ul><li>We iterate over all the sorted boxes, and remove the boxes which have a confidence lower than the threshold we set(<strong>conf_threshold</strong>=0.7)</li></ul><pre><em>while</em> len(bbox_list_thresholded) &gt; 0:<br>    current_box = bbox_list_thresholded.pop(0)<br>    bbox_list_new.append(current_box)</pre><ul><li>In Stage 2, we loop over all the boxes in the list of thresholded boxes(<strong>bbox_list_thresholded</strong>) one by one, till the list is emptied. <br>We start off by removing(<strong>pop</strong>) the first box from this list(current_box), as it has the highest confidence, and append it to our final list (<strong>bbox_list_new</strong>).</li></ul><pre><em>    for</em> box in bbox_list_thresholded:<br>        <em>if</em> current_box[4] == box[4]:<br>            iou = IOU(current_box[:4], box[:4])<br>            <em>if</em> iou &gt; iou_threshold:<br>                bbox_list_thresholded.remove(box)</pre><ul><li>We then iterate over all the remaining boxes in the list <strong>bbox_list_thresholded</strong>, and check whether they belong to the same class as the current box. (box[4] corresponds to the class)</li><li>In case the two boxes belong to the same class, we calculate the IOU between these boxes (we pass <strong>box[:4]</strong> to the IOU function as it corresponds to the values of (x1, y1, x2, y2), since our IOU function does not require class and confidence).</li><li>If the IOU &gt; <strong>iou_threshold, </strong>we remove the box from the list <strong>bbox_list_thresholded, </strong>as this box is the one with lower confidence.</li></ul><pre><em>return</em> bbox_list_new</pre><ul><li>We return the updated list of boxes, after the non max supression.</li></ul><p><strong>Final Points:</strong></p><ul><li>This procedure for non max suppression can be modified according to the application. For example the model YOLOV3 makes use of two sets of confidences as a thresholding measure. Another modification to the algorithm is called soft NMS which I will explain in a further post.</li><li>I have created a <strong>code</strong> that goes through the entire process of NMS threshold for an image with 2 different classes. I will attach the results of it below. The complete code can be found <a href="https://github.com/vineeth2309/Non-Max-Suppression">here</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Y4IozBOkUb64AMalU-nL6A.jpeg" /><figcaption>Figure 5: Result of NMS in code</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6623e6572536" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/non-max-suppression-nms-6623e6572536">Non Max Suppression (NMS)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IOU(Intersection over Union)]]></title>
            <link>https://medium.com/analytics-vidhya/iou-intersection-over-union-705a39e7acef?source=rss-4c59dbefc4cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/705a39e7acef</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[bounding-box]]></category>
            <category><![CDATA[iou]]></category>
            <category><![CDATA[yolov3]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[Vineeth S Subramanyam]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 12:37:17 GMT</pubDate>
            <atom:updated>2021-01-28T16:30:19.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>IOU (Intersection over Union)</h3><p><strong>What is IOU and where is it used?</strong></p><ul><li><strong>IOU</strong>(Intersection over Union) is a term used to describe the extent of overlap of two boxes. The greater the region of overlap, the greater the IOU.</li><li>IOU is mainly used in applications related to object detection, where we train a model to output a box that fits perfectly around an object. For example in the image below, we have a green box, and a blue box. The green box represents the correct box, and the blue box represents the prediction from our model. The aim of this model would be to keep improving its prediction, until the blue box and the green box perfectly overlap, i.e the IOU between the two boxes becomes equal to 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VuAsK1Wwa_mOxW2nK2UovQ.jpeg" /><figcaption>Figure 13: Depiction of the task of object detection</figcaption></figure><ul><li>IOU is also used in non max suppression, which is used to eliminate multiple boxes that surround the same object, based on which box has a higher confidence. I will go over non max suppression in more detail in my next post.</li></ul><p><strong>Calculating IOU:</strong></p><p>Let us assume that box 1 is represented by [x1, y1, x2, y2], and box 2 is represented by [x3, y3, x4, y4]. (We will use this convention later to calculate the areas.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*cNLP-dEczo7oXxEXLzAzQQ.jpeg" /><figcaption>Figure 1: Intersection of two boxes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*-yS1RREVZYbQLAyBEegcrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*r0o3vX-x979Q84_lbJWS_g.jpeg" /><figcaption>Figure 2: Diagrammatic Representation of the formula to calculate IOU</figcaption></figure><ol><li><strong>Calculating the area of the intersection of the boxes</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*dgrpv4eygfybsijkvu06CQ.jpeg" /><figcaption>Figure 3: Boxes can intersect in many different ways, or even completely overlap each other</figcaption></figure><ul><li>Let us represent the coordinates of the intersected rectangle as <br>[x_inter1, y_inter1, x_inter2, y_inter2 ], to denote the coordinates of the top left, and bottom right of the intersection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*OyWv2-kmXW5ZT8BMZLexrw.jpeg" /><figcaption>Figure 4: Naming the coordinates that need to be calculated</figcaption></figure><ul><li>Lets start by defining the reference coordinate system. We use the computer graphics convention of +X axis moving to the right, and +Y axis moving downward.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*sjUSZawTujR26QO2OjnmVg.png" /><figcaption>Figure 5: Reference Coordinate Axis</figcaption></figure><ul><li>To calculate the top left corner of the intersection, we compare the top left corners of each of the boxes. We can see from the examples above, that <strong>x_inter1</strong> can be found by seeing which box has its top left corner more to the right. Similarly <strong>y_inter1</strong> can be found by seeing which box has its top left corner lower than the other. Mathematically they can be calculated as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*XNolgIbbeCw3C_xX3ttXew.png" /><figcaption>Figure 6: Calculating the top left corner of the intersection</figcaption></figure><ul><li>To calculate the bottom right corner of the intersection, we compare the bottom right corners of each of the boxes. <strong>x_inter2</strong> can be found by seeing which box has its bottom right corner more to the left. Similarly <strong>y_inter2</strong> can be found by seeing which box has its bottom right corner higher than the other. Mathematically they can be calculated as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*7VqDuCCWWY3Z6EajN3cwgQ.png" /><figcaption>Figure 7: Calculating the botom right corner of the intersection</figcaption></figure><ul><li>For example, Figure 4 has cases where the boxes overlap perfectly, or have the same value for a particular coordinate. In such cases, the min or max operation of comparing a value with itself, is simply the value itself.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*NBop1PgOPl9AuF5LuxtTgg.png" /><figcaption>Figure 8: Example when comparing boxes with the same value for a coordinate</figcaption></figure><ul><li>Now that we have the coordinates of the intersection, the area of the intersection is simply the area of the rectangle formed. (In practice we would take the modulus of the width and height, to make sure that even if the orders of the boxes are changed, the width and height would still be positive; i.e if x_inter1&gt;x_inter2 , we would still get a positive value of width)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*lStHBv9NJXpazBrxKDuQGA.png" /><figcaption>Figure 8: Calculating the area of the intersection</figcaption></figure><p>2. <strong>Calculating the area of the union of the boxes</strong></p><ul><li>The union of the boxes is the total area covered by both the boxes, as shown in Figure 2.</li><li>To find the total area, we first calculate the area of the individual boxes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*1Ro5ToxRgQco5z3Tjj2LUg.png" /><figcaption>Figure 9: Calculating the areas of the two boxes</figcaption></figure><ul><li>If we look at the total area covered by the two boxes, we see that the portion of the intersection is covered in both the boxes, i.e the area of the intersection is included in both <strong>area_box1</strong> and <strong>area_box2.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*aDM3JsjMNgZCwrjL9s3DZg.jpeg" /><figcaption>Figure 10: Depicting the intersection area being covered in both boxes.</figcaption></figure><ul><li>Since we want to account for the common area of intersection only once, we can subtract the area of intersection we calculated, from the total area of the two boxes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*5yKBoxwgM1z6hU3FotsAWw.png" /><figcaption>Figure 11: Area of the union of the boxes</figcaption></figure><p>3. <strong>Calculating the IOU</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*hStjEFR6573ocDAthW4NUw.png" /><figcaption>Figure 12: Formula to calculate IOU</figcaption></figure><p><strong>What is the range of values that the IOU can have?</strong></p><ul><li>The IOU of two boxes can have any values between 0 and 1.</li><li>In case there are 2 boxes that do not intersect, the area of their intersection would be 0, and therefore the IOU would also be 0.</li><li>In case there are 2 boxes that completely overlap, the area of the intersection would be equal to the area of their union, and therefore the IOU would be 1.</li></ul><p><strong>Coding a function for IOU in python:</strong></p><ul><li>For the same image displayed above, lets write a function in python to calculate the IOU of the green and the blue box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*QIp7ueG_EVH8AAKJWR-Mnw.png" /><figcaption>Figure 14: Function in python to implement IOU</figcaption></figure><ul><li>The function IOU takes in 2 boxes, box1 and box2 as input. The data in each box is a list containing[x1, y1, x2, y2], which is the top left, and bottom right coordinates.</li><li>We find the area of the intersection, followed by the area of the union, as described earlier.</li><li>The abs function is an inbuilt function in python to calculate the modulus. This ensures we never end up with a negative width or height.</li><li>The IOU returned is a value of type float, that lies between 0 and 1.</li><li>I have written a code that allows us to visualize the effect of varying the bounding boxes on the IOU. The link to the complete code is <a href="https://github.com/vineeth2309/IOU">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=705a39e7acef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/iou-intersection-over-union-705a39e7acef">IOU(Intersection over Union)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of Bounding Boxes]]></title>
            <link>https://medium.com/analytics-vidhya/basics-of-bounding-boxes-94e583b5e16c?source=rss-4c59dbefc4cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e583b5e16c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bounding-box]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vineeth S Subramanyam]]></dc:creator>
            <pubDate>Sat, 16 Jan 2021 12:34:13 GMT</pubDate>
            <atom:updated>2024-01-15T11:52:58.971Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is a bounding box?</strong></p><p>A <a href="https://www.analyticsvidhya.com/blog/2020/08/selecting-the-right-bounding-box-using-non-max-suppression-with-implementation/">bounding box</a> in essence, is a rectangle that surrounds an object, that specifies its <strong>position</strong>, <strong>class</strong>(eg: car, person) and <strong>confidence</strong>(how likely it is to be at that location). Bounding boxes are mainly used in the task of <a href="https://www.analyticsvidhya.com/blog/2022/03/a-basic-introduction-to-object-detection/">object detection</a>, where the aim is identifying the position and type of multiple objects in the image. For example, if you look at the image below, the green rectangle is a bounding box that describes where in the image, the car lies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*68SE_oBnBAL2JKM9nx-67w.jpeg" /><figcaption>Bounding Box</figcaption></figure><p><strong>Conventions used in specifying a bounding box:</strong></p><p>There are 2 main conventions followed when representing bounding boxes:</p><ol><li>Specifying the box with respect to the coordinates of its top left, and the bottom right point.</li><li>Specifying the box with respect to its center, and its width and height.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*yvPdthNNOJfmcYKsDhJJtQ.jpeg" /><figcaption>Bounding box specified with respect to its top left and bottom right points</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*PbBGGN_uSFV13R_aX6FiEA.jpeg" /><figcaption>Bounding box specified with respect to its center coordinates</figcaption></figure><p><strong>Parameters used to define a bounding box:</strong></p><p>Depending on the convention followed, here are the main parameters that specify a bounding box:</p><ol><li><strong>Class:</strong> What is ithe object inside the box. Eg car, truck, person etc</li><li><strong>(x1, y1):</strong> Corresponds to the x and y coordinate of the top left corner of the rectangle.</li><li><strong>(x2, y2):</strong> Corresponds to the x and y coordinate of the bottom right corner of the rectangle.</li><li><strong>(xc, yc):</strong> Corresponds to the x and y coordinate of the center of the bounding box.</li><li><strong>Width:</strong> Represents the width of the bounding box.</li><li><strong>Height:</strong> Represents the height of the bounding box.</li><li><strong>Confidence:</strong> Indicates how likely the object is actually present in that box. Eg a confidence of 0.9 would indicate that there is a 90% chance that object actually exists in that box.</li></ol><p><strong>Converting between the conventions:</strong></p><p>We can convert between the different forms of representing the bounding box, depending on our use case.</p><ol><li><strong>xc</strong> = ( x1 + x2 ) / 2</li><li><strong>yc</strong> = ( y1 + y2 ) / 2</li><li><strong>width</strong> = ( x2 — x1)</li><li><strong>height</strong> = (y2 — y1)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e583b5e16c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basics-of-bounding-boxes-94e583b5e16c">Basics of Bounding Boxes</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>