<?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 Dale Kellegrew on Medium]]></title>
        <description><![CDATA[Stories by Dale Kellegrew on Medium]]></description>
        <link>https://medium.com/@dalekellegrew?source=rss-de8d174c1cfc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ATOoSrZ9ATepWX4n</url>
            <title>Stories by Dale Kellegrew on Medium</title>
            <link>https://medium.com/@dalekellegrew?source=rss-de8d174c1cfc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:55:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dalekellegrew/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[Brute force Coding Solutions]]></title>
            <link>https://medium.com/@dalekellegrew/brute-force-coding-solutions-23912c42cc2b?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/23912c42cc2b</guid>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 06:31:50 GMT</pubDate>
            <atom:updated>2020-04-01T06:31:50.213Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>brute force</strong> algorithm finds a solution by trying <em>all</em> possible answers and picking the best one.</p><p>Say you’re a cashier and need to give someone 67 cents (US) using as few coins as possible. How would you do it?</p><p>You could try running through all potential coin combinations and pick the one that adds to 67 cents using the fewest coins. That’s a <em>brute force</em> algorithm, since you’re trying <em>all</em> possible ways to make change.</p><p>Here are a few other brute force algorithms:</p><ul><li>Trying to fit as many overlapping meetings as possible in a conference room? Run through all possible schedules, and pick the schedule that fits the most meetings in the room.</li><li>Trying to find the cheapest route through a set of cities? Try all possible routes and pick the cheapest one.</li><li>Looking for a minimum spanning tree in a <a href="https://www.interviewcake.com/concept/graph">graph</a>? Try all possible sets of edges, and pick the cheapest set that’s also a tree.</li></ul><p><strong>Brute force solutions are usually <em>very slow</em> since they involve testing a huge number of possible answers.</strong></p><p>Brute force approaches are rarely the most efficient. Other approaches, like <a href="https://www.interviewcake.com/concept/greedy">greedy algorithms</a> or <a href="https://www.interviewcake.com/concept/bottom-up">dynamic programming</a> tend to be faster.</p><p>Even so, talking through a brute force solution can be a good first step in a coding interview. It’s usually pretty easy to derive, so it allows you to quickly make progress and come up with <em>something</em> that works. From there, you have some helpful boundaries for refining your algorithm — you’re only interested in solutions that are faster (and/or more space efficient) than the brute force solution you’ve already come up with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23912c42cc2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O Notation]]></title>
            <link>https://medium.com/@dalekellegrew/big-o-notation-6a69997cbf8f?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a69997cbf8f</guid>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 06:42:32 GMT</pubDate>
            <atom:updated>2020-03-25T06:42:32.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>The idea behind big O notation</h3><p><strong>Big O notation is the language we use for talking about how long an algorithm takes to run</strong>. It’s how we compare the efficiency of different approaches to a problem.</p><p>It’s like math except it’s an <strong>awesome, not-boring kind of math</strong> where you get to wave your hands through the details and just focus on what’s <em>basically</em> happening.</p><p>With big O notation we express the runtime in terms of — brace yourself — <em>how quickly it grows relative to the input, as the input gets arbitrarily large</em>.</p><p>Let’s break that down:</p><ol><li><strong>how quickly the runtime grows</strong> — It’s hard to pin down the <em>exact runtime</em> of an algorithm. It depends on the speed of the processor, what else the computer is running, etc. So instead of talking about the runtime directly, we use big O notation to talk about <em>how quickly the runtime grows</em>.</li><li><strong>relative to the input</strong> — If we were measuring our runtime directly, we could express our speed in seconds. Since we’re measuring <em>how quickly our runtime grows</em>, we need to express our speed in terms of…something else. With Big O notation, we use the size of the input, which we call “n<em>n</em>.” So we can say things like the runtime grows “on the order of the size of the input” (O(n)) or “on the order of the square of the size of the input” (O(n²)).</li><li><strong>as the input gets arbitrarily large</strong> — Our algorithm may have steps that seem expensive when n<em>n</em> is small but are eclipsed eventually by other steps as n<em>n</em> gets huge. For big O analysis, we care most about the stuff that grows fastest as the input grows, because everything else is quickly eclipsed as n<em>n</em> gets very large. (If you know what an asymptote is, you might see why “big O analysis” is sometimes called “asymptotic analysis.”)</li></ol><p>If this seems abstract so far, that’s because it is. Let’s look at some examples.</p><h3>Some examples</h3><pre>def print_first_item(items):<br>    print(items[0])</pre><p><strong>This function runs in O(1) time (or “constant time”) relative to its input</strong>. The input list could be 1 item or 1,000 items, but this function would still just require one “step.”</p><pre>def print_all_items(items):<br>    for item in items:<br>        print(item)</pre><p><strong>This function runs in O(n) time (or “linear time”), where n is the number of items in the list</strong>. If the list has 10 items, we have to print 10 times. If it has 1,000 items, we have to print 1,000 times.</p><pre>def print_all_possible_ordered_pairs(items):<br>    for first_item in items:<br>        for second_item in items:<br>            print(first_item, second_item)</pre><p>Here we’re nesting two loops. If our list has n items, our outer loop runs n times and our inner loop runs n<em> times for each iteration of the outer loop</em>, giving us n²<em>n</em>2 total prints. Thus <strong>this function runs in O(n²) time (or “quadratic time”)</strong>. If the list has 10 items, we have to print 100 times. If it has 1,000 items, we have to print 1,000,000 times.</p><h3>N could be the actual input, or the size of the input</h3><p>Both of these functions have O(n) runtime, even though one takes an integer as its input and the other takes a list:</p><pre>def say_hi_n_times(n):<br>    for time in range(n):<br>        print(&quot;hi&quot;)<br></pre><pre>def print_all_items(items):<br>    for item in items:<br>        print(item)</pre><p>So sometimes n<em>n</em> is an <em>actual number</em> that’s an input to our function, and other times n<em>n</em> is the <em>number of items</em> in an input list (or an input map, or an input object, etc.).</p><h3>Drop the constants</h3><p>This is why big O notation <em>rules</em>. When you’re calculating the big O complexity of something, you just throw out the constants. So like:</p><pre>def print_all_items_twice(items):<br>    for item in items:<br>        print(item)</pre><pre>    # Once more, with feeling<br>    for item in items:<br>        print(item)</pre><p>This is O(2n), which we just call O(n).</p><pre>def print_first_item_then_first_half_then_say_hi_100_times(items):<br>    print(items[0])</pre><pre>    middle_index = len(items) / 2<br>    index = 0<br>    while index &lt; middle_index:<br>        print(items[index])<br>        index += 1</pre><pre>    for time in range(100):<br>        print(&quot;hi&quot;)</pre><p>This is O(1 + n/2 + 100), which we just call O(n)<em>O</em>(<em>n</em>).</p><p>Why can we get away with this? Remember, for big O notation we’re looking at what happens <strong>as n gets arbitrarily large</strong>. As n gets really big, adding 100 or dividing by 2 has a decreasingly significant effect.</p><h3>Drop the less significant terms</h3><p>For example:</p><pre>def print_all_numbers_then_all_pair_sums(numbers):<br>    print(&quot;these are the numbers:&quot;)<br>    for number in numbers:<br>        print(number)</pre><pre>    print(&quot;and these are their sums:&quot;)<br>    for first_number in numbers:<br>        for second_number in numbers:<br>            print(first_number + second_number</pre><p>Here our runtime is O(n + n²)), which we just call O(n²). Even if it was O(n²/2 + 100n), it would still be O(n²).</p><p>Similarly:</p><ul><li>O(n³ + 50n² + 10000)) is O(n³)</li><li>O((n + 30) * (n + 5)) is O(n²)</li></ul><p>Again, we can get away with this because the less significant terms quickly become, well, less significant as n<em>n</em> gets big.</p><h3>We’re usually talking about the “worst case”</h3><p>Often this “worst case” stipulation is implied. But sometimes you can impress your interviewer by saying it explicitly.</p><p>Sometimes the worst case runtime is significantly worse than the best case runtime:</p><pre>def contains(haystack, needle):</pre><pre>    # Does the haystack contain the needle?<br>    for item in haystack:<br>        if item == needle:<br>            return True</pre><pre>    return False</pre><p>Here we might have 100 items in our haystack, but the first item might be the needle, in which case we would return in just 1 iteration of our loop.</p><p>In general we’d say this is O(n) runtime and the “worst case” part would be implied. But to be more specific we could say this is worst case O(n) and best case O(1) runtime. For some algorithms we can also make rigorous statements about the “average case” runtime.</p><h3>Space complexity: the final frontier</h3><p>Sometimes we want to optimize for using less memory instead of (or in addition to) using less time. Talking about memory cost (or “space complexity”) is very similar to talking about time cost. We simply look at the total size (relative to the size of the input) of any new variables we’re allocating.</p><p>This function takes O(1)space (we use a fixed number of variables):</p><pre>def say_hi_n_times(n):<br>    for time in range(n):<br>        print(&quot;hi&quot;)</pre><p>This function takes O(n) space (the size of hi_list scales with the size of the input):</p><pre>def list_of_hi_n_times(n):<br>    hi_list = []<br>    for time in range(n):<br>        hi_list.append(&quot;hi&quot;)<br>    return hi_list</pre><p><strong>Usually when we talk about space complexity, we’re talking about <em>additional space</em></strong>, so we don’t include space taken up by the inputs. For example, this function takes constant space even though the input has n<em>n</em> items:</p><pre>def get_largest_item(items):<br>    largest = float(&#39;-inf&#39;)<br>    for item in items:<br>        if item &gt; largest:<br>            largest = item<br>    return largest</pre><p><strong>Sometimes there’s a tradeoff between saving time and saving space</strong>, so you have to decide which one you’re optimizing for.</p><h3>Big O analysis is awesome except when it’s not</h3><p>You should make a habit of thinking about the time and space complexity of algorithms <em>as you design them</em>. Before long this’ll become second nature, allowing you to see optimizations and potential performance issues right away.</p><p>Asymptotic analysis is a powerful tool, but wield it wisely.</p><p>Big O ignores constants, but <strong>sometimes the constants matter</strong>. If we have a script that takes 5 hours to run, an optimization that divides the runtime by 5 might not affect big O, but it still saves you 4 hours of waiting.</p><p><strong>Beware of premature optimization</strong>. Sometimes optimizing time or space negatively impacts readability or coding time. For a young startup it might be more important to write code that’s easy to ship quickly or easy to understand later, even if this means it’s less time and space efficient than it could be.</p><p>But that doesn’t mean startups don’t care about big O analysis. A great engineer (startup or otherwise) knows how to strike the right <em>balance</em> between runtime, space, implementation time, maintainability, and readability.</p><p><strong>You should develop the <em>skill</em> to see time and space optimizations, as well as the <em>wisdom</em> to judge if those optimizations are worthwhile.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a69997cbf8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why it’s so hard to lose weight but easy to gain muscle]]></title>
            <link>https://medium.com/@dalekellegrew/why-its-so-hard-to-lose-weight-but-easy-to-gain-muscle-d6e5876c6df2?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e5876c6df2</guid>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 06:34:20 GMT</pubDate>
            <atom:updated>2020-03-18T06:34:20.460Z</atom:updated>
            <content:encoded><![CDATA[<p>I see a lot of people struggling to either “bulk up” or lose weight. There is some simple math that will get you to either goal. I’ll start with how to gain muscle mass or “bulk up.”</p><p>To bulk up your goal is to gain muscle tissue without gaining fat alongside it. This is achievable by putting the correct stress on your body.</p><p>Step 1. Working out 3 days a week with 1–2 days inbetween workout and doing heavy 70–85% of your max lifts in reps of 5 with 3 sets. Only do one set of 5 with your work weight for deadlifts.</p><p>Doing a routine of Squats, Deadlift, Benchpress/Overhead press will last you 6 months to a year without needing to change routines. Just start at a low weight and add 5lbs a week to your squats and deadlifts while adding 2.5lb per week to your Benchpress/Overhead press.</p><p>Working out is the simple part of the equation. The hard part and Step 2 is…</p><p>Eating in order to give your body enough protien to build the muscle with.</p><p>In order to gain muscle mass at a rate of 10 lbs of muscle per month you need to convert 4340 grams of protien into muscle or 145 grams of protien into muscle every day. In addition to the 145 grams of protien your body needs fuel to live. Depending on how active you are and what your current height and weight is this will flucuate. I am 6 feet talk and weighed 145 pounds. To get to 180 pounds in 6 months I ate 3500–4000 calories per day (the 145 grams of protien is 580 calories of that amount.)</p><p>Why is losing Weight is so much harder than gaining it?</p><p>In order to lose 1 lb of fat you need to deprive yourself of 4000 calories of food!!! So in order to lose the 10 pounds of fat in a month you would need to NOT eat 40,000 calories that your body was telling you to eat or -1,333 calories per day! That’s freaking insane.</p><p>The trick to losing weight is that your body can only build up one type of cell at a time either muscle or fat. So to lose weight you can do the same weight lifting regime as above and eat 2000–2500 calories per day (so you don’t feel like you’re dying of starvation.)</p><p>The 4 things to know are:</p><ol><li>Protien which builds muscle is 4 calories per gram</li><li>Fats are 9 grams per calorie which is a great energy source</li><li>Carbs are also 4 calories per gram and help you feel full.</li><li>Your body can only build muscle or fat stores depending on what sort of stimulous you give it.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e5876c6df2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transmission rates of COVID-19 a quick summary]]></title>
            <link>https://medium.com/@dalekellegrew/transmission-rates-of-covid-19-a-quick-summary-adf9c8b9d264?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf9c8b9d264</guid>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 11 Mar 2020 06:10:30 GMT</pubDate>
            <atom:updated>2020-03-11T06:10:30.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cB201tL_qBuF8B9l.jpg" /></figure><p>I live in Seattle, WA where a total of 22 people have died of COVID-19 currently.</p><p>From doing some brief searching I found that the number of cases is doubling once per week. It can even spread through people who are not showing any symptoms.</p><p>Currently the WHO doesn’t know exactly how many people have been infected in part by the slow rollout of test kits in the US, Italy, and Iran.</p><p>Some Virologists are saying that this may turn into an endemic or just an illness that circulates are the human population like the common cold. Others are saying that 40–70% of people could catch the virus by the end of the year.</p><p>The most dangerous scenario is if a large population of people contract the desease at the same time in the same place say 10,000 in one city. Then they would overwhelm our healthcare system.</p><p>To slow the spread of COVID-19 out communities around the world are implementing different adviseries from avoiding large gatherings, handwashing more frequently, to even closing schools, and making people work from home.</p><p>All in all we don’t know who fast COVID-19 is spreading but people are working on a vaccine to help cure/slow it down. Let’s hope that it doesn’t kill as many people as it is predicted to, 3.4% of people who catch it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf9c8b9d264" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is it more likely to catch the coronavirus on your bus to work or at work?]]></title>
            <link>https://medium.com/@dalekellegrew/is-it-more-likely-to-catch-the-coronavirus-on-your-bus-to-work-or-at-work-1edb24874134?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1edb24874134</guid>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 07:19:11 GMT</pubDate>
            <atom:updated>2020-03-04T07:19:11.156Z</atom:updated>
            <content:encoded><![CDATA[<p>I was wondering whether or not the bus was safer than being a massage therapist when I comes to contracting viruses. Then I started to do some math.</p><p>Me as a massage therapist see 4–6 clients per day and wash my hands before and after touching them. There are also 5 other people that work at my office.</p><p>If everyone at my office interacts with 20 other people before me that is, 10x20, 200 points of contact of 2 degrees of separation from a virus.</p><p>On the other hand being on a bus that carries over 40–60 people in a cramped space which each have been in contact with 10 other people is 400–600 points of contact and I have to take the bus 2 times each day so 800–1200 points of contact.</p><p>With my very rough calculations it is 4 to 6 times more likely for me to catch the coronavirus on my way to and from work that at work even though I touch people for a living. It is probably way worse on my way home since people interact with more people at work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1edb24874134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Keyforge uses ML to randomly generate decks]]></title>
            <link>https://medium.com/@dalekellegrew/how-keyforge-uses-ml-to-randomly-generate-decks-6acfc0ae3f43?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6acfc0ae3f43</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 07:31:37 GMT</pubDate>
            <atom:updated>2020-02-26T07:31:37.323Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s how I think Keyforge a randomly generorated deck game builds their product.</p><p>First they have a random number generator pick 3 numbers from 1–7. These number each correspond with 1 faction in the set.</p><p>Second they roll for each of the 12 cards in 1 set to detemine rarity.</p><p>Third they either have a matrix of cards that go in a similar stratagy or just straight up randomize from the current card pools.</p><p>Repeat the 3rd step for the next 3 houses.</p><p>To randomize the name of the deck they have a bunch of templates an then they have a bunch of random words that are stuck into those templates to create randomized deck names.</p><p>To keep each deck unique the above algorithm can either keep a database and check the new deck against every other deck.</p><p>To avoid having to check too many times they just release new sets and then only have to check agianst those deck for that production cycle.</p><p>While possible for there to be 2 identical decks sneak though because they allow cards from previous sets to show up in new ones there are so many possibilites that it is extreme unlikely that it would happen with a new cards coming uot every 6 month.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6acfc0ae3f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How ML will be using with a Universal Healthcare system]]></title>
            <link>https://medium.com/@dalekellegrew/how-ml-will-be-using-with-a-universal-healthcare-system-2e1d1d820576?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e1d1d820576</guid>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 19 Feb 2020 07:25:17 GMT</pubDate>
            <atom:updated>2020-02-19T07:25:17.965Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of countries have Universal Healthcare. I wonder what sort of patient files and histories they have and what knowledge machine learning could extract from them.</p><p>What if we made a WebMD site that actually had geographical real time predictions based on what hostipitals were actually seeing? So if you caught an illness you could check it against what was currently happening in your city.</p><p>We could have a database that constantly updates with geographical maps based on whether the flu or an ecoli outbreak happens in real time. It could track cancer rates in certain populations within a city, or in certian areas of certain cities. The WHO could use it to more effectively track everything health oriented in the world from average heart rates to BPM to diet.</p><p>I would love to get my hands on this sort of data and start compiling a list of where and who I can get more of it so that we can have a stronger healthier world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e1d1d820576" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starter tutorial for Face Recognition]]></title>
            <link>https://medium.com/@dalekellegrew/starter-tutorial-for-face-recognition-1ad422e1fc78?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad422e1fc78</guid>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 04:47:44 GMT</pubDate>
            <atom:updated>2020-02-12T04:47:44.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how face recognition software in your smartphone works? If so, we will now make one our own.</p><p>Face recognition got all the hype in the smartphone industry after Apple has introduced the FaceID feature for its flagship iPhone X, albeit it was available on many apps like Facebook, Snapchat, Google Photos before. Now the face recognition system has become so advanced that it is now a norm for authentication purposes. Many countries like Chine have already adopted face recognition for use in payment portals, surveillance systems and even as a boarding pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*W0e9IzPmbS9kd_67.jpeg" /></figure><p>Before we start to make one, we need some understanding of some Deep Learning models.</p><h3>FaceNet</h3><p>We will be using FaceNet (<a href="https://arxiv.org/abs/1503.03832">https://arxiv.org/abs/1503.03832</a>) to implement our system.</p><p>Here is a direct quotation from the original FaceNet paper.</p><blockquote><em>FaceNet is a system that directly learns a mapping from face images to a compact Euclidean space where distances directly correspond to a measure of face similarity. Once this space has been produced, tasks such as face recognition, verification and clustering can be easily implemented using standard techniques with FaceNet embeddings as feature vectors.</em></blockquote><p><em>FaceNet maps a face into a 128D Euclidien space. The L2 distance(or Euclidien norm) between two faces embeddings corresponds to its similarity. This is exactly like measuring the distance between two points in a line to know if they are close to each other.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*3gJWPVKGs9f0Nhgr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*MpEvFTD8KmgnVHgH.png" /></figure><p>FaceNet model is a deep convolutional network that employs <em>triplet loss function. </em>Triplet loss function minimizes the distance between a positive and an anchor while maximizing the distance between the anchor and a negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*oaezgwqsSraSkcmJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*GuWRWjNkKkj2tARs.jpeg" /></figure><p>Taken from the original paper</p><p>We will be using a pre-trained FaceNet model available at <a href="https://github.com/davidsandberg/facenet">https://github.com/davidsandberg/facenet</a>.</p><h3>MTCNN</h3><p>We need to first detect and align the face before feeding it to the FaceNet model. This is achieved with a Multi-task cascaded convolutional neural networks(<a href="https://kpzhang93.github.io/MTCNN_face_detection_alignment/index.html">https://kpzhang93.github.io/MTCNN_face_detection_alignment/index.html</a>). If we feed an image into this network, it will give the bounding boxes for the faces in it(if present). We need not go into more details.</p><h3>Implementation</h3><p>We will now create a live face recognition system which can detect learned faces.</p><p>We can start by training an SVM to classify faces.</p><ol><li>Clone the repository <a href="https://github.com/athulpn/face-authenication.git">https://github.com/athulpn/face-authenication.git</a>.(Heavily based on <a href="https://github.com/davidsandberg/facenet.git">https://github.com/davidsandberg/facenet.git</a>). Download the model from <a href="https://drive.google.com/open?id=1EXPBSXwTaqrSC0OhUdXNmKSh9qJUQ55-">https://drive.google.com/open?id=1EXPBSXwTaqrSC0OhUdXNmKSh9qJUQ55-</a> and save it in ./src/models/ directory</li><li>Put photos of the same person in folders as shown below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*4BF4k5LLZc0fU9nN" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*7mgI1ozcannZgfPS.png" /></figure><p>3. Run ./facenet/src/classifier.py with required arguments. You need to provide the photo directory, model directory and the output model name(should be saved as classifier.pk).</p><p>4. We will now have a classifier which is capable of identifying the faces we have provided earlier.</p><p>We can now use the classifier which we have trained to identify faces from the webcam.</p><p>5. I have created a PreProcessor and classify class for aligning and classifying the images which we get from the webcam.</p><pre>from scipy import misc<br>import tensorflow as tf<br>import numpy as np<br>import detect_face<br><br><br>class PreProcessor():<br>    def __init__(self):<br>        with tf.Graph().as_default():<br>            gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.85)<br>            self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))<br>            with self.sess.as_default():<br>                self.pnet, self.rnet, self.onet = detect_face.create_mtcnn(self.sess, None)<br><br>            self.minsize = 20 # minimum size of face<br>            self.threshold = [ 0.6, 0.7, 0.7 ]  # three steps&#39;s threshold<br>            self.factor = 0.709 # scale factor<br><br>    def align(self,image_path, margin=44, image_size=160):<br>        img = misc.imread(image_path)<br>        img = img[:,:,0:3]<br>        bounding_boxes, _ = detect_face.detect_face(img, self.minsize, self.pnet, self.rnet, self.onet, self.threshold, self.factor)<br>        nrof_faces = bounding_boxes.shape[0]<br>        bb = np.zeros(4, dtype=np.int32)<br>        if nrof_faces&gt;0:<br>            det = bounding_boxes[:,0:4]<br>            img_size = np.asarray(img.shape)[0:2]<br>            if nrof_faces&gt;1:<br>                bounding_box_size = (det[:,2]-det[:,0])*(det[:,3]-det[:,1])<br>                img_center = img_size / 2<br>                offsets = np.vstack([ (det[:,0]+det[:,2])/2-img_center[1], (det[:,1]+det[:,3])/2-img_center[0] ])<br>                offset_dist_squared = np.sum(np.power(offsets,2.0),0)<br>                index = np.argmax(bounding_box_size-offset_dist_squared*2.0) # some extra weight on the centering<br>                det = (det[index,:])<br>        else:<br>            return bb<br>    <br>        det = np.squeeze(det)<br>        bb[0] = np.maximum(det[0]-margin/2, 0)<br>        bb[1] = np.maximum(det[1]-margin/2, 0)<br>        bb[2] = np.minimum(det[2]+margin/2, img_size[1])<br>        bb[3] = np.minimum(det[3]+margin/2, img_size[0])<br>        cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]<br>        scaled = misc.imresize(cropped, (image_size, image_size), interp=&#39;bilinear&#39;)<br>        misc.imsave(&quot;temp.png&quot;, scaled)<br>        return bb</pre><pre>import tensorflow as tf<br>import imageio <br>import numpy as np<br>import argparse<br>import os<br>import sys<br>import math<br>import pickle<br>import re<br><br>class Classify():<br>    def __init__(self):<br>        tf.logging.set_verbosity(tf.logging.ERROR)<br>        self.sess = tf.Session().__enter__()<br>        self.load_model(&quot;./model/&quot;)<br>        self.images_placeholder = tf.get_default_graph().get_tensor_by_name(&quot;input:0&quot;)<br>        self.embeddings = tf.get_default_graph().get_tensor_by_name(&quot;embeddings:0&quot;)<br>        self.phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(&quot;phase_train:0&quot;)<br>        self.embedding_size = self.embeddings.get_shape()[1]<br>        self.emb_array = np.zeros((1, self.embedding_size))<br><br>        classifier_filename_exp = os.path.expanduser(&quot;classifier.pk&quot;)<br>        with open(classifier_filename_exp, &#39;rb&#39;) as infile:<br>            (self.model, self.class_names) = pickle.load(infile)<br><br>    def __del__(self):<br>        self.sess.close()<br><br>    def predict(self, path):<br>        image = self.load_image(path)<br>        self.feed_dict = { self.images_placeholder:image, self.phase_train_placeholder:False }<br>        self.emb_array[0,:] = self.sess.run(self.embeddings, feed_dict=self.feed_dict)<br>        predictions = self.model.predict_proba(self.emb_array)<br>        best_class_indices = np.argmax(predictions, axis=1)<br>        best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]<br>        <br>        if best_class_probabilities[0] &lt; 0.8:<br>            return &quot;Unknown face&quot;<br>        else:<br>            return (self.class_names[best_class_indices[0]])<br><br>    def prewhiten(self, x):<br>        mean = np.mean(x)<br>        std = np.std(x)<br>        std_adj = np.maximum(std, 1.0/np.sqrt(x.size))<br>        y = np.multiply(np.subtract(x, mean), 1/std_adj)<br>        return y  <br>    <br>    def load_image(self, image_path):<br>        image = np.zeros((1, 160, 160, 3))<br>        img = imageio.imread(image_path)<br>        img = self.prewhiten(img)<br>        image[0,:,:,:] = img<br>        return image<br><br>    def load_model(self, model=&quot;./model&quot;):<br>        model_exp = os.path.expanduser(model)<br>        print(&#39;Model directory: %s&#39; % model_exp)<br>        meta_file, ckpt_file = self.get_model_filenames(model_exp)<br>        <br>        print(&#39;Metagraph file: %s&#39; % meta_file)<br>        print(&#39;Checkpoint file: %s&#39; % ckpt_file)<br>      <br>        self.saver = tf.train.import_meta_graph(os.path.join(model_exp, meta_file), input_map=None)<br>        self.saver.restore(tf.get_default_session(), os.path.join(model_exp, ckpt_file))<br><br>    def get_model_filenames(self, model_dir):<br>        files = os.listdir(model_dir)<br>        meta_files = [s for s in files if s.endswith(&#39;.meta&#39;)]<br>        if len(meta_files)==0:<br>            raise ValueError(&#39;No meta file found in the model directory (%s)&#39; % model_dir)<br>        elif len(meta_files)&gt;1:<br>            raise ValueError(&#39;There should not be more than one meta file in the model directory (%s)&#39; % model_dir)<br>        meta_file = meta_files[0]<br>        ckpt = tf.train.get_checkpoint_state(model_dir)<br>        if ckpt and ckpt.model_checkpoint_path:<br>            ckpt_file = os.path.basename(ckpt.model_checkpoint_path)<br>            return meta_file, ckpt_file<br><br>        meta_files = [s for s in files if &#39;.ckpt&#39; in s]<br>        max_step = -1<br>        for f in files:<br>            step_str = re.match(r&#39;(^model-[\w\- ]+.ckpt-(\d+))&#39;, f)<br>            if step_str is not None and len(step_str.groups())&gt;=2:<br>                step = int(step_str.groups()[1])<br>                if step &gt; max_step:<br>                    max_step = step<br>                    ckpt_file = step_str.groups()[0]<br>        return meta_file, ckpt_file</pre><p>Now we will use opencv to acquire frames from the webcam and then feed it to the classifier.</p><pre>import classify<br>import sys<br>import cv2<br>import preprocess<br>import time<br><br>classifier = classify.Classify()<br>preprocessor = preprocess.PreProcessor()<br><br>camera = cv2.VideoCapture(0)<br>i = 0;<br>start = time.time()<br>while True:<br>    return_value, image = camera.read()<br>    cv2.imwrite(&#39;opencv&#39;+str(i)+&#39;.png&#39;, image)<br>    bb = (preprocessor.align(&#39;opencv&#39;+str(i)+&#39;.png&#39;))<br>    cv2.rectangle(image, (bb[0],bb[1]), (bb[2],bb[3]), (0, 255, 0), 5)<br>    name = classifier.predict(&#39;temp.png&#39;)<br>    font = cv2.FONT_HERSHEY_SIMPLEX <br>    cv2.putText(image, name, (50, 50), font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)<br>    cv2.imshow(&#39;frame&#39;,image)<br>    cv2.imwrite(&#39;opencv&#39;+str(i)+&#39;.png&#39;, image)<br>    if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>        break<br>    i+=1<br>end_time = time.time()<br>print(i/(end_time-start))<br><br>camera.release()<br>cv2.destroyAllWindows()<br>print(classifier.predict(&#39;temp.png&#39;))</pre><p>6. Run the main.py file. Expect result as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5LBOQ4gXx8R4bKxe.png" /></figure><p>Yeah! Now we have now made a live face recognition system. If you have any doubt ask in the comments.</p><p>Image credits: Google Images.</p><p>Thanks to David Sandberg for his <a href="https://github.com/davidsandberg/facenet">facenet</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad422e1fc78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression and Maths]]></title>
            <link>https://medium.com/@dalekellegrew/linear-regression-and-maths-84e092811104?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e092811104</guid>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 06:40:10 GMT</pubDate>
            <atom:updated>2020-02-05T06:40:10.467Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear Regression are where machine learning models should always start when trying to have a computer guess a number. Linear Regression takes in data points in calculates the mean and makes a prediction from there.</p><p>y = b0 + b1 * x, is the equation for a Linear Regression.</p><p>To solve for the slope (b0 and b1) you take the sum of the points subtracted by the mean of that dimension, x or y.</p><p>B1 = sum((x(i) — mean(x)) * (y(i) — mean(y))) / sum( (x(i) — mean(x))² )<br>B0 = mean(y) — B1 * mean(x).</p><p>Doing this takes very little time so it is great to do before trying more time/space intensive methods.</p><p>Measuring how effective your Linear Regresion model is done by root mean squared error.</p><p>Thank you,</p><p>Dale Kellegrew</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e092811104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Boy who cried Type 1 and Type 2 Errors]]></title>
            <link>https://medium.com/@dalekellegrew/the-boy-who-cried-type-1-and-type-2-errors-e3a622c5dca7?source=rss-de8d174c1cfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a622c5dca7</guid>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Dale Kellegrew]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 07:18:39 GMT</pubDate>
            <atom:updated>2020-01-29T07:18:39.278Z</atom:updated>
            <content:encoded><![CDATA[<p>When doing statistical analysis of how good your machine learning model performs there are 2 types of errors. These errors are named Type 1 and Type 2. These names are not informative at all!</p><p>Type 1 errors are False Positives, when the model thinks the answer is true but it is actually false.</p><p>Type 2 errors are False Negatives, when the model thinks that the answer is false but it is actually true.</p><p>Wait, those descriptions didn’t clarify anything…</p><p>An easy trick to remembering which error is which is to think about the classic story of the “Boy Who Cried Wolf.” If you don’t know the story it is about a lazy child who is tasked with looking out for wolves to protect the town’s flock of sheep. The boy thinking that it would be funny to scare the town comes running in a few times yelling “WOLF!!!” when there is no wolf a Type 1error aka a False Positive. These actions cause the town’s people to stop trusting the boy.</p><p>Later in the story an actual wolf appears and the boy runs into town yelling “WOLF!!” but the town’s people don’t believe him anymore and all their sheep get eaten. This is an example of the type 2 error aka False Negative.</p><p>I hope this trick helps you all remember the difference between type 1 and type 2 errors. I know it sure helped me remember which is which.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a622c5dca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>