<?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 BenMauss on Medium]]></title>
        <description><![CDATA[Stories by BenMauss on Medium]]></description>
        <link>https://medium.com/@benmauss?source=rss-e0c9e4a3e1df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iv1TfG7yBSfRmUX_sSMTsA.jpeg</url>
            <title>Stories by BenMauss on Medium</title>
            <link>https://medium.com/@benmauss?source=rss-e0c9e4a3e1df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:53:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benmauss/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[Basic Principles of Probability]]></title>
            <link>https://benmauss.medium.com/basic-principles-of-probability-421f018fa763?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/421f018fa763</guid>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 20:25:42 GMT</pubDate>
            <atom:updated>2021-04-19T20:25:42.788Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Review of Probability for People Who Hate Math</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*qumDQCsobG8IaX9y-SiLFw.png" /></figure><p>Since the dawn of civilization, the world’s greatest minds have been spent their lives seeking the answer to the question:</p><blockquote>How do I win at back alley dice?</blockquote><p>Ok, so that’s obviously not true. This question does hint at one that actually <em>has </em>plagued humanity for thousands of years:</p><blockquote>What is going to happen?</blockquote><p>Think about it. Pharaohs, kings, magistrates, tribal chieftains, and superstitious everyday people have sought out counsel from wisemen, soothsayers, oracles, prophets and prophetesses, priests and priestesses, palm/tarot readers, fortune tellers, and phoneline psychics to get the answer to this question. Consider the billions, if not trillions, of dollars that have been spent over the last century on stock brokers, actuaries, consultants, and developing machine learning algorithms to predict how investments will turn out.</p><p>All of that money and so many resources have been spent with the intention of predicting the future. Why? Well, because the future is unknown, and, according to H. P. Lovecraft, the oldest and strongest fear is the fear of the unknown (Little did he know that it’s actually the <a href="https://www.washingtonpost.com/news/wonk/wp/2014/10/30/clowns-are-twice-as-scary-to-democrats-as-they-are-to-republicans/">fear of Public Speaking</a>, at least in America). We’re afraid that all that we’ve built today will vanish tomorrow due to some unforeseen event. Just ask a <a href="https://www.youtube.com/watch?v=Gi6FcI2wFrw">YouTube animator</a> that was around before 2012. They’ll be happy to tell you how a change in YouTube’s algorithm took them from a modest income, to nearly unsustainable. In fact, many major YouTubers have a deep rooted anxiety that one day their channel will also become unsustainable due to a sudden change in the algorithm that doesn’t suit their platform. While this is a little off the beaten path, but it goes to show you that these fears are rooted in reality. It’s not an exaggeration to say that people can go from “rags to riches” and vice versa overnight. Just recently we had GameStop’s stock prices skyrocketing thanks to a band of people on Reddit and a few tweets from Elon Musk and a few other popular, hedge fund personalities.</p><p>So how do we go about predicting the future? Well, we first need a decent grasp of probability. To make this fun, we’ll use Back Alley Dice to provide context.</p><h3>A Roll of the Dice</h3><p>Let’s look at a normal, 6-sided die. It’s got six sides, each with a number value 1 through 6. The general consensus is that the probability of rolling a 6 is 1/6th. Is that always true? Not necessarily. What if it’s weighted? How would we measure the probability then? Why, through observation!</p><p>Let’s go ahead and simulate rolling a single die.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*LahgrYJmD0tgRmnFI4Iy6Q.png" /></figure><p>In this function, we have a dictionary whose keys are a <strong>set </strong>of all the possible<strong> </strong>outcomes. We simulate a die rolling with a for loop and each time it rolls a number we update the dictionary (recording our observations). Then the function returns the dictionary so we can view the outcomes.</p><p>Let’s see what happens after 10 rolls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*NSWkOfS_3t4dEvaHVWaPVA.png" /></figure><p>So from 10 rolls, it would seem that you have a greater chance of rolling a 1. Let’s try this out a few more times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*Ym08C2pQOZYq9xCchcbh9g.png" /><figcaption>100 Rolls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*nZ_VUpld-DJd6oK5TtIdiQ.png" /><figcaption>1,000 Rolls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*2sG4z0CvcO_48927DACKiQ.png" /><figcaption>1,000,000 Rolls</figcaption></figure><p>As we can see, the more rolls we record, the more our possible outcomes converge. In other words, the odds for each possible outcome appear to be equal. So the die is fair! Let’s check to see if it equates to 1/6th.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*0mXmqR2mHsmjpW6AlKlQVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*6Y8lCkNBZL3okRizT3KszQ.png" /></figure><p>To calculate the probability of an event, you need the total number of times the event occurred and divide it by the total number of observations. In our case, the event is rolling a six. The number of observations we recorded was 1 million. So in 1 million rolls we rolled six 166,889 times. When we do the math we get 0.166974, which lines up pretty close to 1/6th!</p><p>So why did I spend time proving something that you already know? To outline how you determine the probability of an event. Perform an experiment, record your observations, count the number of times the event occurred and then divide it by the total number of observations.</p><p>Now let’s get to gambling!</p><h4>Back Alley Dice!</h4><p>So Back Alley dice is just a less than legal way of playing Craps. You roll 2 dice at a wall or stoop and add up their values. If you roll a 7 or an 11, you win. If you roll a 2, 3, or 12, you lose. If you roll any other number, you must roll that number again before you roll a 7, 11, or 2, 3, or 12. Fail to do so, and you lose. You can also just make bets on what you’ll roll. What are the odds of rolling even rolling a 7, though? Let’s find out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*_bPVQFXun0gjssdQt5b4Mg.png" /></figure><p>Pretty similar to our first, function. The main difference is that we have 2 dies and we add their values together. Now, let’s run our simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*weAQry3h1x7MMhbvD95wQQ.png" /><figcaption>10 Rolls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*pNHN4xUifI_HLd_w1hZoQA.png" /><figcaption>100 Rolls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*MK_M5Mb6unzarrON0APZXw.png" /><figcaption>1,000 Rolls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*8_NpZ9ew1Au9VxfcBi19sQ.png" /><figcaption>1,000,000 Rolls</figcaption></figure><p>So it appears that 7 is actually the most common outcome! But why? Well, it’s because we aren’t measuring the probability of specific sides of a die, but, rather we’re measuring how many different combinations add up to specific sums. Let’s list them out.</p><blockquote>Important Note: We’ll list the pairs like such: (die1, die2).</blockquote><ul><li>2: (1, 1)</li><li>3: (1, 2) (2, 1)</li><li>4: (1, 3) (2, 2) (3, 1)</li><li>5: (1, 4) (2, 3) (3, 2) (4, 1)</li><li>6: (1, 5) (2, 4) (3, 3) (4, 2) (5, 1)</li><li>7: (1, 6) (2, 5) (3, 4) (4, 3) (5, 2) (6, 1)</li><li>8: (2, 6) (3, 5) (4, 4) (5, 3) (6, 2)</li><li>9: (3, 6) (4, 5) (5, 4) (6, 3)</li><li>10: (4, 3) (5, 5) (4, 1)</li><li>11: (5, 6) (6, 5)</li><li>12: (6, 6)</li></ul><p>As we can see, there are more combinations that add up to 7 than any other number (oddly enough, 1/6th). So when it comes to Back Alley dice, choose to bet by the roll, and then bet on a 7 (6 and 8 are also pretty solid).</p><p>This does raise another question: Why choose the most common roll (7) to be a winning number in Back Alley dice and, by extension, Craps? Well, it’s to keep you gambling! You’ll lose eventually.</p><h3>Summary</h3><p>Always bet on 7.</p><p>But seriously, all predictions are based on understanding probabilities. The probability of an event can be expressed mathematically by taking the number of successful events and dividing it by the total number of attempts. When it comes to probabilities, you can never really have enough data. The more observations you have, the more likely you are to find the true probability of an event</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=421f018fa763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP and D&D: Encapsulation]]></title>
            <link>https://levelup.gitconnected.com/oop-and-d-d-encapsulation-4e7ccbd24319?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e7ccbd24319</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dnd-5e]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 21:16:40 GMT</pubDate>
            <atom:updated>2021-04-14T17:32:55.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using D&amp;D to Understand the Four Pillars of OOP, Part IV</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGWNbWACCxkqlHP2JfeTxw.png" /></figure><p>So far, we’ve covered three out of the four Pillars of Object-Oriented Programming: Inheritance, Abstraction, and Polymorphism. Today, we’ll be wrapping this series up with the final pillar: Encapsulation (and no, I did not plan the series out to set up that pun; It’s just a happy accident). But first, a brief recap!</p><h4>Inheritance</h4><p>If you remember, Inheritance is the ability of a class with hierarchal relationship (Parent-Child classes) to pass on data, variables, and methods to their subclasses. If Animal class has a method called speak(), then any child class of Animal (such as Fox) will inherit that method.</p><h4>Abstraction</h4><p>This is the ability for the developer to hide source code and only provide the user with the details needed to use the methods and data stored in the classes and packages. This is great for both the developer and the user. The developer can protect their source code and the user doesn’t need to write out complex code for themselves to perform a function. If you’ve ever used the pd.read_csv() method from the Pandas library to convert a .csv file to a dataframe, then you’ve benefitted from the power of Abstraction. You don’t need to know all of the underlying code and processes. You just need to know what method to call and the arguments to pass. Meanwhile, Pandas can protect their intellectual property.</p><h4>Polymorphism</h4><p>I gotta make a shout-out to <a href="https://angelohulshout.medium.com/">Angelo Hulshout</a> for providing me with a much better definition for Polymorphism. Last time, I made the mistake of saying that Polymorphism allowed classes to share the same name but serve “different purposes”. While this is technically possible, it’s a terrible idea. Consider the following situation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*W3yfbQUXvzHu9rBosN9sxg.png" /></figure><p>Here, we made the Animal class with the speak() method. Fox class is a child of the Animal class, because a fox IS-AN animal. The Fox class will initialize all Fox objects in a “hungry” state. Then, we decided to use method overriding to repurpose the speak() method (which it inherited from the parent Animal class) so that it ‘feeds’ our fox and changes the hunger state.</p><p>As you can see, the code still works, but it’s also very dumb and illogical. Why not make a feed() method instead? We could have provided an implementation of the speak() so that it printed out sounds that are unique to the fox, but no! We chose poorly and now must reap the consequences of our foolishness.</p><p>Anyway, Angelo pointed this problem out to me and provided a better definition:</p><blockquote>Polymorphism allows different implementations of the same functionality.</blockquote><p>In other words, classes can provide different implementations for a method to achieve the same functionality. Thus, the speak() method can be <em>implemented </em>differently between the Animal and Fox classes, but they still serve the same function: make the object “speak”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*r_E3xVR0e4IgskV5Czdeww.png" /></figure><p>And yes, there is more to Polymorphism than just method overriding, such as upcasting/downcasting classes and method overloading, but let’s allow this to suffice for our review.</p><p>Time to move on to Encapsulation!</p><h3>Encapsulation</h3><p>Encapsulation is the wrapping together of data and methods within a unit or class. This restricts direct manipulation of variables and data to prevent accidental modification. Let’s pull up our example of the Dragon Turtle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*EZC4l8YDi0-uElkU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*Nbs-bT2HHJSPjgrB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*NBk_TgDgVc3Vngtv.jpeg" /></figure><p>So Sentient is an abstract ancestor class from which Monster is derived. Monster is also abstract because it doesn’t provide an implementation for the inherited abstract method, calculate_hit_points(). DragonTurtle is a child of the Monster class (thus, a grand-child to Sentient). It provides an implementation for calculate_hit_points(), and is, therefore, a concrete class.</p><p>As you can see, the DragonTurtle class also provides default stats define all Dragon Turtle objects on instantiation. You’ll notice that in the initializer that the hit_points are initialized by calling the calculate_hit_points() method. This makes it so that the Dungeon Master (DM) doesn’t need to run the method after creating the object.</p><p>We do have an issue, however. Currently, all of the methods, variables, and their associated data are “public”. This means that any class (and I mean ANY) can access and modify them. That’s how vulnerable the data is.</p><p>So how do we restrict access? Well, we can either make our data <strong>protected </strong>or <strong>private</strong>.</p><h4>What’s the Difference?</h4><p>Generally speaking,<strong> protected </strong>methods and data can be accessed by any subclass, as well as any class within the same package. Take note of how I said that ANY subclass can access this data. This includes subclasses that are located in a different package. As long as they’re in the “family tree”, they can access the data.</p><p>(Again) Generally speaking,<strong> private </strong>methods and data<strong> </strong>can only be accessed from within the same class (or through Python name mangling, but don’t worry about that right now). Subclasses do not have access to these data.</p><blockquote>Note: In Python, there is no such thing as a private instance variable that can only be accessed inside the object. Instead, certain conventions have been generally implemented to achieve the same goal.</blockquote><p>So which one should we choose? Well, we do have hierarchal relationships between our three classes here, but at the same time, we don’t want anyone to change data associated with the variables. So let’s make our methods protected, and our data private. In Python, to make variables and methods protected you simply prefix them with a single underscore (e.g. self._hit_points). To make them private, you prefix them with two underscores (e.g. self.__hit_points). Let’s go ahead and do this to our Sentient class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*4cA-O1qYVSpuSxWcHKRd8g.png" /></figure><p>We’ll do the same with Monster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*1yMbv16LMw4obJsp7Ue4PA.png" /></figure><p>With that out of the way, let’s think about our DragonTurtle class. This a concrete class capable of creating objects. We want users to be able to interact with these objects. What good is it to a DM if they can make 50 different Dragon Turtles to attack a small whaling boat filled with their players if they can’t access and retrieve any of the data associated with them? Because of this, we make public “getter” and “setter” methods so that the user can interact with the object indirectly. We’ll do this with the DragonTurtle class by making a getter and setter method for hit_points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*1Z68UgvZSCUA4WNlCTuZ9w.png" /></figure><p>As you can see, our getter method get_hp() simply returns the value of the private variable. This extra degree of distance between the variable and the user/developer prevents any accidental modifications.</p><p>You may be wondering why I included a setter method for the hit-points if those are calculated via the method. Well, this is more for the sake of the DM. Say there is a player in your campaign who is just way too strong and is breaking the game. You want to create an encounter that is challenging, but not impossible for the rest of the group, while also actively trying to make sure that you can destroy that player’s character and bring balance to the campaign. The set_hp() method allows for a more “homebrew” approach.</p><p>Let’s test these methods out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*MHCc3CKBRqkzcXoe3FinVQ.png" /></figure><p>Our getter and setter both work great! Now at the bottom, you’ll noticed that we retrieved the hit-point value without using our getter method. Instead, we used Python name mangling. This is a way of circumventing the getters and setters. As you can see, you still can’t change the values without taking deliberate steps (No one accidently types x._DragonTurtle__hit_points).</p><h3>Summary</h3><p>Encapsulation is a way of hiding variables, data, and methods and protect them from accidental modification. While Python doesn’t have conventional means of creating private instance variables like C++ and Java, simple practices were adopted to help create the same effect.</p><p>With that we’ve come to the end of our discussion of the Four Pillars of OOP! There is a certain unity within these four concepts that make it so that missing one will cause the foundation of the language to collapse. They all work in symbiotic relationship, each benefitting from the other. It’s quite remarkable!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e7ccbd24319" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/oop-and-d-d-encapsulation-4e7ccbd24319">OOP and D&amp;D: Encapsulation</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP with D&D: Polymorphism]]></title>
            <link>https://levelup.gitconnected.com/oop-with-d-d-polymorphism-b1974435063b?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1974435063b</guid>
            <category><![CDATA[dnd-5e]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 19:49:37 GMT</pubDate>
            <atom:updated>2021-04-12T17:24:05.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using D&amp;D to Understand the Four Pillars of OOP, Part III</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koUn1NTGIuEaT3sG-0iuaA.jpeg" /></figure><p>Last week, we discussed Abstraction, which is the ability for a developer to only provide the details necessary to use the various classes and their methods without exposing them to the underlying code. This provides protection to your source code, as well as saving the user time since they don’t have to reinvent the wheel whenever they want to use your methods, classes, packages, etc. It’s a pretty simple concept!</p><p>We also discussed abstract classes, which are classes that have at least one undefined method. In Python, you first need to import ABC (acronym for Abstract Base Class) and abstractmethod from the abc package. We declare our class as abstract by essentially making our class a pseudo-child of the ABC class. To make an abstract method, first declare it with @abstractmethod and name your method, passing self in as an argument. We leave the method empty with pass so that other classes can set their own implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*W1V-L3sbdZ7F8HXN.png" /></figure><p>The Sentient class is now an abstract class. This means that it is not instantiable. This is because abstract classes are not used as a blueprint for objects, but for other classes. Furthermore, any child of an abstract class will also be abstract until they provide an implementation for ALL abstract methods they inherit. Hence, Monster class was also an abstract class even though it was not declared as “abstract”. It was made abstract through inheritance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*vKGm89Zy_RFNv8EIIheUkQ.png" /></figure><p>Once, an implementation is provided, the class becomes concrete and instantiable, as we saw with the DragonTurtle class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*UlGFzpdrWnDKlNa7.png" /></figure><p>This idea of how a child class can provide implementation for a method (abstract or not) provides a good segue into today’s topic: Polymorphism.</p><blockquote>Update April 12, 2021: A special thanks to <a href="https://angelohulshout.medium.com/">Angelo Hulshout</a> for taking the time to clarify the definition of polymorphism to me. Before, I misspoke, stating that methods could “share the same name but be used for different purposes.” This is <strong>very poor practice</strong>. After all, you wouldn’t want two methods called add() and have one of them print lyrics to a song! I’ve taken the liberty of updating the article accordingly with the more appropriate definition provided by Angelo.</blockquote><h3>What is Polymorphism?</h3><p>Polymorphism is really weird. In programming, polymorphism is a property that allows methods to share the same name but have different implementations. Like the word’s definition (“many-forms”) suggests, polymorphism is exhibited in different ways: Dynamic and Static polymorphism.</p><h4>Dynamic Polymorphism (in Python)</h4><p>In Python, Dynamic Polymorphism is generally achieved through Method Overriding. This is when a child class provides its own implementation for a method that it inherited from its parent class. You may remember we did this last week with the Animal and Fox classes and the speak() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*WWSKpINoYR-cD0vl.png" /></figure><p>Here, even though we have two separate implementations for a shared method, the program doesn’t get confused as to which version to use because the implementations are tied to the object’s class. This polymorphic benefit isn’t just reserved for parent-child relationships, however, as we can see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*0fRMMS0gUTn6I8XF7e2j7A.png" /></figure><blockquote>Note: While this is an example of dynamic polymorphism, this is <strong><em>not</em></strong><em> </em>method overriding. Method Overriding can only occur between classes with a parent-child hierarchy.</blockquote><p>Here, we’ve stripped the classes of their hierarchal relationship, yet Python still doesn’t get confused about which version to use since, again, the method is tied to the object’s class.</p><h4>In D&amp;D</h4><p>For this, let’s go ahead and make the Monster class concrete by providing an implementation for calculate_hit_points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*xS1CpIBvNkiUNLm6Sq-eYQ.png" /></figure><p>We based our method on a humanoid Guard, since it makes for a great baseline. Now, we’ll test that it is instantiable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*i19-qhK35Fxl91zaaz95AQ.png" /></figure><p>Ok! The class is now concrete and the method is working as expected. Now, let’s make the DragonTurtle class again and provide its own implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*5hm11DyeQHHxBdL2WKxKHQ.jpeg" /></figure><p>As you can see, the DragonTurtle class’ implementation overrides the Monster class’. This allows for more flexibility and more specified implementations.</p><h4>Why is this important?</h4><p>Well, for one, you don’t need to come up with unique names for every single method. Nor do you have to make long, complex names to differentiate between the methods. This is extremely important when you consider that programmers often think similarly. What if two programmers made a method called mean(). The only way they differ is that operates ONLY on arrays and the other works on Pandas Series. You call the methods in the exact same way. Without polymorphism, you would get an error because the programmers HAPPENED to name their functions the same, even though they operate differently. Thanks to polymorphism, however, we don’t have to worry about that.</p><h4>Dynamic Polymorphism (in Other Languages)</h4><p>It’s generally accepted that Dynamic Polymorphism is when a <em>child </em>object is assigned to a <em>parent</em>-type reference variable, but exhibit the behaviors of the child class’ methods. In essence, the object will LOOK like the parent class, but when you call one of it’s methods, it ACT like the child class. If you assign a parent object to a child-type reference variable and achieve the opposite: it will LOOK like the child class and ACT like the parent class. The same thing can be achieved in Python, but it looks a little different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*JhcR4y2LePNA2b-NLRF3jg.png" /></figure><p>In this case, the object LOOKS like an Animal, but ACTS like a Fox. The way we accomplished this was essentially by overriding the object’s speak method so that it calls the fox class’ implementation. This is different from languages like Java where you would declare the reference variable as an Animal type and assign it to an Fox object. The reason Python is different is because all variables are dynamic; they are not given a “type” in the way they are in Java.</p><p>That’s probably more confusing than it needs to be. Just remember that Dynamic Polymorphism allows you to change which implementation of a method to that of another class’ for further customization.</p><h4>Static Polymorphism</h4><p>Static Polymorphism allows a class to have multiple methods of the same name as long as they take different arguments. This is called Method Overloading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*mRb2B185vzYhnxSqKsSRCw.png" /></figure><p>Here, we’ve provided two methods with the name of add which take in different arguments. One explicitly takes in integers. The other implicitly takes in floats (implied by the round function). Despite having the same name, Python doesn’t get confused about which method to use because the parameters differ in the datatypes they accept. When floats are passed, Python knows to execute the second method. If the arguments are integers, then it executes the first defined method.</p><h4>Why is this important?</h4><p>This makes the user experience much more streamlined. Imagine how annoying it would be if the print function had to be called differently based on the datatype of the object or variable you were referencing. Having to specify print_string, print_int, print_float, print_list, etc. each time would get VERY old, VERY quick!</p><h3>Summary</h3><p>There are many benefits to Polymorphism. Method names can be reused for a better user experience and a standardized interface across different classes. You can also control what methods are applied for more customized implementation.</p><p>Next week: Encapsulation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1974435063b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/oop-with-d-d-polymorphism-b1974435063b">OOP with D&amp;D: Polymorphism</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP and D&D: Abstraction and Abstract Classes]]></title>
            <link>https://levelup.gitconnected.com/oop-and-d-d-abstraction-and-abstract-classes-70e7336a8faf?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e7336a8faf</guid>
            <category><![CDATA[dnd-5e]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 20:36:49 GMT</pubDate>
            <atom:updated>2021-03-30T17:53:22.890Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using D&amp;D to Understand the Four Pillars of OOP, Part II</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KkI25OBBscAO7gZWWQ-kA.jpeg" /><figcaption>Image Source: <a href="https://roguewatson.files.wordpress.com/2018/09/tomb-of-annihilation-session-2-aremag.jpg">RogueWatson.files.WordPress.com</a></figcaption></figure><p>Last time, we spoke at length about the principle of Inheritance in Object-Oriented Programming. Inheritance is a trait in OOP languages that allows a parent/superclass to pass down attributes, data, and methods to their child/subclasses. A major benefit of this is that developers can cut down on redundant code because they do not need to explicitly program a method over and over across many classes that have a hierarchal relationship (parent-child) since the child classes will have already inherited those methods and can pass them implicitly.</p><p>Inheritance also allows for method overriding, where a child class shares a method with its parent class, but implements it differently. Consider the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*ST79wcNOXfABSxI_fNbWJw.png" /></figure><p>As you can see, thanks to Inheritance, Fox objects have access to their parent class’ speak() method implicitly. Foxes don’t make “generic animal noises”, however. As <a href="https://www.youtube.com/watch?v=jofNR_WkoCE">Ylvis </a>once asked: What does the fox say?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*R9FoceqWF7ky_EgP2JoZ4A.png" /></figure><p>The Fox class is still a child of the Animal class, and inherits the speak() method. However, the Fox class can provide its own implementation for the method, overriding it, so that it returns something that is more tailored to the subclass. This ability opens up the floodgates to Polymorphism, which we’ll discuss more next week. For now just know that Inheritance is a very important and powerful trait in OOP languages.</p><p>Today, we’re focusing on another Pillar of OOP: Abstraction.</p><h3>What is Abstraction?</h3><p>Abstraction is only exposing the user to the information that they need, and not to the underlying code that makes it all work. Last time, I mentioned that it’s similar to the process of turning on a car. The average driver will just say that you just need to “turn the key” or “push the button”. Any gear head will tell you that these are just a small part of what happens in the process, however. But does the average driver really NEED to know the whole process in order to start their car? Nope.</p><p>It’s the same with OOP. A developer can create packages filled with complex methods and code, but the user doesn’t need to know or see all of that. They only need to know how to use it.</p><h3>Does Abstraction have anything to do with Abstract classes?</h3><p>Nope!</p><h4>So why are we talking about Abstract classes then??</h4><p>Three reasons!</p><ol><li>Abstraction is a very easy concept to understand and doesn’t take a long time to explain. If you’ve ever imported Pandas and performed methods like pd.DataFrame.isna().sum().sum() (used to find the total number of NaN values in a dataframe) , you’ve experienced the benefits of Abstraction. It’s pretty great!</li><li>If you’re like me and you learned concepts like Abstraction, Abstract classes, Interfaces, and about a dozen other subjects in such a frenzy that you scarcely remember anything that happened that weekend, you also might have had a synapse misfire and think that there’s a connection between the two.</li><li>I need to redeem myself for a lapse in judgment when it came to my implementation of OOP to D&amp;D mechanics.</li></ol><p>You might remember last time, I made a big deal about how the dice roll is the most important behavior in D&amp;D. We then made a class called DiceSet that creates a set of dice and had a method called ability_check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*-T_3L_LtxWKLtmPH.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*mRhmti3w-0Xy2chW.png" /></figure><p>I then stated that the ability_check is a behavior shared with all sentient beings in D&amp;D (player characters, monsters, and non-player characters). This is why I chose to make our next class, Sentient, a child of DiceSet. That way the Sentient class would inherit the ability_check method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*6KLXz3nWzvBL9HAA.png" /></figure><p>There’s a problem with this logic, though, which I mentioned. The point of OOP is to represent real-world objects (or fictional ones in the case of D&amp;D) in code. This means that Hierarchal relationships such as Parent-Child classes should makes sense. However, a Sentient object is NOT a DiceSet. So what went wrong? I got so wrapped up in the game mechanics and inheritance that I didn’t consider the relationship between the objects.</p><p>At this point, I have to give a shout out to <a href="https://tigerarcades.medium.com/">Florian Salihovic</a> again. Not only bringing this problem to my attention, but also for his <a href="https://tigerarcades.medium.com/object-oriented-dungeons-dragon-ccc54e2586ff">excellent article</a> where he tackles this problem with his own approach. I highly recommend reading it, as he does a fantastic job in showing how the relationships of objects and classes should dictate your design choices. This is shown in how he treats game mechanics and characters/NPCs (referred to as Agents in his article) as two separate entities. This makes perfect sense! Game mechanics are analogous to the Laws of Physics; they define what is and isn’t possible and all physical entities are <em>subject </em>to them. A player is not a rule (parent-child relationship), nor do they have a rule (this is composition, where you create an instance in a class that references another object). So, again, I highly recommend reading his article “<a href="https://tigerarcades.medium.com/object-oriented-dungeons-dragon-ccc54e2586ff">Object-Oriented Dungeons &amp; Dragons</a>”.</p><p>So now that we know what I did wrong, let’s fix it! First thing we need to do is remove that reference to the DiceSet class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*zqb89DCunud2V4HhQjrdbg.png" /></figure><p>Good, we fixed it! Now, you might notice something odd about this class. The default arguments are all left empty or None. Why is this? Well, we intentionally designed the Sentient class to be generic as possible so that we could make child classes that will be more specified to players, monsters, and NPCs. This way each of the child classes could provide their own implementation. Classes that are designed in this way are referred to as “Abstract Classes”. A formal definition is a class that contains one or more abstract methods (methods with no defined implementation). Their purpose is to provide a framework for other classes, while giving them the freedom to define methods that are tailored to their needs.</p><p>Since our Sentient class is pretty much an abstract class (it’s just missing the abstract methods to make it fit the formal definition) let’s go ahead and make it official. We’ll add an abstract method called calculate_hit_points to make sure that it fits the definition, but also so that this class is more than just a container for data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*LqTpOqHNAyAbjFv0GhUIow.png" /></figure><p>In Python, to create an abstract class or method, you first need to import ABC (acronym for Abstract Base Class) and abstractmethod from the abc package. We declare our class as abstract with the class Sentient(ABC):. To make an abstract method, first declare it with @abstractmethod and name your method, passing self in as an argument. Leave the method empty with pass so that other classes can set their own implementations.</p><p>You might be wondering why there is a method for calculating hit-points if there is an attribute already listed in the Initializer. Well, let’s look at the entry here for a Dragon Turtle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*p0q-k9ZUxv1VfsnQoWAj1g.png" /></figure><p>Notice how next to Hit Points it has 341, but also (22d20 + 110). This is a choice given to the Dungeon Master. They can either choose a default, median value of 341 hit points for all dragon turtles, or for a more diverse experience, each dragon turtle can have hit point values that are the sum of 22 rolls of a 20-sided die plus an additional 110 hit points. This would mean that you could have a “runt” with 132 (22*(1) + 110) hit points (the minimum) or a particularly beefy dragon turtle with 550 (22*(20) + 110) hit points (the maximum).</p><p>Let’s go ahead and make our Monster class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*6c7RmS-9EbdzRkLs1Icbjg.png" /></figure><p>You’ll notice that Monster also has a concrete method (it provides an implementation. Despite this, Monster is still abstract since it provides no implementation for the calculate_hit_points method. Children of abstract classes MUST provide implementation for ALL of the methods for them to become “concrete” and instantiable.</p><p>To that end, let’s make a class for Dragon Turtles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*RkSBW0LMrY8bTPT2mRzgFQ.png" /></figure><blockquote>Note: Normally, I would go through and make sure that every attribute was also filled in when we defined the DragonTurtle class, as these attributes are shared across all instances of DragonTurtle objects. However, to save time, I skipped this step, as the primary focus is the implementation of an abstract method.</blockquote><p>Now that DragonTurtle has provided an implementation for the calculate_hit_points method, the class is considered concrete. We’ve even created a DragonTurtle named Bertha, and she has 378 hit points.</p><h3>Why is This Important?</h3><p>Just as how classes are a template for objects, abstract classes act as a template for other classes. When you want to provide a common interface for different implementations of a method, an abstract class is the way to go. They’re used to aid in the creation of APIs and Plugins for programs.</p><p>Join us next week for our discussion of Polymorphism!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e7336a8faf" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/oop-and-d-d-abstraction-and-abstract-classes-70e7336a8faf">OOP and D&amp;D: Abstraction and Abstract Classes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP with D&D]]></title>
            <link>https://levelup.gitconnected.com/oop-with-d-d-e8fef2b3b6e7?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8fef2b3b6e7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[dnd-5e]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 21:34:13 GMT</pubDate>
            <atom:updated>2021-03-29T15:45:19.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>OOP with D&amp;D: Inheritance</h3><h4>Using D&amp;D to Understand the Four Pillars of OOP, Part I</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yeIfT7pMQduxrf6m7mdOA.jpeg" /></figure><blockquote>Update 3/24/2021: I wanted to take a moment to thank <a href="https://tigerarcades.medium.com/">Florian Salihovic</a> for helping me identify areas that needed clarification.</blockquote><p>Today, we’ll be discussing Inheritance, one of the “Four Pillars of Object-Oriented Programming”. The programming language we’ll be using in our discussion is Python. I should preface that I have a bias for Python. Why? Because the syntax is simpler. That’s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*66UcJ_WfzF0KJuvSUiRCWQ.gif" /></figure><p>So let’s get started!</p><h3>What are the Four Pillars of OOP?</h3><p>The Four Pillars are as follows:</p><p><strong>Inheritance</strong>: The ability of an object in a subclass to inherit the behaviors and attributes from its parent class.</p><p><strong>Abstraction</strong>: A process where you show only “relevant” data and “hide” unnecessary details of an object from the user. It’s like turning on a car. The car manufacturer knows that “turning the key” (or pushing the button) is just a part of the process of that gets the car’s engine to start. On the other hand, a driver doesn’t need to to know every detail about that process, they only need to know that if you turn the key/push the button, the engine will start. That is abstraction. In OOP, it’s giving the developer the ability to create classes and packages, and the user only needs to how/when to access and use the methods, not how it works.</p><p><strong>Polymorphism</strong>: The ability of a function or method to operate on many different types. For example, print(len(&quot;hello&quot;) and print(len([1, 2, 3, 4, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;])) are both valid uses of the function len(), despite that it is operating on a string and a list. In OOP, this also allows us to define methods in a child class with the same name as one in the parent class (called Method Overriding).</p><p><strong>Encapsulation</strong>: The ability to wrap data (variables) and methods in a single unit (such as a class) to restrict direct access to them and prevent accidental modification.</p><p>These four principles build a strong foundation for all object-oriented programming languages. Missing a single component can cause the language to become bug/error prone, take up too much memory, and require substantially more code than is necessary (the kind that would make my gripes about Java look like I’m just being petty…which…I am, but you know what I mean).</p><p>Today, we’ll discuss how Inheritance works. Time for some Dungeons &amp; Dragons!</p><h3>D&amp;D</h3><p>There are a couple of reasons D&amp;D is great for practicing OOP. First, it is a game with hundreds of diverse creatures and other assets that are unique but still share similar traits (e.g. an Elf and a Human are both “humanoids” despite being different races and having different abilities).</p><p>Another reason why D&amp;D works well with OOP is because most video games have some mechanic that is analogous to D&amp;D. From the obvious RPGs to First-Person Shooters, all games implement a “dice roll” mechanic of some sort. Don’t believe me? Think of how in an FPS your weapon is more accurate if you’re character model is in a state of rest. This is the equivalent to the “Advantage” mechanic in D&amp;D, where you increase the odds of hitting your target by rolling your ability check twice and using the larger number. In the video game, you gain “advantage” by decreasing movement speed and crouching. On the other hand, by running and gunning, you are disadvantaged (roll your ability check twice and use the lesser number) and are less likely to hit your target.</p><p>With that out of the way, let’s get started!</p><h4>The Primordial Class</h4><p>Thinking of our first parent class can be difficult. Parent classes should be very general. If we want to make a parent class from which ALL sentient objects in the game are derived, then it should only contain attributes and behaviors that all sentient characters, NPCs, and monsters have in common. You might be thinking that a great first class will have attributes like name, race, hit-points, alignment, armor class, etc., like in the stat sheet here for an Aatxe,:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*5jLfOwktnUAB6ywbzrEjYw.png" /><figcaption>Source: <a href="https://open5e.com/monsters/aatxe">Open5e.com</a></figcaption></figure><p>Most of the stats above are universal, with a few exceptions like Legendary Actions. This would make a great starting place! But there is something else that is shared by everything in the game: The Dice!</p><p>Dice roll dictates the success and failure of nearly every action of every single sentient being in the game. Thus, we want all of our creatures and characters to inherit a dice roll method.</p><p>So we’ll start there!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*DZYry-UP17OK6SAecYCqkg.png" /></figure><p>Here, we have started a class that defines what dice come in the set and the possible results one could get from a single roll of a die (Note: A d2, or a die with 2 sides, isn’t a die. It’s essentially a coin flip which isn’t in the normal D&amp;D mechanics, but it’s included for a Dungeon Master to use at their discretion, such as when an NPC has a 50% chance of a successful action). The __init__method is the Initializer (or “Constructor”, if you’re a Java kinda person) in Python. Attributes inside this method are considered default attributes for all child classes. The argument self is a Python argument. When a class is instantiated as an object, the object itself is implicitly passed as the first argument in all methods. To account for this, the standard practice is to add the argument self as a parameter. You’ll see an example of this when we add the next method: The Ability Check!</p><p>The Ability Check is the most important mechanic in D&amp;D. In the game, if you wanted to perform some action that would require some skill (like convince someone to sell all of their possessions for a bean, or run on a wall), you must perform an ability check. To do this, you roll a d20 and add in any modifiers that your character might have. The Dungeon Master (DM) will assign a number to represent difficulty for the action, called a Difficulty Class (DC). Your ability check (the sum of your dice roll and any modifiers you might have) must be greater than, or equal to the DC.</p><p>For example, let’s say you want your character to run on the wall. Running on a wall is difficult, but you don’t need to be a professional acrobat to do it, so your DM says that you need to roll at least a 14. This means that for your ability check, your roll and your modifiers need to add up to a minimum of 14.</p><p>Modifiers are related to your character’s stats. If your character is really good at acrobatics, they would naturally have a higher chance of success, so they would have a larger positive modifier, like “add 5 to all acrobatics ability checks”. So if your dice roll was 9, you would still succeed at the wall run because your +5 modifier turned your 9 into a 14.</p><p>However, let’s say your character wasn’t the athletic type and you had a -1 modifier. Well, even if you rolled a 14, the -1 modifier turns it into a 13 and you failed because performing stunts is difficult for you.</p><p>Rolling a “Natural 20”, meaning the result of the dice roll itself was 20, without modifiers, guarantees your success (the DM can’t force you to fail just because it ruins their plans).</p><p>Rolling a 1 (a “Natural 1”), however, guarantees you fail and you fail in a big way (whatever bad can happen, will happen). It doesn’t matter what your modifiers are, an over-powered character can’t escape the DM’s wrath.</p><p>I know that was a bit of a tangent, but we need to know how the mechanic works if we’re going to recreate it in code. So, with all of this knowledge, we’ll create the ability_check method (Note: a method is like a function, except that is bound to a class and its instance variables).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*o0nqP7k-50WMaXTgd5Z2FA.png" /></figure><p>As you can see, we’ve got arguments for advantage and disadvantage, a character’s modifiers, and the number of dice to roll (remember that with advantage and disadvantage, you must roll a d20 twice and pick the larger or lesser number, respectively). Let’s test this out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*2qqsWOHstp9Q2T7e4VlkeQ.png" /></figure><p>Going back to the wall example. Jennifer is the name of our character, and we made some dice for her by creating an instance of the DiceSet class. Jennifer is extremely athletic and excels in acrobatic feats, so she has a +5 modifier for her acrobatic ability checks. Sadly, she is having an off day and she rolled a “modified” 10, and she failed, slipping on the wall. Even Olympians have bad days.</p><p>Let’s say she had a little pep in her step from drinking a great cup of coffee which gives her advantage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*d_uQpa91c7fHULwYeUjUow.png" /></figure><p>Awesome, she passed! Now, what if someone spiked her morning coffee and now her judgement is off, giving her disadvantage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*LuodD3W0uTpu4r7PAtFWSw.png" /></figure><p>Lucky for her, her muscle memory was able to kick in and save her from falling! (Note: Just because you’re disadvantaged, doesn’t mean that you’re guaranteed to fail. It just increases the probability of failing by forcing you to roll twice and pick the lower number, even if one of your rolls was a Nat20 like the one above. That’s why Jennifer passed the Ability Check. The lower number, a modified 16, was still greater than the Difficulty Class of a running on a wall, 14.)</p><h4>Inheritance</h4><p>OK! Our method works, and our first parent class is working properly. Now let’s create a child class that will be the blueprint for sentient objects in the game. We’ll call it Sentient because all of its attributes will be ones that are shared by both monsters and characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*fXVvcCmDpIs_dNKAQPxSJw.png" /></figure><p>Above, you can see that we passed DiceSet inside the parentheses when we declared the sentient class. This sets up the parent-child relationship; Sentient is a child of DiceSet. This raises a very good question. Should a class that is the parent of all sentient classes, be the child of a class that represents dice? Typically, you’d want the names of parent and child classes to have some relevance to each other to reflect their relationship. For instance, the hierarchy of a Sparrow class would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Z5WPF-Yhe-z8KhzkpHrHRg.png" /></figure><p>Here, we see a clear relationship; a form of family tree. There is the ancestor class, Animal, which is a parent to Bird (since a bird IS AN animal), which has the child class Sparrow(a sparrow IS A<em> </em>bird). Thus, classes should follow an IS-A(N) relationship. But we all know that sentient things aren’t examples of dice sets. A sentient being HAS A dice set. This get’s into a more nuanced characteristic of Inheritance called “Composition”, which we won’t discuss right now, since I’m already teaching you to play D&amp;D. So is my example appropriate? Absolutely not. Are we going to go with it anyway? Yes, but just understand that a more appropriate use would be to either make DiceSet an interface that other classes can <em>implement</em>, or keep rules and gameplay mechanics completely separate from Sentient class objects and their children.</p><p>We’ll fix part of this glaring problem when we talk about Abstraction next week. For now, let’s check to see if a Sentient class, inherited everything from DiceSet class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*hsUmMeg6i6gKc-sBaJyvJA.png" /></figure><p>As we can see, our Aatxe (named Barry) inherited everything from its parent class! And Jennifer? Has she inherited anything from this new relationship?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*sBHB-NO4HH16Xs2LEaLPAQ.png" /></figure><p>Jennifer has no roll modifiers because she’s a DiceSet object. A parent class object cannot inherit the traits of a child class.</p><p>Now, let’s make a Monster class that is a child of the Sentient class. We mentioned earlier that one big difference between characters and monsters is that only monsters have Legendary Actions. Therefore, the Monster class will have this attribute for themselves and a method to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*K_IjZlQv0j2ZozG16RRGTQ.png" /></figure><p>Next we’ll create a new Aatxe monster, this time it will be an object of the Monster class. Since its parent is the Sentient class, we should be able to define the monster’s attributes at instantiation, just like we can with it’s parent class. We’ll also define the Aatxe implementation of the legendary_actions method.</p><p>Alright, let’s check out what Leslie can do! Can we access her race (a parent attribute)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*gBhHxEZmU5Qz-yjmhewpbw.png" /></figure><p>What are her options for Legendary Actions?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*iVbpQ-cEo0yK2hppqFP-hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*fljhXE-tyPiOrrO94qmxhA.png" /></figure><p>If selling a time-share in Orlando, Florida had a Difficulty Class of 15, could she make the sale?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*OB2Ary5yZMuiuvWALnHpPw.png" /></figure><p>We passed Leslie’s Charisma modifier (she’ll need to be a smooth talker, afterall) as our modifier argument for the ability_check method, and she rolled a 16. That time-share is sold, baby!</p><p>Levity aside, this demonstrates that descendant classes and objects also inherit attributes and methods from their ancestors, as well.</p><p>What about Sibling classes (classes that share the same parent)? Can sibling classes inherit each other’s methods? Let’s make a character class and see if it inherits its sibling class’ legendary_actions method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*UCm0kVQpcS6VEmfmU6ZOXA.png" /></figure><p>So objects of the Character class can override the name attribute they inherit from their parent class, but cannot inherit the legendary_actions method of from its sibling class.</p><h3>Why Classes?</h3><p>You might have noticed that I have primarily been using classes as data storage. Why not just use an array or dictionary then? Good question!</p><p>A class creates a blueprint or template to create objects that you can store data (like character information) or behaviors (methods that allow your objects to perform a function, like rolling an ability check). Thanks to inheritance, we can substantially reduce the amount of code that we need to write, since the subclass will have access to all of the methods and attributes they were capable of inheriting. Therefore, I don’t need to rewrite the ability_check method for EVERY single monster or character.</p><p>Next time, we’ll be discussing another Pillar of OOP: Abstraction. See you then!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8fef2b3b6e7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/oop-with-d-d-e8fef2b3b6e7">OOP with D&amp;D</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAM Doesn’t Make Your Computer Faster]]></title>
            <link>https://benmauss.medium.com/ram-doesnt-make-your-computer-faster-61575549fb13?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/61575549fb13</guid>
            <category><![CDATA[computer-performance]]></category>
            <category><![CDATA[mythbusters]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cpu]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 18:46:27 GMT</pubDate>
            <atom:updated>2021-03-16T14:02:10.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Addressing Common Technology Myths, Part I: How to Explain RAM and Computer Performance Speed to “Technophobes”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqYzQdOYCrxzXuL9-Rk48Q.jpeg" /></figure><p>I’m taking a much needed break from talking about <a href="https://levelup.gitconnected.com/deployment-computer-vision-in-practice-99b7bbb6aa7c">Computer Vision</a> to address a misconception about RAM that still get’s passed around today.</p><p>I remember when I was younger I would hear this axiom:</p><blockquote>“If your computer is slow, just add more RAM!”- Almost every sales associate at MicroCenter or Best Buy</blockquote><p>This lead to a general belief among the masses that you could keep your 10 year-old Dell running and relevant by JUST increasing the RAM. This is not true. Adding more RAM does not make a faster computer. It also is not a way to undo the damage to old tech by the ravages of time.</p><p>To many of you this is a no brainer. So why should you bother reading this? Maybe you’re like me and have family and friends that are a little “technophobic” and the second you start explaining how it really works, you get this reaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*XURVBsuo-Eza1mBiL8W5og.gif" /><figcaption>Source: It’s Always Sunny In Philadelphia S12 E5</figcaption></figure><p>(Not gonna lie, I get this way when I read scholarly articles about Data Science)</p><p>Today, we’re going to break concepts down so that anyone can understand them. Let’s get started!</p><h3>What is Defines a Computer’s “Speed”?</h3><p>This is a complex question. A computer’s overall performance speed is a relationship between the computer processor and the amount RAM the computer has, as well as the hard drive. That’s already too much techno-babble! So we’ll explain what this means with an analogy.</p><h4>The Puzzle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hs6PKw8PQGWh_OaKpbQEFA.jpeg" /><figcaption>Image Source: <a href="https://www.verywellmind.com/thmb/QbzTAfKCWxjcfWJMdyUGZn8hDXs=/2121x1414/filters:fill(ABEAC3,1)/puzzles-f2b858e7f3d44642bf0df99d3da6e704.jpg">VeryWellMind.com</a></figcaption></figure><p>Let’s say that you want to put together a puzzle. Like most people, you start by sorting all of the pieces and finding the edge pieces first.</p><p>For the sake of the argument, we’ll say that the normal human can sort through 20 puzzle pieces and find all of the edge-pieces in 30 seconds. Also, let’s agree that sorting 20 pieces is all a person can handle mentally at any one time. Any more and they’ll get a big headache.</p><p>Now, for some reason, you’re sorting a these pieces at a very small accent table, like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Cer9G1BYajMzYNUyIZReaA.jpeg" /><figcaption>Image Source: <a href="https://www.worldmarket.com/category/furniture/living-room/end-tables.do?template=PLA-2&amp;plfsku=394560&amp;mrkgadid=3282585734&amp;mrkgcl=660&amp;mrkgen=gpla&amp;mrkgbflag=0&amp;mrkgcat=Furniture&amp;camp=ppc%3Agoogle%3Apla%2BMerkle_Shopping_PLA%7CFurniture%2BLiving_Furniture&amp;acctid=21700000001660222&amp;dskeywordid=92700046651982139&amp;lid=92700046651982139&amp;ds_s_kwgid=58700005275197214&amp;ds_s_inventory_feed_id=97700000007265821&amp;dsproductgroupid=430165429565&amp;product_id=394560&amp;merchid=5165106&amp;prodctry=US&amp;prodlang=en&amp;channel=online&amp;storeid=&amp;device=c&amp;network=g&amp;matchtype=&amp;locationid=9010776&amp;creative=260704782461&amp;targetid=pla-430165429565&amp;campaignid=1338279815&amp;adgroupid=53808061175&amp;gclid=Cj0KCQjwi7yCBhDJARIsAMWFScMgNE2isGWszJIekhC_D17sd0GmyiK80UZjDj0DUOngnjix3KAl5hwaAv69EALw_wcB&amp;gclsrc=aw.ds">WorldMarket.com</a></figcaption></figure><p>The accent table that you’re sorting at can only hold a 10 pieces. From experience, you’ve learned that, no matter how many handfuls you sort, it takes an additional 5 seconds to gracefully take the edge-pieces and add them to an “edge” pile, pour the rest of the pieces into a “non-edge” pile, and add a new selection of pieces to the table. Again, it takes 5 seconds to do this whether you’re sorting 10 or 20 pieces. It’s a <em>constant.</em></p><p>Since your table can only hold 10 pieces (half of your maximum capability) it takes you 20 seconds to sort, separate, clear the table, and add new pieces; 15 seconds to sort a single handful, plus the extra 5 seconds. This means that it takes 40 seconds to sort 20 pieces.</p><p>You decide that since you’re working with half of what you’re capable of, you’ll just get a table that can hold twice as many pieces. Doing this you’ve noticed that it now takes 35 seconds to sift through 20 pieces! You’ve shaved off 5 seconds! You begin to think, “If doubling the size of the table took 5 seconds off, then doubling again should make sorting go even faster!”</p><p>Following this logic, you go get a table that is quadruple the size of your original table. You have enough space for 40 pieces, but remember, you can only sort 20 pieces at a time, or you’ll get a massive migraine and have to stop. Therefore, you only work with half of the available pieces. As a result, it still takes you 35 seconds to sift through one batch.</p><p>What went wrong? Changing tables the first time made the process <em>faster</em>, didn’t it? No! It only made it more <em>efficient.</em></p><h4>What Does This Have to Do With Computers?</h4><p>In this example, you are the computer processor. You have specific limitations to how many items your can process and sort through and a certain speed at which you can perform the task. The RAM, then, is the table. The hard disk could technically be the box that the puzzle came in (or even the closet that you store all of you puzzles in), but that’s not important right now.</p><p>Going back to the analogy, at the beginning of the analogy, you (the processor) had too little resources (RAM) to work at your full potential. You increased the table size to fix this (increasing the RAM available). This resulted is processing time to decrease because you’re now working at full capacity. This is how the myth of “More RAM = More Speed” began. People had computers with CPUs that could process more items than the RAM could hold. Increasing the available RAM made the computer more efficient by utilizing more of the processor’s capabilities. This increased the computer’s overall <em>performance </em>speed, but it did not change the computer’s <em>processing </em>speed.</p><p>You might be wondering what the difference is between “performance” and “processing” speed. Performance speed is how long it takes to perform a task. In our puzzle analogy, it’s how long it takes to collect pieces from the box, put them on the table, find and separate the edge pieces into a different pile, pour the remaining pieces into the “non-piece” pile, and collect new pieces to sort. In our example, the maximum puzzle sorting <em>performance </em>speed is 35 seconds per 20 pieces.</p><p>Processing speed is what people actually think of when they think of speed. It’s defined by how much data (puzzle pieces) the CPU can process and how quickly it can actually process them. Going back to the analogy, the processing speed is how many pieces you can sort at a single time and how fast you can sort them. Your max <em>processing </em>speed is 15 seconds per 10 pieces and a limit to 20 pieces at a time, totaling in a minimum of 30 seconds (we’re not including the time to clear the table and collect 20 pieces because that’s not part of the processing, or sorting, task.). This is why switching to the even bigger table didn’t result in an increase in <em>performance </em>speed. The amount of pieces the table can hold doesn’t matter if you can’t decrease the time it takes to sort through them all.</p><p>So where does the hard drive come to play in all of this? The hard drive is where all of the information is stored. When you run a program (pick a puzzle to make), the data stored on the hard disk (the pieces) gets loaded into RAM (or put on the table). Why can’t we just run it all from the hard drive? Why do we need RAM? Well, if we could bypass the RAM, I’d imagine this would be the equivalent of pouring all of the pieces of your entire collection of puzzles on the floor and then trying to make specific puzzle out of the pile. There just isn’t a processor around that can keep track of all of that and it’s horribly inefficient.</p><p>Now, you can increase performance speed a little by defragging the hard drive. This is like organizing and pre-sorting the puzzle pieces by edges, colors, and shapes. This reduces the amount of sorting you would have to do by hand. We’ll still have some trouble when it comes to how some colors could appear in multiple places of the full puzzle, but it’s at least all organized.</p><p>Another way that the hard drive can increase the performance speed is by switching from a standard optical drive (which uses a laser to read information on a spinning disk like a CD Player) to a Solid State Drive (essentially a high capacity SD card with additional functions like running an operating system). This is like the puzzle box being pre-sorted into bags that hold exactly two handfuls and are labeled by edges and specific sections of the puzzle (e.g. “Edges”, “Upper-left 1, “Upper-Left 2”, “Top-Center-Left”, etc.). Essentially, the box would be so organized that finding the right pieces is less of a chore. This way all of the pieces go from the box (hard drive) to the table (RAM) in a quick and organized manner.</p><p>That’s about the extent of what you can do with hard drives (that I can think of). It’s important, but plays a much smaller role in the overall scheme of computer performance speed (with the exception of Solid State Drives).</p><h4>What If I Change Processors?</h4><p>Good question! It’s also has a somewhat complex answer because of the different kinds of processors out there. Let’s go back to our analogy. It’s just you, the puzzle, and a table that holds twice as many pieces than you can sort at a single time. There are two ways you can go about increasing your processing speed. You can either improve your own skill or you can invite a friend over.</p><p>Let’s say you improve your skill. This is like buying an updated version of your current processor. We’ll say that after an afternoon of watching YouTube videos on puzzle speedrun techniques, you’ve managed to decrease your “processing” time from 15 seconds per 10 pieces to 10 seconds. So now a single iteration of 20 pieces is 25 seconds (20 for finding the edges, plus the 5 to separate and collect 20 new pieces to sift through). You’ve increased the processing speed more than you could have ever hoped to by just increasing the table size. There is still a problem, though. The table can hold 40 pieces, but you are still only working on 20 at a time!</p><p>You decide that getting a bigger table won’t do anything. So you call your friend and teach them the same speedrun techniques you learned. Since they will be working concurrently with you, you’ve doubled the processing power. Together, you’re capable of sorting and collecting 40 pieces at a time and performing it in 25 seconds! Essentially, you’ve become a “Multi-core processor”. These are processors that are made up of smaller processors, called “cores”. Tasks are broken up and performed across many cores. This drastically reduces the amount of time needed to process the data which allows you to utilize as much of your RAM as possible.</p><p>Now what happens if you both go back and work on the table that only holds 20 pieces? Well, either your friend will have nothing to do, or you will both only be working at half of your full capacity!</p><h3>Summary</h3><p>We talked about a lot of things but the key take away is that maximizing your computer’s performance is a balancing act. If you’re processor is too weak, then adding RAM won’t speed it up. Likewise, if you have very little RAM, increasing CPUs processing power will not only be expensive, but you computer will never be as fast as it could be. By balancing processing power and amount of computer memory, you can maximize the computer’s performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61575549fb13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment: Computer Vision in Practice]]></title>
            <link>https://levelup.gitconnected.com/deployment-computer-vision-in-practice-99b7bbb6aa7c?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b7bbb6aa7c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[viola-jones]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 19:55:37 GMT</pubDate>
            <atom:updated>2021-03-11T15:12:55.730Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to Computer Vision, Part VII</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn8VKKEW-3rv6opELKZl8A.jpeg" /></figure><p>Over the last six weeks, we’ve learned a lot about how we teach a model to detect images. We started with the basics of how a computer reads and stores an image. Then transitioned to how an algorithm defines objects in an image by use of Haar-like features. We discussed how the Integral Image reduces the time and necessary resources to calculate the hundreds of thousands of possible features in an image. From there, we talked about how models are trained, both on an intuitional level and on a slightly more mathematical level, especially as it related to Adaboost. Finally, we saw model training in action. Today, we’re going to take the “trained” model we built last time, and apply ALL of what we’ve learned to understand how object detection works in real-time.</p><blockquote>Note: This entire time, we’ve been basing all of our knowledge off of the Viola-Jones algorithm, utilizing the basic set of Haar-like Features that Viola and Jones worked with 20 years ago. While deep learning neural networks are slowly becoming the new standard, the Viola-Jones algorithm is still a powerful tool that serves as a great foundation for building one’s understanding of Computer Vision.</blockquote><blockquote>And while the Viola-Jones algorithm is used for face-detection, at its core, it is an <strong>object-detection</strong> algorithm that was <strong>trained</strong> on faces. As such, we can easily apply the same processes to our scenario here.</blockquote><h3>From Still Images to Real-Time</h3><p>The transition from classifying still-images to real-time is pretty fluid in actuality. Remember that what we call “video” is nothing more than a series a still-photos taken in rapid succession. The model takes these images as inputs, much like during training, and tests the now “trained” (or “fitted”) equation against these images. In order for the model to keep up with the live-feed, an equilibrium needs to be established between resolution of the feed, the available processing power, and the number of frames being captured each second (AKA: Frames Per Second, or “FPS”). When each of these elements are in proper alignment, you’ll achieve results like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*MOTqoMEnVYaOJgAp823wxg.gif" /><figcaption>Image Source: <a href="https://www.pyimagesearch.com/2018/09/24/opencv-face-recognition/">PyImageSearch.com</a></figcaption></figure><p>As you can see, the frames that outline this couple’s individual faces are able to scale, calculate, and track in real-time. If the computer’s processing power was too low, or if either the FPS or resolution settings were too high, you would see the frame lag behind. This is seen a lot in low- to mid-range digital cameras.</p><p>Real-time object detection is available mostly thanks to the optimization created through use of the Integral Image and Adaboost. Another reason for the relatively smooth transition is because once a model is trained, tested, and deployed, the weights and features that remain in the model’s equation (e.g. <em>F</em>(<em>x</em>) = <em>α</em>₀<em> f</em>₀(<em>x</em>) + <em>α</em>₁<em> f</em>₁(<em>x</em>) + <em>α</em>₂<em> f</em>₂(<em>x</em>) + …+<em>α</em>₁₇₉,₉₉₉<em>f</em>₁₇₉,₉₉₉(<em>x</em>)+ …) have been “frozen”. This means that the weights (<em>αₙ</em>) and features (<em>fₙ) </em>cannot be changed unless you intend on retraining the model.</p><p>In a way, you can think of the trained model as checklist. If the minimum number of features are present in side of a pre-defined space, then the probability of it being the target object is very high. What do I mean by a predefined space? Simply put, it’s that scaling frame you see around each of those faces above! It scales to compensate for different facial sizes and forced perspective (when an object looks smaller or larger based on distance from the camera). The model slides this frame across the images until it detects ALL of the necessary features are inside that box. Once it finds those features, it begins to calculate.</p><p>Before moving on, let’s take a close look at that GIF one last time. You might notice the fluctuating numbers in the top right corner of each box. This represents the <em>probability </em>of the<em> </em>outlined object being the target object. Let’s look at the equation again behind the model one last time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*F6zp7kl22wtXDYQ1.png" /></figure><p>Last time, we said that <em>F</em>(<em>x</em>) represents the classifier. While this is true, it is not the <em>whole </em>truth. Remember, all of this is one big math equation. As such, when you add up the all of the terms (<em>αₙ fₙ</em>(<em>x</em>)), the result is going to be a number. That number is the likelihood that the model has found the target object. Therefore, <em>F</em>(<em>x</em>) is the <em>probability </em>that the target object was detected within that frame.</p><p>With all of this out of the way, let’s get to ahead and see how our model works.</p><h3>Detecting Walmart</h3><p>So last time we pretended to train an image classifier that could detect Walmarts. So we’ll say that one of the images captured in our live feed was this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aQx-QH4XiMSqp3V0.jpeg" /><figcaption>Image Source: <a href="https://www.ttnews.com/articles/walmart-fights-54-million-lawsuit-verdict-awarding-drivers-sleeper-berth-pay">TTNews.com</a></figcaption></figure><p>On our screen we see this image, but remember all the way back in the <a href="https://levelup.gitconnected.com/pixels-arrays-and-images-ef3f03638fe7">Part I</a> of this series that an image is actually an array spread across three channels which correspond to the red, green, and blue channels of pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*mSfHCmDorqR2hMY9.png" /></figure><p>The dimensions of the arrays are equal to the resolution of the image, as each cell represents a single pixel. The cells of each channel represent the intensity (or brightness) of that channel for that pixel. So while we see a picture of Walmart, the computer sees this as a collection of numbers and channels.</p><h4>Transformations</h4><p>Next, the model performs two transformations in the background. These are both transformations you’ve seen before: converting the image to grayscale, and scaling the numerical values (not the resolution).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gw3AipH9VijdxXms.jpeg" /></figure><p>Each of the cells in the separate channels get converted to grayscale. This makes the math simpler which helps reduce the complexity of the task.</p><p>The second transformation is scaling the values in each cell. Normally, the brightness is on a scale of 0 to 255 with 255 being the brightest. However, for simplicity, the values get scaled so that they are between 0 and 1 (0 being no light and 1 being the brightest).</p><p>Now, you might remember that, during training, the image’s resolution was also scaled down. Well, that doesn’t happen after the model is deployed. Instead, all of the features get scaled up to match the proportions of the image resolution! So just remember: during training, the <em>image </em>gets scaled <strong>down</strong>. In practice, the <em>features </em>get scaled <strong>up</strong>.</p><h4>Detecting Features</h4><p>With the image array, channels, and numbers in the proper format, the model then starts looking for the target’s features. It calculates out all of the <em>necessary </em>Haar-like features. You might remember this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*g9hPV1QDmFbFcOs8.png" /></figure><p>The model wants to determine if the outlined section of the image contains an edge-feature. It does this by creating an Integral Image like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*JGkTkZZA1lluVVC3.png" /></figure><p>It uses the integral image to locate the 4 magical numbers it needs to quickly find the sum and calculate the average of the lighter and darker halves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*Zho9nAcZtexGZfMh.png" /><figcaption>Numbers for the Lighter Half</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*gx4BZ_bRzTRkvfHB.png" /><figcaption>Numbers for the Darker Half</figcaption></figure><h4>Cascading: Another Brilliant Optimization</h4><p>This all sounds very familiar but something is different this time. I mentioned earlier that it’s calculating the <em>necessary </em>features. Remember that during training, we cut out all of the unnecessary features and reduced the equation to something that looks like this:</p><p><em>F</em>(<em>x</em>) = <em>α</em>₀<em> f</em>₀(<em>x</em>) + <em>α</em>₁<em> f</em>₁(<em>x</em>) + <em>α</em>₂<em> f</em>₂(<em>x</em>) + … +<em>α</em>₅<em>f</em>₅(<em>x</em>)</p><p>If the frame that pans around the image (like the frames in the GIF of the couple) doesn’t find the first feature, <em>f</em>₀, it simply stops calculating, and shifts over a pixel and tries again. If it finds <em>f</em>₀, but not <em>f</em>₁, again, it stops and moves over a pixel. It will do this until <em>f</em>₀ through <em>f</em>₅ are all inside of the box. This time saving method is called “cascading”. This keeps the model from wasting time performing calculations for Haar-like features, etc. if all of the important features are not present. In the case of our model, these features correspond to the ones seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nLIcdLc6qdIahu5o.jpeg" /></figure><p>So our model moves a frame around until all six of the features above are found inside of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4DmZxvAK3IVqZ7xORGmU0A.jpeg" /></figure><h4>Predicting</h4><p>At this point, the model takes the values calculated earlier (to determine if they’re Haar-like features), and substitutes them into their corresponding <em>fₙ </em>term in the<em> </em>equation. It multiplies them by their respective weights (<em>αₙ</em>). The result is the probability that the object detected is the target.</p><p>In our case, the probability is very high, and our live feed highlights it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mO7wZAMfzD6yLozZ8mbFwQ.jpeg" /></figure><p>There is a problem here, though! Look at the box! We wanted a model that detected a Walmart store, but instead our model only detects the Walmart logo! Luckily, there are ways of correcting this. In its current state, however, the model is great at telling us if a Walmart is <em>present </em>in the live-feed, but performs poorly in outlining the object itself.</p><h3>Summary</h3><p>Throughout this series, we’ve discussed the very intricate development of the foundations of computer vision. They’re so fundamental that even deep learning neural networks, while discarding concepts like Haar-like features, etc., still follow similar patterns of such as defining edges within an image. They’re also so powerful that these algorithms are still used in many models today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b7bbb6aa7c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/deployment-computer-vision-in-practice-99b7bbb6aa7c">Deployment: Computer Vision in Practice</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaboost in Image Classification]]></title>
            <link>https://levelup.gitconnected.com/adaboost-in-image-classification-8dcc1799e53d?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dcc1799e53d</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[adaboost]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 20:39:13 GMT</pubDate>
            <atom:updated>2021-03-02T16:20:10.737Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to Computer Vision, Part 5</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RggSDygo6ZDQPRGzieUgIw.jpeg" /><figcaption>Image Source: <a href="https://www.socialpilot.co/blog/worth-boosting-facebook-posts-when-and-how-to">SocialPilot.co</a></figcaption></figure><p><a href="https://levelup.gitconnected.com/training-day-training-image-classifiers-97825ac4bfde">Last time</a>, we talked about the intuition behind training an image classifier. We discussed its similarity to how infants learn to recognize objects and associate names/labels with them as they develop their ability to speak. We then applied that intuition to better understand how the Viola-Jones algorithm was trained. One thing that we haven’t talked about, however, was the math involved during this particular stage. Let’s take a brief look at that! If you’re scared, don’t worry too much. We’re simply taking what we’ve already discussed and seeing how the algorithm creates a trained model using only numbers!</p><p>Let’s take a look at the equation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*5z4geMZrkIJxDJZNlc6F_g.png" /></figure><p>This is actually our classifier! Time to break this down so that each of the terms actually mean something to us. <em>F</em>(<em>x</em>) represents the classifier itself. It is also referred to as the “strong classifier” because it is the <em>sum </em>of many “weak classifiers”. Each term <em>αₙ fₙ</em>(<em>x</em>) is a <em>weak classifier</em>. They’re considered “weak” because, on their own, they aren’t enough to classify an image, but together they’re strong.</p><p>The <em>x </em>represents the input. In the case of our object-detection, it is the <em>current </em>image that the algorithm is trying to classify.</p><p>The <em>fₙ </em>represents a specific Haar-like feature. Now, let’s say <em>f</em>₂ represented an Edge-feature. It doesn’t represent <em>all </em>edge-features in the image. Depending on the resolution of an image, there could be hundreds of thousands of edge-features of different sizes! To treat them all the same would lead to a lot of wasted time and an inaccurate model. Thus, <em>f</em>₂ must represents a specific edge-feature within the image.</p><p>Alpha, written as <em>αₙ, </em>represents the <em>weight </em>of the associated feature. As we discussed in the last article, the “weight” of a feature is just another way of saying how <em>important </em>it is. If the weight of <em>α</em>₅₉ is zero (<em>α</em>₅₉ = 0), then it means that <em>f</em>₅₉ has no importance when classifying the target image. An example of this would be the background in a face-detection algorithm. Most (if not all) of the features that are detected in the background would have a weight of zero since backgrounds will change from picture to picture. This is a key aspect that we’ll elaborate on when we discuss Adaboost.</p><p>The subscript <em>n</em> simply denotes which specific feature we’re referring to and its associated weight. It’s only there for organizational purposes. Since I decided to start with <em>α</em>₀<em> f</em>₀(<em>x</em>) as the first term, all of the features are Zero-Indexed (the first item is labeled “0”, the second as “1”, and so forth). For people unaccustomed to zero-indexing, just add 1 to the number in your head and you’ll know that <em>f</em>₅₉ is the 60th feature that was found and stored by the algorithm.</p><p>Now that we understand the equation, let’s talk about Adaboost; What it is, what it does, and why it’s so important!</p><h3>Adaboost</h3><p>Adaptive boosting (or Adaboost) is another optimization that was utilized in the creation of the Viola-Jones algorithm. Remember when we learned about the Integral Image, we spoke about the Big O. We learned that the Big O is a computational problem that states that as a task increases in complexity, the time taken and resources used to perform it increase exponentially. Since there are over 180,000 features in a single 24x24 pixel image, our equation would look something like this:</p><p><em>F</em>(<em>x</em>) = <em>α</em>₀<em> f</em>₀(<em>x</em>) + <em>α</em>₁<em> f</em>₁(<em>x</em>) + <em>α</em>₂<em> f</em>₂(<em>x</em>) + …+<em>α</em>₁₇₉,₉₉₉<em>f</em>₁₇₉,₉₉₉(<em>x</em>)+ …</p><p>Like we mentioned last time, if it took 1ms to perform the computations necessary for a single feature (again, this is EXTREMELY slow), then the time to compute ALL of the features in a 24x24 pixel image would skyrocket to over 6 minutes. To address this, the Integral Image is created so that potential Haar-like features can be evaluated in a fraction of the time.</p><p>Adaboost performs a similar role for our equation. It reduces complexity of image classification even more by finding the most important features of the target object and, essentially, getting rid of the rest.</p><p>Now, how does it “get rid of” unimportant features? Well, remember earlier that any feature where <em>αₙ = </em>0 is considered unimportant. Then take into account this basic multiplication rule: <em>n</em> x 0 = 0. Therefore, any term (<em>αₙ fₙ</em>(<em>x</em>)) in our equation where <em>αₙ = </em>0 calculates to 0 (e.g. 0<em> fₙ</em>(<em>x</em>) = 0) and is dropped!</p><p>So Adaboost’s goal is to update the weights of specific features to maximize the likelihood of classifying the target object correctly while also eliminating Haar-like features that don’t aid in the detection process. Features that give the classifier a higher number of true-positives (target image classified as “target”) and true-negatives (non-target classified as “non-target”) receive larger weights, as they’re more likely to be unique to the target object. On the other hand, features that lead to a high number of false-positives (non-targets classified as “target”) and false-negatives (targets classified as “non-target”) receive smaller weights with a possibility of being assigned a weight of zero.</p><p>That was a lot of words and numbers, so let’s see it in action and tie it in with the intuition we developed in the last article.</p><h3>Where’s Walmart?</h3><p>Let’s pretend we’re training an image classifier that can detect Walmart stores. We scour the internet for various images of different Walmarts, as well as non-Walmart stores, to train and test our model with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WQaYkqCVFhTQTPuhwhJpg.jpeg" /><figcaption>Image Source: <a href="https://www.ttnews.com/articles/walmart-fights-54-million-lawsuit-verdict-awarding-drivers-sleeper-berth-pay">TTNews.com</a></figcaption></figure><p>Above is just one of the pictures of the Walmarts from the training dataset. Below is also just a single sample of the non-Walmart storefronts from the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMRWRtNqAXwoJeA-7l9v_A.jpeg" /><figcaption>Image Source: <a href="https://www.cookinglight.com/entertaining/holidays-occasions/target-halloween-snacks">CookingLight.com</a></figcaption></figure><p>For simplicity’s sake, we’re going to just refer to these two images (I’m only one man, after all). In reality, the algorithm would scour the training images looking for commonalities that are unique to Walmarts and test its observations against the validation set (sometimes referred to as the “test set”).</p><p>Our first step is to set all of the images (in both training and validation sets) to grayscale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKEGUwy16L4-yH8uCd_QQg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyiOli6RS-wugjJWBvDBzw.jpeg" /></figure><p>The next step would be to set all of the images to the same resolution, as well as scale them down. We’re going to skip that for now, but remember that it’s a crucial step in practice.</p><p>Below is our validation set split into “Walmart” and “Non-Walmart” groups for ease of interpretation. Again, all of the transformations that we applied to the training set would be applied to this as well, but we’re going to just skip that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYyHDXJ5QbsXXjeplrNhGw.png" /><figcaption>Walmart Validation Images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOcOYn_TSFiajsf4ciUsvw.png" /><figcaption>Not Walmart Validation Images</figcaption></figure><h4>Training</h4><p>Now that our images are in the proper format, we start training our classifier. If you remember from last time, this is very similar to an infant learning to differentiate their parent’s from other people and objects. The algorithm is narrowing down the number of features in an image until it finds the ones that are most unique to the target object. Let’s take a look at our training image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qHK4Gekj0ke3XTUbUaaVg.jpeg" /></figure><p>Let’s say that the yellow line represents 11 separate edge-features. The model looked at several Walmart images and made the determination that these edges were important, but what was <em>most </em>important were the vertical edges. These happened to make sharp angles that it “feels” are unique to Walmarts. So it sets the weights of the vertical edges to be much larger than the horizontal. It then sets smaller weights to all of the other features in the image and tests this against the validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emn-Kisx2vmd5F-lEzujWQ.png" /><figcaption>2 False-Negatives!</figcaption></figure><p>As we can see, the model was able to see the vertical edges in the three images on the left (the top-left image was a little iffy, but it still predicted correctly). The top-right image was misclassified because it had no vertical edges along the roof. Similarly, the bottom-right image had more Four-rectangle features (remember that those detect diagonal line features, usually on a small scale), so it was misclassified as well.</p><p>Let’s see how it did on the non-Walmart images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Z9myI5uSFCA2sMI1tflKQ.png" /></figure><p>So the Lowe’s picture was classified correctly because the same reason the bottom-right Walmart was misclassified: a lot of diagonal four-rectangle features. The Best Buy in the bottom-left was classified correctly because the size of the vertical edge features were too big. Why were the others false-positives? Well, look at the Target below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZVe4wKPWxXfWVutsy6CXQ.jpeg" /></figure><p>That outline is simply too general and clearly isn’t unique to <em>just </em>Walmart. The algorithm takes this into account and <em>adapts </em>(This is where the “adaptive” part of Adaboost comes into play). It lowers the weights of the vertical edges and raises the weights of the horizontal edges. It re-runs the validation set and is able to re-classify some images correctly, but images that were true-positives before are now false-positives/-negatives. The algorithm reiterates this process over and over. It manages to get accuracy up a little, but determines that this just simply isn’t enough to go on. On the plus side, during all of the iterations, it discovered that adjusting the weights of the features found in the sky did nothing to help with classifying the image. So it sets the weight of all of those to zero! Our model just got a little simpler!</p><p>What has our model learned so far?</p><ul><li>Horizontal and vertical edges are important, but not a defining feature</li><li>Four-rectangle features are more important than it originally estimated, but not the most important.</li><li>The features above that boundary have no effect in the model’s predictive power.</li></ul><p>Moving on, in its search for additional features that might help with classification, the algorithm notices that the overhang above the doors are lighter than the recessed doors themselves. This creates a large edge-feature, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3Ep0tl7AH7T5CIeS-PI5Q.jpeg" /></figure><p>Again, the algorithm adjusts the weight of this particular edge-feature and tests the new equation against the validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRLElnwzY5PVTZmM1QQTeg.png" /></figure><p>Alright! It managed to classify the bottom-right Walmart correctly this time around. We’re still getting false-negatives, though, and the change in parameters caused one that was previously a true-positive to now be a false-negative. (Again, the bottom-left one is iffy, but you can still make out an overhang that is lighter than the doors)</p><p>And the non-Walmarts?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9FAuAXfwsQcqsFb_xyRnQ.png" /></figure><p>So this edge-feature actually increased the probability of obtaining false-positives. As a result, the algorithm, again, adapts to this new found knowledge. Increasing the weight of this feature <em>did </em>make a small difference in helping to classify <em>some </em>Walmarts, so it’s not insignificant. However, creating a higher false-positive rate means that it shouldn’t be considered a defining feature. The algorithm, again, refines the model by iterating over and over to find an appropriate weight for this feature and simultaneously finds more features that have little to no effect on the model’s accuracy (trees, people, cars, carts, bollards, stop signs, etc.) and gives them weights of zero as well! At this point, it’s dropped a LOT of features from model, which, in turn reduces the number of terms in our equation drastically.</p><p>What additional knowledge did the model gain this time?</p><ul><li>While this Edge-feature is somewhat important with helping to identify <em>some </em>Walmarts, overall accuracy decreases when it is given larger weights.</li><li>Additional, smaller features (listed above) can be removed without affecting performance.</li></ul><p>The algorithm continues to iterate, adjusting weights as it goes. Finally it notices these six line and four-rectangle features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fb-dH0rD9LEH9wm10XwlzQ.jpeg" /></figure><p>The accuracy of the model increased as the weights of these features increased. This fact was true even when reducing the weights of other Haar-like features that were once considered important. Finally, it reduced the weights of everything in the model that weren’t these six to zero. The result?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOZtLh5JPLmyaCnx_SM4kQ.png" /></figure><p>We have a single false-negative above. This is simply because it is an older Walmart, built before the corporation came up with the minimalist logo. What about the non-Walmarts?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTYEWOBnD-_6Fio1-kYBMw.png" /></figure><p>No false-positives this time around! So the six Haar-like features have the most effect on our model’s performance. What’s the implication here? Well, let’s look at how our model has changed.</p><p>We started out with an equation like this:</p><p><em>F</em>(<em>x</em>) = <em>α</em>₀<em> f</em>₀(<em>x</em>) + <em>α</em>₁<em> f</em>₁(<em>x</em>) + <em>α</em>₂<em> f</em>₂(<em>x</em>) + …+<em>α</em>₁₇₉,₉₉₉<em>f</em>₁₇₉,₉₉₉(<em>x</em>)+ …</p><p>After during training, Adaboost reduced the complexity of the model until it created a highly accurate model. The resulting equation would look something like the one below:</p><p><em>F</em>(<em>x</em>) = <em>α</em>₀<em> f</em>₀(<em>x</em>) + <em>α</em>₁<em> f</em>₁(<em>x</em>) + <em>α</em>₂<em> f</em>₂(<em>x</em>) + … +<em>α</em>₅<em>f</em>₅(<em>x</em>)</p><p>(Remember that the terms above are zero-indexed, so the count starts at 0)</p><p>Now, it’s highly unlikely that these six features would happen to correspond with the first six terms of our equation, but you get the point. We went from a model what had over 180,000 features to just six!</p><h3>The Takeaway</h3><p>While this exercise has been simplified, it does show just how powerful Adaboost is. It’s yet another elegant solution to hardware limitations, as well as limitations created by the Big O.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dcc1799e53d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/adaboost-in-image-classification-8dcc1799e53d">Adaboost in Image Classification</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training Day: Training Image Classifiers]]></title>
            <link>https://levelup.gitconnected.com/training-day-training-image-classifiers-97825ac4bfde?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/97825ac4bfde</guid>
            <category><![CDATA[viola-jones]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 22:03:38 GMT</pubDate>
            <atom:updated>2021-02-23T15:49:29.877Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to Computer Vision, Part 4</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*dVitAALgE2MFFiezOaFePQ.jpeg" /></figure><p>Up until now we’ve discussed <a href="https://levelup.gitconnected.com/pixels-arrays-and-images-ef3f03638fe7">how computers “see” images</a>, <a href="https://levelup.gitconnected.com/haar-like-features-seeing-in-black-and-white-1a240caaf1e3">how algorithms detect objects within an image</a>, and <a href="https://levelup.gitconnected.com/the-integral-image-4df3df5dce35">an ingenious shortcut</a> utilized by Paul Viola and Michael Jones to greatly reduce the amount of time and processing power needed to train and run their algorithm 20 years ago. What we haven’t talked about is how algorithms learn to differentiate between objects. After all, an image to a computer is nothing more than an array of numbers. How is it able to tell that one section of numbers is a face and another section is the background? Well, it’s all in the training!</p><h3>Intuition</h3><p>As always, we’re going to start with the intuition. As it turns out, training an image classifier (e.g. an object-detecting algorithm or model) is very analogous to teaching an infant to speak and recognize objects. So let’s build our intuition off of that!</p><h4>Babies First Words</h4><p>Meet Morticia and Gomez Addams!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ka3QyVS31Y1vTl4xYrhxZg.jpeg" /><figcaption>Image Source: <a href="https://m.media-amazon.com/images/M/MV5BMTQxNjEwNjkyOF5BMl5BanBnXkFtZTgwMTE3NjU5MTE@._V1_.jpg">media-amazon.com</a></figcaption></figure><p>This beautiful couple are elated to see that their wonderful baby boy, Pubert, is on the cusp of saying his first word! With a little help from his parents, he finally manages to say, “Ma-ma”. Morticia and Gomez shower him with praise and Pubert is just loving it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ymQcqlBIzgew2zx4aOOcOQ.gif" /><figcaption>Image Source: <a href="https://ar.pinterest.com/pin/351421577157025113/?amp_client_id=CLIENT_ID(_)&amp;mweb_unauth_id={{default.session}}&amp;simplified=true">Pinterest.com</a></figcaption></figure><p>He loves the praise so much that he starts saying it all of the time! He picks up a block and proudly exclaims, “Ma-ma!”</p><p>While finding it cute, Morticia gently says, “No, that’s a BLOCK,” then points to herself and says, “Ma-ma!”</p><p>Since Pubert is not being showered with praise, he instinctively realizes that he made a mistake. He looks at the block and looks at his mother. He sees his mother is pointing at herself and repeating the one word in his vocabulary. Then he copies his mother by reaching out toward her and says, “ma-ma”. Morticia showers him with praise and now has learned that “Mama” isn’t a catch-all term for everything, but is instead a <em>person.</em></p><p>Time passes and one day Gomez walked by Pubert’s play room. Pubert wanted to get some praise from his father, so he makes some noise to get Gomez’s attention. He reaches out and declares, “Ma-ma!” Again, this doesn’t result in the praise he wanted.</p><p>Gomez playfully says, “No, not ‘Ma-ma’,” and, like Morticia before him, points to himself and says, “Da-da!” This confuses little Pubert. He knew that “Ma-ma” was a label for a <em>person</em>. Seeing that his father had all of the <em>features </em>of a person, surely the label “Ma-ma” would apply to him as well. So why is he not getting praised?</p><p>To help his son, Gomez picks up the little boy and calls for the child’s mother. He points at his wife and says, “Ma-ma,” then points at himself and repeats the new word “Da-da”.</p><p>Pubert looks at his mother and says, “Ma-ma,” and gets praised. He studies her face and her form. He looks back at his father and does the same. It’s at this time that he begins to notice that his mother and father have different features. Morticia is slender and has very long hair. His father has a medium build, short hair, and even hair on his face! Taking these (rather general) differences into account, Pubert looks at his father and states, “Da-da!” His parents are overcome with joy and shower him with love. Not only has the boy added the word, “Da-da” to his growing lexicon, but he’s also learned that “Ma-ma” is a label for a slender person with long, dark hair, and “Da-da” is a label for a person with short hair and a moustache.</p><p>Time passes and Pubert sees his sister, Wednesday. She’s a slender girl with long, dark hair, so he calls out to her. “Ma-Ma!” he yells. Wednesday calls for their mother and together they teach him to say a primitive form of his sister’s name, “Wez-day.” Again, he gets the praise and affection he wanted.</p><p>He then looks back at his mother and says, “Wez-day,” thinking that this new word was just another label for slender people with long, dark hair. Morticia corrects him saying, “No. Ma-ma!” She then directs his attention to his sister and, like before, says, “Wednesday.”</p><p>Just like when he was learning the word “Da-da”, Pubert studied his sister and tried to discern what features were unique to her. He notices that Wednesday is shorter and looks younger than their mother. He calls out, “Wez-day,” and everyone celebrates!</p><p>Life continues and Pubert has many more lessons like this until he eventually learns that “Ma-ma” is a label reserved for his mother, “Da-da” for his father, etc..</p><p>This was a rather long analogy, but let’s quickly breakdown what happened:</p><ol><li>Pubert learned the word “Ma-ma”, but doesn’t really understand what the word means. He just knows he gets rewarded for saying it.</li><li>Since he doesn’t know any better, he calls a toy block “ma-ma”. His mother corrects him and he learns that “ma-ma” is a term for <em>people.</em></li><li>Later, he calls his father “Ma-ma,” since his father had all of the qualities (features) of a person. Gomez and Morticia work together to teach him the word “Da-da” and, after some studying, Pubert learned that there was a <em>difference </em>between his mother and father, and associated these differences with their respective labels.</li><li>The <em>features </em>that Pubert found <em>important </em>for calling someone “ma-ma” were still too general, however, and he ended up referring to his sister as such. He then had to find out what features were unique to his sister and refine what features were used to define “Mama”.</li></ol><p>As Pubert was exposed to more people, he would learn from mistakes by studying what sets his mother apart from the people around him. This story probably sounds very similar to parents, as this is a common process with teaching a child to speak. Well folks, believe it or not, but this is pretty much what happens when we train an image classifier. We compile a large set of images of the target object we want the algorithm to recognize, as well as images that are not the target. The algorithm studies the all of the images and, in a sense, compares them to determine what sets the target apart from the rest. It repeats this process over and over again until it determines what the <em>most important features</em> of the target object are.</p><p>Before we go into the specifics, we should learn review some key terminology in the context of image classification. These terms are:</p><p>True-Positive: The classifier correctly recognizes and labels the target object (Pubert sees his mother and says, “Mama”).</p><p>True-Negative: The classifier correctly recognizes that the image is not the target object (Pubert sees his father, knows he’s not his mother, and says, “Dada”).</p><p>False-Positive: The classifier mistakenly labels a non-target object as the target (Pubert sees his sister and calls her “Mama”).</p><p>False-Negative: The classifier mistakenly labels the target object as a non-target (Pubert calls his mother “Wez-day”).</p><p>With that out of the way, let’s dive into how image classifiers are trained.</p><h3>Preparation</h3><p>You’re going to need images. A LOT of images. Specifically, you’ll need two sets of images. One set should be compiled of images of the target objects you want your algorithm to detect and you’ll want the them to be featured in a variety of settings. When I say “settings”, I mean that the images shouldn’t ALL come from the same background, at the exact same angle, with the same lighting, and the same distance from the camera. Generally, it should vary since, in practice, the target object will rarely, if ever, be subject to the exact same circumstances. If all or a majority of your images were taken in such sterile circumstances, it would also have a huge impact on the training process, a point we’ll address shortly.</p><p>The second set of should contain images of literally anything else. The entire point of this set is to help the algorithm learn what the target object <em>isn’t</em> and narrow down what features are unique to the target. If you really want to train your algorithm well, most (if not all) of the images should share similarities with the target object. For example, if you wanted to make an algorithm that could detect a Walmart, you would want to include pictures of Best Buy, Target, and other stores in this set. That way, the algorithm can learn that a Walmart isn’t just any large cement building.</p><h4>Number of Images</h4><p>As for the number of images in each set, it depends on how much time and resources you have. Image classifiers such as Google’s Xception model were trained on the ImageNet dataset, which contained over 14 million images. That’s a lot of images and it would take forever to train even with top of the line hardware. The Viola-Jones algorithm was trained on nearly 5,000 faces and about 5,000 non-faces. If you want a reliable model, you’re going to want a few hundred in for each set. Also, having a roughly even distribution (e.g. about 50–50 split of target and non-target images) is highly recommended.</p><h4>Labeling</h4><p>In each of these sets, the images should be labeled to indicate whether or not they’re an image of the target object (e.g. “Walmart” or “Not Walmart”). While this can be painstakingly mind-numbing, it is a crucial step since both of these sets will be combined. Without labels to use as an answer key, the algorithm will have no way of evaluating whether its predictions were correct. Labeled data ensures that your algorithm’s predictions are reliable and minimize the number of false-positives and false-negatives.</p><h4>Image Transforming</h4><p>Like we’ve said in previous lessons, the image is transformed from color to grayscale. This is true both in training and in practice. It makes the math easier and helps the algorithm to run quicker.</p><p>Another transformation that is performed is that the image resolution is rescaled. This reduces the computational complexity by reducing the total possible number of Haar-like features that can fit within the image. Viola and Jones reduced their images to 24x24 pixels and each image still contained over 180,000 features. This transformation is only done in training, however. After the algorithm is trained, the images it is used on remain the same resolution, but the features and their weights (more on this below) are scaled up.</p><h4>Creating Training and Test Sets</h4><p>After labeling all of the images, you shuffle sets together. After it’s shuffled you’ll make a set for training and a smaller set for testing the algorithm on. The reason for this is that once an algorithm or machine learning model has been trained, it is able to recognize data that it was trained with and, as a result, already knows what to predict. By reserving a small portion of the data (the validation or test set) for evaluating AFTER training is complete, we’re able to get a sense for how accurately the algorithm actually performs because it has never seen this particular data before.</p><h3>Training</h3><p>Let’s refer back to the Viola-Jones algorithm once more to discuss training. So during training, the model is fed various face and non-face images. It maps out all of the possible Haar-like features in each image and makes a prediction on whether or not the image contains a face. Let’s say it first started with this image of George Clooney:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*mnmNS2V_XjDjnhpcGb4QHw.jpeg" /><figcaption>Image Source: <a href="https://www.google.com/search?q=george+clooney&amp;tbm=isch&amp;ved=2ahUKEwjs5M6alf7uAhWLoFMKHRPOCvcQ2-cCegQIABAA&amp;oq=george+cloo&amp;gs_lcp=CgNpbWcQARgAMggIABCxAxCDATIFCAAQsQMyBQgAELEDMgUIABCxAzIFCAAQsQMyBQgAELEDMgUIABCxAzIICAAQsQMQgwEyCAgAELEDEIMBMggIABCxAxCDAToECCMQJzoCCAA6BAgAEEM6CggAELEDEIMBEENQncEPWPHmD2D_8A9oAXAAeACAAVqIAeYHkgECMTKYAQCgAQGqAQtnd3Mtd2l6LWltZ8ABAQ&amp;sclient=img&amp;ei=y_0zYKzTA4vBzgKTnKu4Dw&amp;bih=1323&amp;biw=1278#imgrc=yDbDiYNYf372mM">Today.com</a></figcaption></figure><p>It’s the first image that it has seen and has literally nothing else to go off of. It maps out the Haar-like features in the image and predicts “face” for no reason (kinda like a baby’s first words). It’s correct and so the algorithm says to itself, “Okay, I am looking for something that looks exactly like this!” So it assigns a <strong>weight</strong> to every single Edge, Line, and Four-rectangle feature in this image. A “weight” just a numerical value of how <strong>important</strong> the feature is. The larger the number, the more important that feature is.</p><p>It should also be noted that when I say every feature, I mean EVERY feature! At this point with an untrained algorithm, every single Haar-like feature that is possibly detected (even in the background) are fair game. In our hypothetical scenario here, not only is Georgie boy’s face considered a face, but even the blurred out background is considered a face. Why? Because, just like a baby, the algorithm doesn’t know any better. This is the only image it has seen so far. As such, the background is considered as equally important as the actual face.</p><p>The next image it sees is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLHH-y0QGMHtNgR4RY07rw.jpeg" /><figcaption>Image Source: <a href="https://www.eater.com/2019/8/9/20799131/seagull-beach-food-stealing-stare-it-in-the-eye">Eater.com</a></figcaption></figure><p>For some odd reason, the person compiling the sets included this image of a seagull. It shares very few of the Haar-like features from Clooney’s photo and, for this reason, the algorithm predicts “Not Face”. Since it’s correct, the algorithm doesn’t change its opinion of what a face is (currently, a single picture of George Clooney). None of the weights are adjusted as a result. This is the reason non-target images used during training should share similarities with the target. It creates a higher chance of a false-positive. This leads to the algorithm making adjustments to the feature weights and reconsider what features are the most important to minimize a false-positive.</p><p>The next image it sees is this picture of Chris Pratt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fe_YUHRv3Pc20p8tZKmZLA.jpeg" /><figcaption>Image Source: <a href="https://www.independent.co.uk/news/people/17-rich-and-famous-people-who-were-once-homeless-a7350941.html">Independent.co.uk</a></figcaption></figure><p>While this certainly has more features in common with Clooney’s picture than the seagull’s, remember that at this point, the algorithm thinks that a “face” is a picture of George Clooney with a blurry background (every feature in that picture is currently of equal importance). Because of this, let’s say that our algorithm is going to predict that this isn’t a face. BOOM! Our first false-negative! Now the algorithm looks at what similarities the two images have and adjusts the weights of the features it considers to be most important. Since each image has a fuzzy background, we’ll say that our algorithm has noticed that both pictures clearly outline the head and shoulders and thinks, “Alright, this shape must be a face.” It adjusts the weights of those features and considers them the most important.</p><p>Then it see’s this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CN7gcawolnN1Yh70uOCl0Q.png" /><figcaption>Image Source: <a href="http://haleypatterson.weebly.com/project-3-final-images.html">Haley Patterson</a></figcaption></figure><p>We have the all the features of the outline that we saw before and the algorithm now has a little bit of wiggle room for interpretation thanks to the other weights being adjusted, so let’s say that it predicts “face”. BOOM! False-positive! Its definition that a face is simply the outline of the human body is too general (much like Pubert’s definition of “Mama” at the beginning). Now the algorithm re-evaluates. It goes back to the features that Clooney and Pratt shared. They both have eyes! Perhaps eyes are the most important feature! So it adjusts the weights accordingly and moves onto the next photo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*pEvl7ZYOM71Kudi_IYgB6g.jpeg" /><figcaption>Image Source: <a href="https://www.teenvogue.com/gallery/best-sunglass-chains-trend-gigi-hadid">teenvogue.com</a></figcaption></figure><p>Well, this person has no eyes, so it can’t possibly be a face! It predicts “Not Face”. Another false-negative. Again, the algorithm re-evaluates and decides since they all had noses, that must be what defines a face!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_57Je5e9rCEGOKr9Ty4HMA.jpeg" /></figure><p>Ok, so it’s not the nose. They all have lighter skin!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*yoWQAO4URNzRQp_0ahfZWw.jpeg" /><figcaption>Image Source: <a href="https://twitter.com/lancereddick">Lance Reddick</a></figcaption></figure><p>You can see where I’m going with this. This is why you need such a diverse set of images to train on. If all of the target images were the same, the algorithm would only work when it was under the exact same circumstances. With a diverse training set, however, the algorithm learns what is and is not a face and adjusts what combination of features to look for in an image that minimizes the probability of getting a false-positive or false-negative. And just like the baby in our analogy, the algorithm discovers more and more features that are unique to the target object.</p><h3>Summary</h3><p>While there is a lot more math involved (something we’ll go over next week), the overall process of training an image classifying algorithm is very intuitive and almost human in nature.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97825ac4bfde" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/training-day-training-image-classifiers-97825ac4bfde">Training Day: Training Image Classifiers</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Integral Image]]></title>
            <link>https://levelup.gitconnected.com/the-integral-image-4df3df5dce35?source=rss-e0c9e4a3e1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df3df5dce35</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[viola-jones]]></category>
            <category><![CDATA[face-detection-software]]></category>
            <category><![CDATA[integral-image]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[BenMauss]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 22:52:40 GMT</pubDate>
            <atom:updated>2021-02-16T16:50:14.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to Computer Vision, Part 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UIjX20rXN5KfGXf7HCUUg.jpeg" /><figcaption>Image Source: <a href="https://venturebeat.com/2020/08/29/how-to-tell-if-computer-vision-can-transform-your-business/">VentureBeat.com</a></figcaption></figure><p><a href="https://levelup.gitconnected.com/haar-like-features-seeing-in-black-and-white-1a240caaf1e3">Last time</a>, we discussed Haar-like features, what they are, how they help the Viola-Jones algorithm detect objects, and how they determine if they’ve found a feature. We covered a lot of information and if you’ve never heard of Haar-like features before, I highly recommend reading the previous article, as any summary I give will not be enough to give you the foundation needed to understand our topic today: The Integral Image.</p><p>To really underscore the importance of the Integral Image, let’s talk a little bit about…</p><h3>The Big O</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*mmtscGVX5mjSmhdA0RvB-w.gif" /><figcaption>Image Source: <a href="https://www.pinterest.ca/pin/756182593678986973/">Pinterest.com</a></figcaption></figure><p>No, not that Big O. This Big O:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*k-acuFitTKegB5l5JTn0tA.png" /><figcaption>Image Source: <a href="https://medium.com/journey-of-one-thousand-apps/complexity-and-big-o-notation-in-swift-478a67ba20e7">Christopher Webb</a></figcaption></figure><p>The Big O is a method of computing the amount of time and resources used to accomplish a task. As you increase the number of variables/elements/inputs, the longer the process takes and the more resources (processing power, memory, etc.) it uses up. Don’t get bogged down too much in the details just remember this:</p><blockquote>As you increase the complexity of a task, the amount of time and resources needed increase <strong>exponentially</strong>.</blockquote><p>Now, how does this relate to Integral Images?</p><p>So remember that Haar-like features are a series of frames that “pan” over an array that represents a grayscale image. These frames can be scaled to nearly any size except a 1x1 pixel. This is because each cell (or element) of the frame (and the image array) represents a single pixel, which can only contain the value for a single color. The other reason is because the entire function of these frames is to compare the “white-ness” and “black-ness” of <em>neighboring</em> pixels and, therefore, cannot be scaled down to a single pixel.</p><p>While many Haar-like features have been developed since the creation of the Viola-Jones in 2001, we’re focusing on the three that was available to them at the time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*hbFPsfsCqV8rf1MV8b8p5w.jpeg" /><figcaption>Image Source: <a href="https://docs.opencv.org/master/d2/d99/tutorial_js_face_detection.html">OpenCV.org</a></figcaption></figure><ul><li>Edge Features: Detect edges of an object. Smallest scale- 1x2 or 2x1.</li><li>Line Features: Detect lines and highlights within an object. Smallest scale- 1x3 or 3x1.</li><li>Four-Rectangle Features: Detect diagonal edges and lines. Smallest scale- 2x2</li></ul><p>A feature is classified by calculating the means of the “lighter” and “darker” sides of the frame and subtracting them from one another. If the difference lands within a certain threshold, then the algorithm recognizes that the pixels within that frame make up a Haar-like feature.</p><p>This is where the Big O comes into play. Since these frames are scalable, there are thousands of combinations and places where features fit within even a tiny image. As was mentioned in the <a href="https://levelup.gitconnected.com/haar-like-features-seeing-in-black-and-white-1a240caaf1e3">previous article</a>, a 24x24 pixel image contains over 180,000 possible features. The frames within that image can be between 1x2 (or 2x1) pixels and 24x24 pixels.</p><p>To better illustrate this problem, consider this example:</p><p>Let’s say that the amount of time it takes for a computer to calculate the mean of a single feature is 1 millisecond (this would be incredibly slow, but let’s run with it). Since there are over 180,000 features in a 24x24 pixel image, it would take 180,000ms (3 minutes) to calculate all of the features in it. That’s not including processing power and memory used up to complete it.</p><p>The amount of time explodes even more when you consider that, these days, you’re most likely going to be using an image with a resolution of 1920x1080 pixels. In order to reduce the amount of time and resources used up, we need to find a way to reduce the complexity of the task. How did Viola and Jones accomplish this to such a degree that their algorithm could detect faces in real-time on a digital camera?</p><h3>Enter: the Integral Image</h3><p>What is an Integral Image anyway? Well, it’s an array whose values are the sums of values of an image. What values, though? And how is it arranged in any meaningful way? Let’s just make one. It’ll be easier to understand when you see it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*ZaFmHzlhp3VKniaH.png" /><figcaption>Figure 1</figcaption></figure><p>Let’s say that this array represents a 10x8 pixel image. As we know, the numbers represent how bright a pixel is on that channel. For the sake of simplicity, let’s say that we didn’t scale these values down to be between 0 and 1. So these values are on their original scale of 0 to 255 with 0 being no brightness and 255 being the brightest (meaning the image above is almost pitch-black).</p><p>The algorithm takes this original image and creates an array of sums with the exact same dimensions called the integral image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*js6X9RqBvnksPtfDGnGJ3A.png" /><figcaption>Figure 1.02</figcaption></figure><p>It then begins to populate this table by calculating the sums of the values in the original image following a specific pattern. Again, it’ll be easier to understand when we see it in action. Let’s say we want the value shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*pqL1n-wp5H930w-0.png" /><figcaption>Figure 1.03</figcaption></figure><p>Well, this cell is not a pixel, but the sum of all values in a corresponding area on the original image. To calculate its value, go to the pixel of the original image that corresponds to this one. Then draw a line from the bottom-right corner going straight up and another going to the left. Shade in the values that are above and to the left of these lines and you’ll get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*a15YWuoBaIx0KWFV.png" /><figcaption>Figure 1.04</figcaption></figure><p>The value for the cell in our <strong>integral image</strong> is the <strong>sum </strong>of all the numbers in the <strong>shaded area</strong>. The sum of these numbers is 51, so let’s go ahead and put that in our Integral Image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*IvYh4uoYo6hwTPd8.png" /><figcaption>Figure 1.05</figcaption></figure><p>Awesome! Let’s try one more to get the hang of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*Ukn-NREYjPaTwK2k.png" /><figcaption>Figure 1.06</figcaption></figure><p>What area of the original image would the cell below represent?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*hbN3q4dX846GV8Vl.png" /><figcaption>Figure 1.07</figcaption></figure><p>If this was your answer, you’d be right! Now to put it in our Integral Image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*EsAVpqLaPtZKw4aD.png" /><figcaption>Figure 1.08</figcaption></figure><p>By now, you’ve probably noticed a pattern. A <strong>cell </strong>in the <em>Integral </em>image <strong>corresponds to a specific area</strong> in the <em>original </em>image. The <strong>value </strong>of that cell is the<strong> sum of all the values in that corresponding area</strong> in the original image. Now that we have a little bit of intuition for how an Integral mage is made and organized, let’s fill out the rest of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*vBy_3EqGmRbCuvsav4ffVg.png" /><figcaption>Figure 1.09</figcaption></figure><p>Now, go back to the <em>original </em>image. We’re going to select a portion of the image that we want to find the sum of and we’ll outline it in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*YVYDq4wmHET3QAfP.png" /><figcaption>Figure 1.10</figcaption></figure><p>This is only 5x3 pixels large, so we could just add up all 15 numbers, it’s not that hard. However, what if we had a frame that was 100x100 pixels? or 1000x1000 pixels? That’s a lot of numbers to add up! This is where the Integral image shines. Because each cell of the Integral image corresponds to an <em>area</em> of the original image, we can find the sum of the area that holds all of the values we have outlined and then subtract the excess values. Let’s try it out!</p><p>First, find the cell that corresponds to the bottom-right pixel in the red box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*5RBJ-bGTT2M504A4.png" /><figcaption>Figure 1.11</figcaption></figure><p>Now, again, this number is the sum of the values located in a specific area of the original image. What area of the <em>original </em>image does this cell correspond to?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*_CoWSnq_xgx_PH_Q.png" /><figcaption>Figure 1.12</figcaption></figure><p>Ok! We’ve already started to isolate the area in the box! Referring back to the Integral image, we know that the sum of this shaded portion is 215. This still includes values outside of the red box, however, so we need to remove some more.</p><p>Luckily, these excess values can be broken down into two shapes seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*I7ZlDjRgrJRvAezi.png" /><figcaption>Figure 1.13</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*4hLuDdFmo8sAVneU.png" /><figcaption>Figure 1.14</figcaption></figure><p>Let’s start by removing the top two rows (shaded in orange in Figure 1.13). What cell in the <em>Integral </em>image would correspond to this area?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*vZyh1UBs95YL7hYb.png" /><figcaption>Figure 1.15</figcaption></figure><p>80! When you subtract 80 from 215, you get 135. Let’s check our progress on the original image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*PgBfCWSLYsuaSN3L.png" /><figcaption>Figure 1.16</figcaption></figure><p>So the sum of the values shaded in blue is 135. Now we just need to remove that last part shaded in green in Figure 1.14. There’s a problem, that we need to address first, however!</p><p>Take a second to compare Figures 1.13 and 1.14. A keen eye would notice that they overlap! Looking at Figure 1.17 below, you’ll see the overlapping area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*9YDFU1afVSJ1lsqC.png" /><figcaption>Figure 1.17</figcaption></figure><p>The problem then is that we’ve already subtracted the sum of this area when we removed the top two rows. If we jump ahead and subtract the green shaded area from Figure 1.14, we’ll be subtracting these values twice! No worries, though! This is an easy fix. We simply need to add these values back into our calculations. So go back to the integral image and find the value that corresponds to the pink area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*-BS1IgKZhAzKRSKH.png" /><figcaption>Figure 1.18</figcaption></figure><p>That’s right! 20! So add this back to our running total and we have 155. More importantly, however, we’ve fixed the problem. Check it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*e6Ilvu0rLoPabEu6.png" /><figcaption>Figure 1.19</figcaption></figure><p>The remaining blue shaded area now perfectly lines up with the green area in Figure 1.14! Now we just subtract this area! Let’s find the value on the integral image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*-fGolxBu66Am12bz.png" /><figcaption>Figure 1.20</figcaption></figure><p>Perfect! Subtract subtracting this will get us our answer. 155- 72 = 83. That’s the sum of all of the values in the red box on the original image from Figure 1.10!</p><p>Now, what does this all mean? Quite simply, no matter how many pixels are selected in a frame, you only need four numbers to calculate the sum of those values. Whether the area is 24x24 pixels or 1000x1000 pixels, it doesn’t matter. You only need those four numbers. This process drastically reduces the complexity of the task, which reduces the amount of time and resources needed to compute.</p><h3>Applying to Haar-like Features</h3><p>So how does this work with the Viola-Jones algorithm? Let’s take a look at the original image again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*-JkRaaUIQLJ-rq1PWx4nug.png" /><figcaption>Figure 2</figcaption></figure><p>The frame here represents an Edge feature. The algorithm needs to calculate the means of the lighter and darker halves and subtract them to see if the difference falls within the threshold. For the sake of the argument, let’s say that our threshold is 10 (remember that we’re interpreting the values in the array as if they were still on a scale of 0 to 255). So it creates the integral image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*NXV0wbZSRuqMBKvjjiKlgg.png" /><figcaption>Figure 2.01</figcaption></figure><p>Then it calculates the sum of the lighter half by finding the four relevant numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*KLgsyAzg_ewGjUtYd7Ly6Q.png" /><figcaption>Figure 2.02</figcaption></figure><blockquote>255 - 215 + 46 - 55 = 31</blockquote><p>Taking this sum, the algorithm calculates the mean by dividing it by the number of columns in the frame.</p><blockquote>31 / 6 = 5.167</blockquote><p>Now, it follows the exact same steps to find the mean of the darker half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*USQA6BdGpi-92YOH1UARHg.png" /><figcaption>Figure 2.03</figcaption></figure><blockquote>302 - 255 + 55 - 69 = 33</blockquote><blockquote>33 / 6 = 5.5</blockquote><p>Now, it subtracts the means to see if it falls within the threshold.</p><blockquote>5.5 - 5.167 = 0.333</blockquote><p>This falls way outside of our threshold and the algorithm determines that there is no Edge feature in this portion of the image and moves on.</p><h3>Summary</h3><p>We covered a lot of ground today, but the key takeaway is that the Integral Image plays a big role in reducing the amount of time and processing power required to calculate and evaluate hundreds of thousands of features in real-time. It’s clever shortcuts like this that made this object detection possible on hardware 20 years ago. It’s simply brilliant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4df3df5dce35" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-integral-image-4df3df5dce35">The Integral Image</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>