<?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 Vikas S Shetty on Medium]]></title>
        <description><![CDATA[Stories by Vikas S Shetty on Medium]]></description>
        <link>https://medium.com/@vikassshetty?source=rss-d178f4aa3c84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jSNvGrsvwGxKg42PaDzmDw.jpeg</url>
            <title>Stories by Vikas S Shetty on Medium</title>
            <link>https://medium.com/@vikassshetty?source=rss-d178f4aa3c84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:35:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikassshetty/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[Making Sense of Parser Combinators]]></title>
            <link>https://medium.com/inspiredbrilliance/making-sense-of-parsers-0b55b9c4c904?source=rss-d178f4aa3c84------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b55b9c4c904</guid>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Vikas S Shetty]]></dc:creator>
            <pubDate>Sat, 30 Mar 2024 01:49:31 GMT</pubDate>
            <atom:updated>2026-08-06T15:51:08.659Z</atom:updated>
            <content:encoded><![CDATA[<p>Initially, I started this post with the protocol I wrote a parser for, but since the post became big and complicated — it was probably worth breaking it down into a smaller piece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unCtoATPzBBNV_aHVDI8yg.jpeg" /></figure><h3>So what are we doing here?</h3><p>Our aim is to write a simple parser from scratch and parse a number from a String. For this post let’s scope it down to positive numbers (unsigned integers).</p><p>The first question that arises is: why do we need to start from scratch? We could utilise existing libraries or regular expressions to achieve similar goals. There are times when delving deeper into the construction process is necessary for learning purposes.</p><p>In my first attempt to write a parser, I ended up writing my implementation top-down, writing implementations for things as I came across them and split them later. While the initial effort in doing it this way is lesser, the problems with testing these implementations became more and more complicated and I was repeating a lot of the effort. So what’s the alternative way? Can we build our parser from the ground up — reuse components?</p><blockquote>There are multiple options for parsing and I won’t be diving into the choices (Recursive Descent Parsing, LL Parser, LR Parser, etc). For this post we are sticking to writing our parser using <a href="https://en.wikipedia.org/wiki/Parser_combinator">Parser Combinators</a>.</blockquote><p>Well, what do we need to make this happen?</p><ul><li>What is the smallest block in the string we are trying to parse?</li><li>How do we build up blocks (ie) what operations/combinators do we need to make this happen?</li></ul><h3>How do we interact with a parser?</h3><p>If we think about it, we are going to deal with some string, we recognize a pattern and we extract the information we are interested in.</p><p>What happens if there is more than what we need? For example — if the goal is to recognize a single digit from a string and we have a string — “1abc”, ideally we would want to split the string and get back ‘1’ and “abc”. In parsing we read characters till we get the token that we are interested in and return the remaining string (also known as Follow). If we get something else, we stop and return the follow.</p><blockquote>In parser combinators, both the lexer and parser are crafted together. Unlike traditional parsing methods where lexing (tokenization) and parsing (grammar analysis) are distinct phases, parser combinators intertwine these processes.</blockquote><pre>Interface Parser&lt;Token&gt; {<br><br>  function parse(value: String) -&gt; (Token, String)<br><br>}<br>// Token is a generic data type that determines what the Parser returns<br><br><br>Parser&lt;Token&gt; = function (String) -&gt; (Token, String)<br>// How you want to represent the parser will vary from language to language</pre><p>Here (Token, String) is a tuple — a pair of values.</p><p>Our input is a String, output is a token that we are interested in along with the remaining string. A token is a single character that we are interested in.</p><h3>Smallest block in a number</h3><p>So what do we need to represent a number? A number is a combination of digits. Is that all we need?</p><p>Okay, so what’s a digit?</p><p>A digit can be represented as one of the characters from 0 to 9.</p><p>We have our smallest block — a single digit.</p><pre>// Here a Token is a parser that takes a single character as state. <br>// As a parser it is only interested in the one character <br>// that it is initialized with.<br><br>Token(&#39;1&#39;).parse(&quot;123&quot;) -&gt; (&#39;1&#39;, &quot;23&quot;)<br>Token(&#39;2&#39;).parse(&quot;23&quot;) -&gt; (&#39;2&#39;, &quot;3&quot;)</pre><p>We have our happy path. What do we do if we don’t get the token we are interested in?</p><pre>Token(&#39;1&#39;).parse(&quot;23&quot;) -&gt; ?</pre><h3>Handling errors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*9d634nd0XLnJhaK1.jpg" /></figure><p>Either we get a tuple of (Token, String) or we get an Error (check out <a href="https://en.wikipedia.org/wiki/Result_type">Result type</a>)</p><pre>enum Result&lt;T, E&gt; {<br>  Ok(T),<br>  Err(E)<br>}<br>// a result has an Ok type and an error type.<br>// In this case T -&gt; (Token, String)<br>// E -&gt; String</pre><p>This is what the Parser “interface” and return type would look like in Rust.</p><pre>// T is a generic that represent any data type<br>pub trait Parser&lt;T&gt; {<br>    fn parse_from(&amp;self, val: &amp;String) -&gt; ParseResult&lt;T&gt;;<br>}<br><br>pub type ParseResult&lt;T&gt; = Result&lt;(T, String), String&gt;;</pre><pre>Token(&#39;1&#39;).parse(&quot;123&quot;) -&gt; Ok( (&#39;1&#39;, &quot;23&quot;) )<br>Token(&#39;1&#39;).parse(&quot;23&quot;) -&gt; Error(&quot;Couldn&#39;t find 1&quot;)</pre><h3>Parsing a digit</h3><p>We have 10 different digits we are interested in. How do we combine 10 different blocks?</p><p>This leads us up to our first operation/combinator!</p><h3>What is a Parser Combinator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEMetJWhfD21figkal5H1w.png" /></figure><p>A combinator is a <a href="https://en.wikipedia.org/wiki/Higher-order_function">higher order function</a> that takes one or more parsers and returns a new parser.</p><pre>function combinator1(p1: Parser&lt;X&gt;) -&gt; Parser&lt;Z&gt;<br>function combinator2(p1: Parser&lt;X&gt;, p2: Parser&lt;Y&gt;) -&gt; Parser&lt;Z&gt;<br>// Parser&lt;X&gt; is a function on (String) -&gt; (X, String)<br>// Both 1 and 2 are valid combinators<br>// X, Y, Z can be any token or combination of tokens</pre><p>How we choose to represent a combinator will change based on the language you choose, just like the Parser itself. The way I represented a combinator was as something that was a Parser — took one or more parsers and did some operation using these parsers.</p><p>Can a combinator take anything other than Parsers? A combinator can take other functions as input — it’s a higher order function after all.</p><h3>OR</h3><p>A digit can be represented as</p><pre>digit_parser = Token(&#39;0&#39;) or Token(&#39;1&#39;) or .. or Token(&#39;9&#39;)<br>digit_parser = or([Token(&#39;0&#39;), Token(&#39;1&#39;), Token(&#39;2&#39;), ..., Token(&#39;9&#39;)])<br>digit_parser = or(Token(&#39;0&#39;), or(Token(&#39;1&#39;), or(Token(&#39;2&#39;), .... <br><br>// all of them are valid representations<br>// Example 1 uses &#39;or&#39; as an operator<br>// Example 2 is a function that takes a list of parsers<br>// Example 3 is a function that takes 2 parser, so we end up chaning all 10</pre><p>where <strong>or</strong> represents the OR combinator. So what we are saying here is that a digit is 0 or 1 or so on.</p><p>If we have a string “123”, what we want to do is read one character at a time and change that into a digit. So the first time we run the string through our parser we get (‘1’, “23”). The 2nd time gives us (‘2’, “3”) and the 3rd time gives us (‘3’, “”).</p><pre>digit_parser = Token(&#39;1&#39;) or Token(&#39;2&#39;) ....<br>digit_parser.parse(&quot;123&quot;) -&gt; Ok( (&#39;1&#39;, &quot;23&quot;) )<br>digit_parser.parse(&quot;23&quot;) -&gt; Ok( (&#39;2&#39;, &quot;3&quot;) )<br>digit_parser.parse(&quot;abc&quot;) -&gt; Err(&quot;Could not find a digit&quot;)</pre><p>The general idea is if you find one of the tokens you are looking for, then you return that token and the follow. If none of them match then you return an Error.</p><p>This is what the operation would look like in Rust. We take two Parsers (doesn’t matter what the parser is interested in), and try to parse the input string. If the 1st parser is successful you would return Either::Left or if the 2nd parser is successful you return Either::Right. Error if neither matches. An Either is how we represent an OR here :)</p><pre>pub struct OrParser&lt;P1, P2&gt;(P1, P2);<br><br>// Implement Parser&lt;Either&lt;U,V&gt;&gt; for OrParser<br>// The OrParser takes in two parsers as it&#39;s input.<br><br>// The implementation makes use of the parsers and<br>// returns the first valid result that is available<br><br>impl&lt;P1, P2, U, V&gt; Parser&lt;Either&lt;U, V&gt;&gt; for OrParser&lt;P1, P2&gt;<br>where<br>    P1: Parser&lt;U&gt;,<br>    P2: Parser&lt;V&gt;,<br>{<br>    fn parse_from(&amp;self, val: &amp;String) -&gt; ParseResult&lt;Either&lt;U, V&gt;&gt; {<br>        self.0<br>            .parse_from(val)<br>            .map(|(val, follow)| (Either::Left(val), follow))<br>            .or_else(|_| {<br>                self.1<br>                    .parse_from(val)<br>                    .map(|(val, follow)| (Either::Right(val), follow))<br>            })<br>    }<br>}</pre><p>Notice that what we are parsing is a digit character. We will need to convert these into an unsigned integer. How do we do it?</p><h3>Map</h3><p>What does a Map combinator do?</p><p>Before we dive into that, what does a map do in the normal world? A map is a higher order function that takes a Collection (list or a set) of items and a function. The function is applied on each item to produce an output.</p><blockquote>The concept of a map is not limited to lists/sets and can be applied to other abstract containers.</blockquote><pre>map(Collection[U], function U -&gt; V) -&gt; Collection[V]<br>// U is the input<br>// The function transforms U to V<br>// V is the output</pre><pre>list = [1, 2, 3, 4]<br>double = x -&gt; 2*x // function that doubles the value of input<br>new_list = map(list, double)<br>// [2, 4, 6, 8]</pre><p>In the above example, both the input and output are a list of numbers. But all the items in the new list were doubled in value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*aBCeVqE-kY3SGSJt.png" /><figcaption>Image from fsharpforfunandprofit.com</figcaption></figure><blockquote>What does a Map combinator do?</blockquote><p>Well it’s pretty much the same thing as our traditional map, but now instead of a Collection we have a Parser as a input.</p><pre>// Parser(A) with a function(A) -&gt; B gives us Parser(B)<br>// A and B can be any Token or combination of Tokens<br>function map(parser: Parser(A), mapper: function(A) -&gt; B) -&gt; Parser(B)</pre><p>What we are looking for is mapping the character to a unsigned integer that represents the digit:</p><pre>&#39;0&#39; -&gt; 0<br>&#39;1&#39; -&gt; 1<br>&#39;2&#39; -&gt; 2<br>.. <br>.. <br>&#39;9&#39; -&gt; 9</pre><p>If we are representing the Digit as an enum of integer values from 0 to 9, then digit would have a method like:</p><pre>enum Digit {<br>  ...<br>  function from(value: Char) -&gt; Digit;<br>  // Digit is an enum of 0 to 9<br>}</pre><p>The final digit parser:</p><pre>raw_digit_parser = Token(&#39;1&#39;) or Token(&#39;2&#39;) ....<br>digit_parser = map(raw_digit_parser, Digit::from)<br>digit_parser.parse(&quot;123&quot;) -&gt; Ok( (Digit(1), &quot;23&quot;) )<br>digit_parser.parse(&quot;23&quot;) -&gt; Ok( (Digit(2), &quot;3&quot;) )<br></pre><p>We can recognize a digit now! Onto the next hurdle — recognize all digits in a number :)</p><h3>Zero or Many</h3><p>The idea behind Zero or Many is pretty simple — if there are multiple instances of the same token — Zero or More -&gt; parse them and return all of them. This is also popularly known as Many0 in combinator libraries.</p><pre>Many0(Token(&#39;1&#39;)).parse(&quot;1112&quot;) -&gt; Ok( ([&#39;1&#39;, &#39;1&#39;, &#39;1&#39;], &quot;2&quot;) )<br>Many0(digit_parser).parse(&quot;123&quot;) -&gt; Ok( ([Digit(1), Digit(2), Digit(3)] , &quot;&quot;) )</pre><p>Since we are okay with 0 tokens being available in the string that is being parsed, a Many0 parser will never error out.</p><pre>Many0(Token(&#39;1&#39;)).parse(&quot;234&quot;) -&gt; Ok( ([], &quot;234&quot;) )</pre><p>Great, is it in line with what we need from a number?</p><p>Close, but not exactly — a number has at least one digit. Well technically a number has to start with a non-zero digit but for the purposes of this exercise let’s assume that prefixed 0’s will be ignored.</p><p>Before we think about this hurdle, let’s talk about AND. We already covered OR but what does AND mean in the context of a parser?</p><h3>AND</h3><p>Let’s say we want to parse one digit and an alphabet.</p><pre>alphabet = Token(&#39;a&#39;) or Token(&#39;b&#39;) .... or Token(&#39;z&#39;) or Token(&#39;A&#39;) .. or Token(&#39;Z&#39;)<br>parser = digit and alphabet <br>// parser = and(digit, alphabet) is also a valid combinator<br>parser.parse(&quot;1a&quot;) -&gt; Ok((&#39;1&#39;, &#39;a&#39;), &quot;&quot;)<br>parser.parse(&quot;.$&quot;) -&gt; Error(&quot;Could not find a digit&quot;)</pre><p>So it’s the same as saying parse with a digit, get the remaining string and run it through the 2nd parser. This gives us two tokens and the remaining string.</p><p>This is how I represented an AND for two parsers in Rust.<br>A tuple of parser represents an AND and the idea is to pass the follow from the first parse operation onto the 2nd parser. If there are failures along the way, there is an early exit and the parser returns Error whenever it can.</p><pre>impl&lt;P1, P2, X, Y&gt; Parser&lt;(X, Y)&gt; for (P1, P2)<br>where<br>    P1: Parser&lt;X&gt;,<br>    P2: Parser&lt;Y&gt;,<br>{<br>    fn parse_from(&amp;self, val: &amp;String) -&gt; ParseResult&lt;(X, Y)&gt; {<br>        self.0.parse_from(val).and_then(|(x, follow)| {<br>            self.1<br>                .parse_from(&amp;follow)<br>                .map(|(y, remaining)| ((x, y), remaining))<br>        })<br>    }<br>}</pre><h3>One or Many</h3><p>As the name suggests, the parser expect atleast one instance of the token to be available in the string. This is commonly known as a Many1 Parser.</p><p>Okay, can we now think of a way to represent a Many1 with whatever we have so far?</p><pre>Many1(parser) = parser and Many0(parser)</pre><p>If we have atleast one token, then the first parser works, Many0 returns the remaining. If there are zero tokens, then the first parser fails and errors out.</p><pre>many1_digit = Many1(digit)<br>many1_digit.parse(&quot;123&quot;) -&gt; Ok( ((&#39;1&#39;, [&#39;2&#39;, &#39;3&#39;]), &quot;&quot;))<br>many1_digit.parse(&quot;abc&quot;) -&gt; Error(&quot;Digit not found&quot;) </pre><p>Note that a Many1 based on our currently implementation provides a tuple of (Token, List[Token]) and what we need is a single list. We would ideally want to flatten this to just one List[Token].</p><p>So here we want a Function that takes in a tuple of (Token, List[Token]) and return us List[Token]</p><pre>concat = ( token: Token, list : List[Token] ) -&gt; [token].concat(list)<br>// A-&gt; (Token, List[Token])<br>// B-&gt; (List[Token])</pre><pre>digits = map(many1_digit, concat)<br>digit.parse(&quot;123&quot;) -&gt; Ok( ([Digit(1), Digit(2), Digit(3)], &quot;&quot;) )</pre><h3>Putting everything together</h3><p>The final piece we need is a way to “map” a list of digits into a number.</p><pre>[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;] -&gt; 123</pre><p>How would we go about doing that?</p><pre>123 -&gt; 100 * 1 + 2 * 10 + 3 * 1</pre><p>For a list of digits, the map function we are looking for would look something like this:</p><pre>reduce_digits = (digits) -&gt; digits.reduce(0, (acc, d) -&gt; acc*10 + d)</pre><p>Given some digits, reduce it in a way where we start with our state as 0 and keep multiplying it by 10 (radix) and add the digit.</p><pre>[1, 2, 3]<br>1 -&gt; 0*10 + 1 -&gt; 1<br>2 -&gt; 1*10 + 2 -&gt; 12<br>3 -&gt; 12*10 + 3 -&gt; 123</pre><p>The final parser looks something like this:</p><pre>raw_digit_parser = Token(&#39;0&#39;) or Token(&#39;1&#39;) or Token(&#39;2&#39;) or .. or Token(&#39;9&#39;)<br>digit_parser = map(raw_digit_parser, Digit::from) <br>concat = ( token: Token, list : List[Token] ) -&gt; [token].concat(list)<br>digits_parser = map(many1(digit_parser), concat)<br>reduce_digits = (digits) -&gt; digits.reduce(0, (acc, d) -&gt; acc*10 + d)<br>number_parser = map(digits_parser, reduce_digits)<br>number_parser.parse(&quot;123&quot;) -&gt; Ok( (123, &quot;&quot;) )<br>number_parser.parse(&quot;123abc&quot;) -&gt; Ok( (123, &quot;abc&quot;) ) </pre><h3>Conclusion</h3><p>While it might seem like a lot of work to parse something as simple as a number, the underlying idea is that once you have all the smaller pieces in place, creating a parser on top of the pieces is as simple as declaring them.</p><p>Think about this:</p><ol><li>If we wanted to move onto parsing a negative number — what is the effort to get that done?</li><li>Parse an integer</li><li>a floating point number</li></ol><p>I’d like to extend a special shoutout to <a href="https://www.artful.dev/">Sudarsan</a>, whose guidance and enthusiasm introduced me to the fascinating world of parser combinators. Here’s to the mentors who ignite our curiosity and propel us forward in our exploration of new concepts and technologies.</p><ol><li>Code sample for the <a href="https://github.com/vss96/number-parser">Number parser</a> in Rust</li><li><a href="https://docs.rs/nom/latest/nom/">Nom</a> — a Rust combinator library</li><li><a href="https://github.com/stephan-tolksdorf/fparsec?tab=readme-ov-file">Fparsec</a> — F# combinator library</li><li><a href="https://fsharpforfunandprofit.com/posts/understanding-parser-combinators-2/">Building a useful set of parser combinators</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b55b9c4c904" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/making-sense-of-parsers-0b55b9c4c904">Making Sense of Parser Combinators</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object detection through Ensemble of models]]></title>
            <link>https://medium.com/inspiredbrilliance/object-detection-through-ensemble-of-models-fed015bc1ee0?source=rss-d178f4aa3c84------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed015bc1ee0</guid>
            <category><![CDATA[detectron2]]></category>
            <category><![CDATA[faster-r-cnn]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[yolov3]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Vikas S Shetty]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 14:09:36 GMT</pubDate>
            <atom:updated>2020-11-23T16:50:48.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*fTc7_JVkDUofF2yr.png" /></figure><h3>Introduction</h3><p>Ensembling machine learning models is a common practice and has been used in multiple scenarios as they combine the decisions from multiple models to improve the overall performance but when it comes to DNN(Deep Neural Networks) based Object detection models it’s not as simple as merging the results.</p><h3>Need for Ensembling</h3><p>In order to get good results with any model, there are certain criteria (data, hyperparameters) that need to be fulfilled. But in the real world scenario, you might either end up with bad training data or might have a hard time figuring out appropriate hyperparameters. In these situations, ensembling multiple weaker performing models can help get the results that you need. In one sense, ensemble learning may be thought of as a way to compensate for poor learning algorithms by performing a lot of extra computation. On the other hand, the alternative is to do a lot more learning on one non-ensemble system. An ensemble system may be more efficient at improving overall accuracy for the same increase in compute, storage, or communication resources by using that increase on two or more methods, than would have been improved by increasing resource use for a single method.</p><h3>Seems too good to be true, any drawbacks?</h3><ul><li>Harder to debug or understand the predictions since the boxes are drawn up from multiple models.</li><li>Inference time increases based on the models and the number of models used.</li><li>Experimenting with different models to get the appropriate set of models is a time-consuming affair.</li></ul><h3>Different methods for Ensembling</h3><ol><li>OR method (Affirmative): A box is considered if it’s generated by at least one of the models.</li><li>AND method (Unanimous): A box is considered if all of the models generate the same box (the box is considered the same if IOU &gt; 0.5).</li><li>Consensus method: A box is considered if the majority of the models generate the same box (ie) if there are m models and (m/2 +1) models generate the same box, that box is considered as valid.</li><li>Weighted Fusion: This is a novel method which was created to replace NMS and it’s shortcomings.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xkqDfkPx5DrdUjU3" /><figcaption>Various Ensemble methods</figcaption></figure><p>In the above example, predictions for the OR [Affirmative] method get all the required object boxes but also ends up with a false positive, Consensus method misses out the horse and the AND [Unanimous] method misses out both the horse and the dog.</p><h3>Evaluation</h3><p>For evaluating the different ensembling methods, we are going to track the following parameters:</p><ol><li><strong>True Positives</strong>: When the predicted box matches the ground truth</li><li><strong>False Positives</strong>: When the predicted box is wrong</li><li><strong>False Negatives:</strong> No prediction even though ground truth exists.</li><li><strong>Precision</strong>: measures how accurate your predictions are. i.e. the percentage of your predictions are correct [TP/ (TP + FP)]</li><li><strong>Recall</strong>: measures what percentage of ground truth was predicted [TP/ (TP + FN)]</li><li><strong>Average Precision</strong>: Area under the precision-recall graph (In this case all points are considered for the area under the graph)</li></ol><h3>Models being used</h3><p>To understand how ensembling helps, we have provided the results for standalone models that we used to experiment.</p><h4>1. YoloV3:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*da6idsQXDxTzkiTq" /></figure><h4>2. Faster R-CNN — ResNeXt 101 [X101-FPN]:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5_NgN5MbzlADT4nf" /></figure><h3>Ensemble Experiments</h3><h4>1. OR — [YoloV3, X101-FPN]</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GKEPHP4cwaqEW9y6" /></figure><p>If you notice closely, the number of FPs has increased which in turn reduces the precision. At the same time, the number of TPs has increased which in turn increases the recall. This is a general trend that is observed when you use the OR method.</p><h4>2. AND — [YoloV3, X101-FPN]</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WfGGKscdRG0w_ba_" /></figure><p>Opposite to what we observed with the OR method, in the AND method we end up with high precision and lower recall since almost all of the False Positives are removed since most FPs for both YoloV3 and X101 are different.</p><h4>How Weighted Boxes fusion works</h4><p>In the NMS method, the boxes are considered as belonging to a single object if their overlap, Intersection over Union (IoU) is higher than some threshold value. Thus, the boxes filtering process depends on the selection of this single IoU threshold value, which affects the performance of the model. However, setting this threshold is tricky: if there are objects side by side, one of them would be eliminated. NMS discards redundant boxes and thus cannot produce averaged localization predictions from different models effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*MpIIekOPfq1omP90" /></figure><p>The main difference between NMS and WBF is that WBF is trying to make use of all the boxes instead of discarding them. In the above example, the red box is the ground truth and the blue boxes are the predictions made by multiple models. Notice how redundant boxes are removed by NMS but WBF creates a brand new box (fused box) by considering all the prediction boxes.</p><h4>3. Weighted Boxes Fusion — [Yolov3, X101-FPN]</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*reaJkNkGLblbmB0R" /></figure><p>We used a weight ratio of 2:1 for YoloV3, X101-FPN respectively. We also tried increasing the ratio in favour of X101-FPN (since it was better performing) but didn’t see any drastic difference in the performance. From what we had read from the paper of Weighted Boxes fusion, the results that the authors noticed was an increase in AP but as you can see, WBF with YoloV3 and X101-FPN does not outperform the OR method by a lot. One more thing that we noticed in the paper was that most of the experiments involved at least 3 or more models which lead us to think as to what would happen if we added more models to the mix.</p><h4>4. Weighted Boxes Fusion — [Yolov3, X101, R101, R50]</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Y8W2-29nbTGiUw-" /></figure><p>For the final experiment, we ended up using YoloV3 along with 3 models that we had trained in Detectron2 [ ResNeXt101-FPN, ResNet101-FPN, ResNet50-FPN]. Obviously, there is a jump in recall (about 0.3 from traditional methods) but the jump in AP isn’t a lot. Also, one more thing to notice is that the number of False Positives shoots up when you add more models to the WF method.</p><h3>Conclusion</h3><p>Ensembling can be a great way to improve performance when the models that complement each other are used but it also comes at the cost of speed at which inference is done. Based on the requirements, one can decide as to how many models, which method to go for, so on and so forth. But from the experiments that we conducted, the amount of performance jump doesn’t seem proportionate enough to the resources and inference time that is needed to run these models together.</p><h3>References</h3><ol><li>Weighted Fusion boxes: <a href="https://arxiv.org/pdf/1910.13302.pdf">https://arxiv.org/pdf/1910.13302.pdf</a></li><li>Github repo for WBF: <a href="https://github.com/ZFTurbo/Weighted-Boxes-Fusion">https://github.com/ZFTurbo/Weighted-Boxes-Fusion</a></li><li>Ensemble methods for Object detection: <a href="https://www.unirioja.es/cu/joheras/papers/ensemble.pdf">https://www.unirioja.es/cu/joheras/papers/ensemble.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed015bc1ee0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/object-detection-through-ensemble-of-models-fed015bc1ee0">Object detection through Ensemble of models</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YoloV3 on TPU]]></title>
            <link>https://medium.com/inspiredbrilliance/yolov3-on-tpu-53cd7f6c0faf?source=rss-d178f4aa3c84------2</link>
            <guid isPermaLink="false">https://medium.com/p/53cd7f6c0faf</guid>
            <category><![CDATA[research-and-development]]></category>
            <category><![CDATA[logo-detection]]></category>
            <category><![CDATA[yolov3]]></category>
            <category><![CDATA[tpu]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Vikas S Shetty]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 11:49:10 GMT</pubDate>
            <atom:updated>2020-08-28T11:49:10.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3TY-7Ze-y9c6yYry.png" /></figure><h4>Problem Statement</h4><p>Given a set of images, detect the target logos (localise and classify). There are multiple ways to solve the problem of object detection and localization but for this particular walkthrough, we made use of YoloV3.</p><h3>Dataset</h3><p>We decided to evaluate the effectiveness of Yolov3 on logos and picked two random logos from datasets that are available for research purposes. For this, we used the Belgalogos¹, Web-2m² dataset to procure images and annotations. Web-2m images needed manual effort to annotate the images. The code that we used relied on Pascal VOC XML files for getting annotations of the images.</p><h3>Training Data</h3><p>We had roughly around 2.7k images (logo1, logo2 together) and we relied on augmentation to create 5 augmented instances per image in the training set. We also added around 900 negative sample images (Neither has logo1 nor logo2) to reduce the number of false positives.</p><p>For augmentation we used ImgAug and applied the following techniques randomly:</p><ul><li>Horizontal flipping</li><li>Vertical flipping</li><li>Cropping</li><li>Padding</li><li>Rotation by 60 to 90 degrees</li><li>Hue</li><li>Color temperature</li><li>Brightness</li><li>Sharpening</li><li>Blurring</li><li>Embossing with Gaussian filter, median filter, etc.</li><li>Elastic transformation</li><li>Perspective transformation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cc3tPdl0PguvxRVKii2-iQ.png" /></figure><h3>Validation Data</h3><p>For validation data, we got around 800 images from similar sources as well as videos (usually ads). We made sure that there wasn’t an imbalance between the number of logo1 and logo2 images (or the validation set becomes biased).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOUUfffwvo68X-xnbmJQog.png" /></figure><h3>Results on GPU:</h3><p>We used the dataset that we had prepared and used YoloV3-SPP as our model to detect Logo1 and Logo2. As seen we were able to do pretty well and get precision and recall above 85%.</p><p>Throughout the post, we will be concentrating on the results we got on the validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9qYDj5p1R6_UwPmb" /></figure><h3>Why TPU?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*bD7Glie4ee31ryVS.gif" /></figure><p>TPUs have been shown to give a 10x performance increase over high-end GPU while being 50% costlier than GPU. It felt like the next logical step was to try training YoloV3 on TPU and finding if we could achieve similar results while reducing the time taken and the cost.</p><h3>Cost and Time Benefits:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LBQtrxmQIe6f7t9t" /></figure><p>By looking up the prices of standard GPUs like V100 and TPUs in GCP, it’s clear that TPUs are cost-effective and can also reduce the time it takes to train a model. The above information was recorded for a dataset of roughly 23k images.</p><h3>Changes that were required:</h3><ol><li><strong>Porting Keras changes to Tensorflow.keras</strong>: This was a minor change, mostly imports were changed and everything else almost remained unchanged.</li><li><strong>Using Tensorflow dataset API instead of Keras generators</strong>: Google recommends using the TensorFlow dataset so that the TPU can be efficiently used. The dataset API also comes with options of prefetching data, parallelizing the network calls that are made to fetch the data which reduces the waiting time for the TPU.</li><li><strong>Moving to TF records</strong>: Along with tf.Dataset, Google also recommends using TF records to have the fastest performance possible. In an experiment that Google conducted, they were able to demonstrate that using TF records gives at least a 2x speedup. We were able to use the Keras generators that we previously used to create the required TF records. Since the training data’s tensors were big (around 30gb), we had to shard the records before storing them on the GCP bucket.</li><li><strong>Changing Model implementations to use static Tensors (shapes were fixed): </strong>These changes were mostly in the Keras model implementation where certain tensors were set in a dynamic way( the shape of the tensor is decided at runtime). This took a while to debug since we had to find the exact sizes of the tensors being used. TPUs can’t work with dynamically shaped tensors and need to know the exact size of the tensor before processing them.</li></ol><h3>Initial Results (LR : 8*10e-4, Epochs : 5+ 50)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRH0Plve7ySbkjbG_qGubA.png" /></figure><h3>Possible reasons for not being closer to GPU run:</h3><p>The initial results were far off from the GPU run, so we had to debug and figure out why this was the case. After a little bit of research and looking up issues that were common with TPUs, this is what we came up with.</p><ol><li>We used tf.keras adam instead of tf.train adam which does not work well on TPU. Generally, SGDs work better on TPUs³.</li><li>If your model uses batch normalization, a total batch size less than 256 (for example, less than 32 per core) might reduce accuracy⁴. [we’re using 64 as BS and every convolution block has got BN layer for Yolov3]</li><li>The ideal batch size when training on the TPU is 1024 (128 per TPU core) since this eliminates inefficiencies related to memory transfer and padding⁵.</li><li>The way warmup is implemented in Yolo might work differently in different environments. So one of the ideas was to reduce the number of warmup epochs and see how it affected the performance.</li><li>The learning rate has to be changed appropriately whenever the batch size is increased or decreased, but by what factor was still an uncertainty.</li></ol><h3>Results with Lesser Warmup epochs ( LR: 8*10e-4, Epochs: 2+53, Optimizer: tf.keras Adam):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dwAz3AprcRf4X-ASJzPIg.png" /></figure><h3>Results with Lower learning rate(LR: 10e-4, Epochs: 2+53, Optimizer: tf.keras Adam)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jC3oHQFWhoGpm2x7YGrcKA.png" /></figure><h3>Results with Tf Train Adam(LR: 8*10e-4, Epochs: 2+53, Optimizer: tf.train Adam):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78nwY3jXyaNTNAJO0YugAg.png" /></figure><h3>Results with Variational SGD(LR: 10e-4, Epochs: 2+53, Optimizer: tfp VariationalSGD)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANqUaKB09f9bpnMgyHPjaw.png" /></figure><h3>Future Work:</h3><ul><li>Even though we tried out both Adam and SGD there is a possibility for better convergence with different learning rates and also there is room for experimentation with different optimisers and LR schedulers.</li><li>In the case of Variational SGD (which implements burn-in), there are a lot of parameters which can be changed for more experimentation.</li><li>It is possible that the model might converge better on TPU if it is run for more epochs. Only by changing the parameters and experimenting can we confirm whether it’s possible or not.</li><li>Our implementation relied on tf.keras models and using <strong>.fit()</strong> to converge the model on the dataset. There are implementations of Yolov3 which use pure TensorFlow functions to represent the model and manual training loops which calculate the losses per iteration⁶.</li></ul><h3>Conclusion:</h3><p>From the different experiments that we tried out, we were still not able to get closer to the GPU equivalent run for the same dataset. A batch size 256 or more is required for batch normalization to work properly on TPU, which requires us to use high-end instances that incur higher cost. So it makes more sense to use TPUs when the amount of data that we have is huge (&gt; 1 million images).</p><p>[1]: Alexis Joly and Olivier Buisson, <a href="http://portal.acm.org/citation.cfm?id=1631361#">Logo retrieval with a contrario visual query expansion</a>, In Proceedings of the Seventeen ACM International Conference on Multimedia, 2009.</p><p>[2]:<a href="https://openaccess.thecvf.com/content_ICCV_2017_workshops/papers/w5/Su_WebLogo-2M_Scalable_Logo_ICCV_2017_paper.pdf">https://openaccess.thecvf.com/content_ICCV_2017_workshops/papers/w5/Su_WebLogo-2M_Scalable_Logo_ICCV_2017_paper.pdf</a></p><p>[3]:<a href="https://medium.com/bigdatarepublic/cost-comparison-of-deep-learning-hardware-google-tpuv2-vs-nvidia-tesla-v100-3c63fe56c20f">https://medium.com/bigdatarepublic/cost-comparison-of-deep-learning-hardware-google-tpuv2-vs-nvidia-tesla-v100-3c63fe56c20f</a></p><p>[4]:<a href="https://cloud.google.com/tpu/docs/troubleshooting#multi-core-training">https://cloud.google.com/tpu/docs/troubleshooting#multi-core-training</a></p><p>[5]:<a href="https://cloud.google.com/tpu/docs/troubleshooting#batch-too-small">https://cloud.google.com/tpu/docs/troubleshooting#batch-too-smal</a>l</p><p>[6]:<a href="https://github.com/nikhillovestech/Yolov3-TPU">https://github.com/nikhillovestech/Yolov3-TPU</a></p><p>[7]:<a href="https://cloud.google.com/tpu/pricing#pod-pricing">https://cloud.google.com/tpu/pricing#pod-pricing</a></p><p>[8]: <a href="https://www.tensorflow.org/guide/tpu">https://www.tensorflow.org/guide/tpu</a></p><p>[9]: <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord">https://www.tensorflow.org/tutorials/load_data/tfrecord</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53cd7f6c0faf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/yolov3-on-tpu-53cd7f6c0faf">YoloV3 on TPU</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>