<?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 Andy Elmsley on Medium]]></title>
        <description><![CDATA[Stories by Andy Elmsley on Medium]]></description>
        <link>https://medium.com/@andyr0id?source=rss-5e7590883be1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pFpWRjWuG9lt1Lh929qugw.jpeg</url>
            <title>Stories by Andy Elmsley on Medium</title>
            <link>https://medium.com/@andyr0id?source=rss-5e7590883be1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 23:32:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andyr0id/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[Enter the Mutant: Genetic algorithms, part III]]></title>
            <link>https://medium.com/the-sound-of-ai/enter-the-mutant-genetic-algorithms-part-iii-3681fca42189?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3681fca42189</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 14:21:14 GMT</pubDate>
            <atom:updated>2019-06-19T14:21:14.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back, chromosomes! Over the last <a href="https://medium.com/the-sound-of-ai/intelligence-is-in-my-genes-genetic-algorithms-part-i-59fed978c118">two</a> <a href="https://medium.com/the-sound-of-ai/selection-crossover-i-choose-you-genetic-algorithms-part-ii-5ff620c10029">posts</a>, we’ve been exploring Genetic Algorithms (GAs). You might want to review those pieces before reading this one. We’ll start off with some problems you may have noticed in last week’s code, and address how to solve them by adding the final aspect of GAs: mutation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*13U8SdwXz2lKc1eq" /><figcaption>The X-Men get some pretty awesome mutations. Image: <a href="https://archive.nerdist.com/marvel-announces-the-return-of-the-x-men-blue-and-gold-teams-in-2017/">Nerdist</a></figcaption></figure><h3>What’s in a search?</h3><p>Last week I asked you to investigate the effect of the number of generations on the discovered solution. Setting the number of generations to 20 might give an output something like this:</p><blockquote>Generation 0 best fitness: 272<br>Generation 1 best fitness: 278<br>Generation 2 best fitness: 278<br>Generation 3 best fitness: 294<br>Generation 4 best fitness: 297<br>Generation 5 best fitness: 317<br>Generation 6 best fitness: 317<br>Generation 7 best fitness: 334<br>Generation 8 best fitness: 334<br>Generation 9 best fitness: 337<br>Generation 10 best fitness: 337<br>Generation 11 best fitness: 337<br>Generation 12 best fitness: 350<br>Generation 13 best fitness: 350<br>Generation 14 best fitness: 350<br>Generation 15 best fitness: 350<br>Generation 16 best fitness: 350<br>Generation 17 best fitness: 350<br>Generation 18 best fitness: 350<br>Generation 19 best fitness: 350<br>Generation 20 best fitness: 350</blockquote><p>As you can see, the fitness stops increasing (‘converges’) after 12 generations — but why does this happen?</p><p>Well, with selection and crossover being the only search operations in our GA, we only have a <strong>very limited gene pool </strong>to search. What’s worse, as the GA is iterating from one generation to the next, the search space shrinks. And after a while, the entire population will become exact clones of one another. At this stage the selection and crossover operations don’t actually do anything!</p><p>You may have also noticed that the GA search isn’t exhaustive — <strong>it won’t always discover the most optimum solution</strong> to the problem like a brute force method will. This is also partly down to the limited gene pool. The optimal solution will only be discovered if two criteria apply: the initial random population contains that magic set of genes, and they’re not lost in the crossover process. Quite a small chance of success, then.</p><p>In order to fix these two issues, we need to introduce the final weapon in the GA’s arsenal: mutation.</p><h3>Mutating the search</h3><p>In the theory of natural selection, forward leaps in fitness can only be achieved by a chance change in an organism’s genes. These genetic mutations may have allowed the first fish to breathe air, or the first mammals to walk upright — sometimes even spawning entirely new species.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-Rmuvaz-jq7TAPEz" /><figcaption>Genetic mutation: nature’s answer to novelty in search. Image: CC0 Public Domain</figcaption></figure><p>In GAs, mutation is implemented by altering a few genes in a chromosome, based on some random chance. So far, we’ve looked at <strong>binary chromosomes</strong> — chromosomes containing zeros and ones — and for these a simple mutation function can be implemented like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b203a8d7719751973bb3370fb3808f5e/href">https://medium.com/media/b203a8d7719751973bb3370fb3808f5e/href</a></iframe><p>Since mutation has the chance to result in a worse solution, it is usually implemented with a sense of <strong>elitism</strong>, where the best performing chromosome is not mutated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a215d24bf55bcbedde5f4ef29c7c7a81/href">https://medium.com/media/a215d24bf55bcbedde5f4ef29c7c7a81/href</a></iframe><h3>Evolution and balance</h3><p>What’s really happening with mutation is that we’re adding some randomness back into the population in order to keep <strong>variety</strong> in the search space, and potentially <strong>explore new spaces</strong> that weren’t in the initial population or have been lost over the generations. However, as with many things in AI, mutation isn’t a magic bullet. The GA will be sensitive to the balance between the population size and the mutation chance.</p><p>The following table shows this in action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cbd10ea04614e3b56d370382d8191db/href">https://medium.com/media/2cbd10ea04614e3b56d370382d8191db/href</a></iframe><p>The larger the population size, the smaller the mutation chance should be. In the above example, a population of 10 got the best result with a mutation chance of 0.03, 20 worked best with 0.01 and when the population was 50 a mutation chance of 0 was the best.</p><h3>Convergence</h3><p>That’s it for this week! We’ve covered mutation and finished our implementation of a GA. The full code for the GA is on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>We’re going to be taking a break for a little while on Code of AI, while I do some genetic evolution of my own (I’m having a baby). So be sure to subscribe to our mailing list <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a> or give us a <a href="https://twitter.com/melodrivemusic">follow</a> to stay up to date and receive updates on our latest posts. Please feel free to send us some feedback on what you might like to learn when Code of AI returns later this year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3681fca42189" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/enter-the-mutant-genetic-algorithms-part-iii-3681fca42189">Enter the Mutant: Genetic algorithms, part III</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selection, Crossover, I choose you! Genetic algorithms, part II]]></title>
            <link>https://medium.com/the-sound-of-ai/selection-crossover-i-choose-you-genetic-algorithms-part-ii-5ff620c10029?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ff620c10029</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[evolution]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 14:01:45 GMT</pubDate>
            <atom:updated>2019-06-05T14:01:45.520Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back, phenotypes! <a href="https://medium.com/the-sound-of-ai/intelligence-is-in-my-genes-genetic-algorithms-part-i-59fed978c118">Last time</a> we introduced Genetic Algorithms (GAs), an AI method for searching complex spaces, inspired by natural selection. I’d recommend you review that article before you get started on this one, as we’re picking up where we left off. This week we’re going to dig into the evolution process behind GAs and learn how to use a fitness function to evolve fitter solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*KtaTmpan2FNm8Q7X" /><figcaption><em>Everything I know about evolution I learned from Pokémon.</em></figcaption></figure><h3>The fitness function</h3><p>As any Pokémon trainer knows, you need to build your Pokémon’s experience to make them evolve and become stronger. In GA terms, a Pokémon’s experience in battle would be known as its <strong>fitness</strong>. More generally, we can measure the fitness of any chromosome with a problem-specific <strong>fitness function</strong>. For instance, here’s my fitness function for the knapsack problem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d62b4b5417705180d302a796bd3e7b25/href">https://medium.com/media/d62b4b5417705180d302a796bd3e7b25/href</a></iframe><p>We first create a phenotype solution out of the chromosome, and then calculate the fitness based on weight and value. The more value we have in the knapsack, the higher the fitness.</p><h3>The evolutionary process</h3><p>Natural evolution is a process that happens among a <strong>population</strong> of entities. If you really want to be the very best, one Pokémon in your roster just won’t cut it — you need a team of Pokémon, each with their own unique abilities. In a GA, having a number of chromosome candidates to search your space will lead to a better result, faster. In the below function, we create a population of chromosomes by simply making a list of lists:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1fce1e40b2c1f947ae575e0df2c7a52/href">https://medium.com/media/a1fce1e40b2c1f947ae575e0df2c7a52/href</a></iframe><p>Only the fittest members of this population will be able to survive to the next generation. This is known as <strong>selection</strong>. First, the entire population is ranked by its fitness scores, and then a certain ratio (50% in this example) of the population are selected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5a134b71ac0a2e0552486b706043ddf/href">https://medium.com/media/f5a134b71ac0a2e0552486b706043ddf/href</a></iframe><p>One part of evolution that Pokémon conveniently leaves out is exactly how genes are passed down from one generation to the next (NSFW: when a mummy and a daddy Pikachu love each other very much…). In GAs, we simplify the act of creating ‘children’ down to mixing genes, in a process known as <strong>crossover</strong>. We take two parents and create a child by mixing the chromosomes together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/898e650e918f9de746502c488f526851/href">https://medium.com/media/898e650e918f9de746502c488f526851/href</a></iframe><p>This is one of the main search operations in a GA (there’s another one, but we’ll cover it next time). The intuition behind this is that by mixing chromosomes together, we can explore the search space in directions we already know work well.</p><p>Finally, the resulting children from the crossover process are added back into the population, replacing the rejected chromosomes, and the process continues. The loop of selection and crossover is then repeated for multiple <strong>generations</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f09990bbf3c291486b804b52ae3c968a/href">https://medium.com/media/f09990bbf3c291486b804b52ae3c968a/href</a></iframe><p>If you run all the above code snippets (also available as a single script on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>), you should notice fitness improving over time.</p><h3>Next generation</h3><p>That’s it for this week! We’ve covered the process of a GA’s evolution from population, to fitness, selection and crossover. I have a couple of challenges for you that won’t endanger your survival:</p><ol><li>What happens when you increase the number of generations in the example code (to e.g. 20)? Why do you think this happens?</li><li>Compare the execution time and results of the previous week’s brute force approach and this week’s GA approach. Run them each a few times, changing the number of items. What do you notice about:</li></ol><ul><li>The discovered solutions?</li><li>The execution time?</li></ul><p>As always, you can find the source code for all the above examples on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>To begin your AI-coding training at day one, go <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>. And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ff620c10029" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/selection-crossover-i-choose-you-genetic-algorithms-part-ii-5ff620c10029">Selection, Crossover, I choose you! Genetic algorithms, part II</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intelligence is in my genes: Genetic algorithms, part I]]></title>
            <link>https://medium.com/the-sound-of-ai/intelligence-is-in-my-genes-genetic-algorithms-part-i-59fed978c118?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/59fed978c118</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Fri, 24 May 2019 12:57:29 GMT</pubDate>
            <atom:updated>2019-05-24T12:57:29.513Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello again, cross-validators. For the <a href="https://medium.com/the-sound-of-ai/thinking-artificially-artificial-neural-networks-part-i-fb0ea78a9f6">last</a> <a href="https://medium.com/the-sound-of-ai/training-to-train-artificial-neural-networks-part-ii-b1b4efd944be">few</a> <a href="https://medium.com/the-sound-of-ai/jumping-into-hyperparameters-5b72dfa0c29">weeks</a> we’ve been discussing Artificial Neural Networks (ANNs) and how to train them. People often conflate the more general idea of AI with the more specific terms ‘machine learning’ or ‘deep learning’. It’s important to realise the differences and limitations of any AI model, so that you know what they’re capable of and where to effectively apply them. With that in mind, this week we’ll move on to a new kind of AI algorithm: Genetic Algorithms (GAs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LzbRNBIIaqceTvJ" /><figcaption><em>The internet: a sophisticated cat-sharing technology.</em></figcaption></figure><h3>Searching for… something?</h3><p>GAs fall into the <strong>search </strong>or <strong>optimisation </strong>categories of AI, where, generally speaking, ANNs can’t be used. Sure, they can be used as part of a search solution (classifying web pages based on their content, for instance). But the <strong>process</strong> of conducting a search or optimising a set of parameters is not one that lends itself well to the architecture of an ANN.</p><p>This is because ANNs are essentially statistically-driven input-output mapping machines. Put in an image and the ANN can tell you if it’s a cat or not (most likely yes if you found the picture on the internet). But try to ask an ANN to find a cat on the internet and you get stuck. What are the inputs/outputs? How will you train it? This problem becomes worse when the problem is so ill-defined that you’re not exactly sure of what you’re looking for (finding that perfect cat gif for your team’s #random channel on Slack), or when the number of options to search through grows unreasonably high (my Google search for ‘cat’ just returned 7.5 billion results, which is more than the population of the planet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TApjqyHyulG6gHxM" /><figcaption><em>There’s one less cat on the internet. RIP Grumpy Cat. Image: </em><a href="https://www.nytimes.com/2019/05/17/business/media/grumpy-cat-dead.html"><em>NYT</em></a></figcaption></figure><h3>The knapsack problem</h3><p>Now the cat’s out of the bag, let’s illustrate the issue with a classic example of a search/optimisation problem: the knapsack problem.</p><p>The knapsack problem goes like this: imagine you’re a travelling salesperson who carries all of your wares in your trusty knapsack. Naturally, you want to make sure that you make the most money you can that day by taking your most valuable goods on your round. But you have a problem — you can only carry so much or your bag will break! Every morning, you need to find the <strong>best combination of items</strong> to put in your bag that will <strong>maximise the value</strong> you carry, but not go over the bag’s <strong>capacity </strong>so it breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b13Mnn0qZMm2lInd" /><figcaption><em>The knapsack problem is a classic search/optimisation problem that can’t be solved with ANNs. Image: </em><a href="https://en.wikipedia.org/wiki/Knapsack_problem"><em>Wikipedia</em></a><em>.</em></figcaption></figure><p>Let’s begin tackling this problem by revising a couple of AI search terms we covered <a href="https://medium.com/the-sound-of-ai/hello-search-1103c4f126ad">way back at the start</a> of this Code of AI series:</p><ul><li><strong>Search space</strong> — abstract parameters constraining a search.</li><li><strong>States</strong> — positions or sets of conditions in a space.</li><li><strong>Goal state</strong> — a desirable outcome, or solution.</li></ul><p>The <strong>search space</strong> in the knapsack problem is every possible combination of items to put in the bag. Each item has an associated <strong>value </strong>and <strong>weight</strong>, and the bag itself has a maximum <strong>capacity</strong>. A single <strong>state</strong> is one of those combinations of items in the bag, and the <strong>goal state</strong> is the one single combination that maximises value without going over the bag’s capacity.</p><h3>A brute force solution</h3><p>The knapsack is quite a simple problem to solve with a brute force method. In this code snippet we iterate through all the possible combinations of the items in the bag and test each one for its value and weight.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb808b7685551eefa292a9fa6c727552/href">https://medium.com/media/eb808b7685551eefa292a9fa6c727552/href</a></iframe><p>Running this code shows that we do indeed find a solution, and for the 10 items in this example we find the solution quite quickly. But what happens if there are more items to search through? With 10 items we only need to search through around 1000 combinations, and it takes about 7ms on my machine. But with 20 items the number of combinations grows to around 1,000,000 and takes 2.5 seconds. Just five more (25) items makes around 33 million combinations and takes around 2 minutes to search. This trend shows that the knapsack problem has exponential (<em>O(2^n)</em>) complexity, which means that it quickly becomes impractical for larger values of n.</p><h3>GAs: a different kind of search</h3><p>Let’s think of a better way to search the vast space of the knapsack problem. The problem we’re facing lies in the exponential rise in the number of combinations when we increase the number of items. What if, instead of searching through every possible combination of items in the bag, we have a <strong>fixed number of states</strong>, <strong>evaluate their value</strong>, and then <strong>change them</strong> in some way to<strong> explore the search space</strong>.</p><p>This is exactly the intuition behind a GA. Inspired by natural evolution — the process by which a simple organism becomes more complex and better adapted to their environment over time through natural selection — GAs evaluate a set of states (a <strong>population </strong>in GA terms) for their <strong>fitness </strong>and <strong>evolve</strong> the best solutions (“fittest”) in the next generation. Eventually, the overall fitness of the population will rise and a best-fit solution to the problem will be found.</p><p>We’ll get more into the mechanics of the GA search process next time. For now, let’s focus on a few fundamental concepts in GAs, all of which are inspired by natural evolution: <strong>genes</strong>, <strong>chromosomes, phenotypes </strong>and <strong>fitness functions</strong>.</p><p>You can think of a <strong>phenotype</strong> as analogous to a search state in general AI terms. In biology, you are a living phenotype, and your genes define how you appear. If you have the brown-eyed gene then your phenotypic eyes will be brown too. Similarly in a GA, a <strong>gene </strong>is an abstract parameter that encodes one aspect of the phenotype. A <strong>chromosome </strong>is the collection of genes that together fully represent the phenotype in an abstract way. Finally, the <strong>fitness function</strong> is an application-specific evaluation method that creates a phenotype from a chromosome and computes how good the solution is.</p><h3>The knapsack as a chromosome</h3><p>In our knapsack example we’ve already said that a single search state — a phenotype — is one possible combination of items in the bag. Encoding this into a chromosome is as simple as creating a <strong>binary list</strong> where the length is the number of possible items to put in the bag. If a single gene takes a value of one, it’s included in the bag.</p><p>To illustrate this, here’s some example code that creates a random chromosome and converts it into a phenotype.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bd38853f93593c9cae944d237db95b2/href">https://medium.com/media/3bd38853f93593c9cae944d237db95b2/href</a></iframe><h3>It’s in the bag</h3><p>That’s where we’ll leave it for this week. We’ve covered some of the limitations of machine learning and ANNs, and the need for a wider perspective on some AI problems. We also introduced genetic algorithms as an alternative way to search a complex space, and some fundamental concepts in GAs, <strong>genes</strong>, <strong>chromosomes, phenotypes </strong>and <strong>fitness functions</strong>.</p><p>I’ve provided some code for a knapsack problem chromosome. If you’re up for a challenge, can you take some code from the bruteForceKnapsack function (above), and create a fitness function to evaluate a single chromosome?</p><p>As always, you can find the source code for all the above examples on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>To begin your AI-coding training at day one, go <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>. And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59fed978c118" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/intelligence-is-in-my-genes-genetic-algorithms-part-i-59fed978c118">Intelligence is in my genes: Genetic algorithms, part I</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’re fit and you know it: overfitting and cross-validation]]></title>
            <link>https://medium.com/the-sound-of-ai/youre-fit-and-you-know-it-overfitting-and-cross-validation-90a3a9f67c74?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a3a9f67c74</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Thu, 02 May 2019 14:31:00 GMT</pubDate>
            <atom:updated>2019-05-02T15:00:59.043Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back machine-learners. Last time we finished off our brief tour of Artificial Neural Networks (ANNs) with a look into their hyperparameters. As part of that investigation, I advised you to always train multiple models before you stick with a hyperparameter choice. This week we’ll dig a bit further into this idea by exploring one of the most common pitfalls of machine learning — overfitting — and how to discover ways to be sure that you’re model is fit with cross-validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wKN2QERrWGjji0Ku" /><figcaption>Clever Hans was able to perform basic maths, or was he?</figcaption></figure><h3>Clever Hans — a machine learning fable</h3><p>Before we dig in to some theory, here’s a true story about a horse named ‘Clever Hans’. As his name suggests, Hans wasn’t like other horses. His owner Wilhelm soon discovered that he could be trained to read basic equations on a chalkboard and tap the correct answer with his foot. This amazed Wilhelm, who promptly showed off Hans all across Germany. However, it was soon discovered that, unbeknown to Wilhelm, Hans only appeared clever, and couldn’t really do maths. Hans’ cleverness hinged on his ability to have an up-close, unobstructed view of the person who knew the correct answer. Take that away, and his accuracy plummeted to zero. Hans was just very good at reading people’s body language, which indicated to him to stop tapping his foot.</p><p>So, what does this tell us about machine learning? Just like Hans’ owner Wilhelm, as model trainers <strong>we can’t always be sure of exactly what our model has learned</strong> from the data. The model may appear to perform superbly in training, but then makes terrible predictions about unseen data in a production environment. This is currently a hot topic within the machine learning community (I even attended <a href="http://c4dm.eecs.qmul.ac.uk/horse2017/">an academic conference</a> on the subject). If you’d like to find out more you can check out <a href="https://ieeexplore.ieee.org/document/6847693?tp=&amp;arnumber=6847693">this paper</a>.</p><h3>How to be ‘too’ fit</h3><p>Let’s take the following example. Here we have a dataset containing two classes represented by red crosses and blue circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*BJDjXYeJhVmSRo_1" /></figure><p>We’d like to train a model that can classify the data into the two classes. After training you might be chuffed to find out that the model scores 100% accuracy on this dataset. But when you feed it some new data, the accuracy might drop completely — a classic sign of overfitting.</p><p>The classification boundary our model is using might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*cmTz7JyBm_vWwFQ1" /></figure><p>Here you might already be able to see the problem. The 100% training score is achieved because the model has <strong>tightly fit</strong> a boundary line, but does not appear to have discovered the <strong>general trend</strong> in the data. A better generalised model might draw the line more like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*9VhikLv6L_H7L6j0" /></figure><p>Sure, the <strong>training accuracy</strong> of this model will be lower (we have two mistakes in blue and four mistakes in red), but the model has discovered a <strong>general pattern</strong> that will ensure better accuracy on new data.</p><h3>Cross-validation to the rescue</h3><p>To summarise, we need to keep two things in mind when evaluating our trained model. The error on the training set will only give us part of the story. Only through evaluating on a different set of ‘unseen’ data are we able to say that the model is performing well. This is what cross-validation sets out to achieve.</p><p>In cross-validation, the dataset is split into chunks. A certain proportion — let’s say 80% — is used for training the model as usual. The remaining data (20%) is not used for backpropagation, but instead is used to keep track of a <strong>test error</strong>. When this error stops improving (or in most cases, gets worse), it’s a sure sign that we’re overfitting — so we can stop training at that point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*GQHdKuWRgMuIRNFr" /><figcaption><em>An example of cross-validation in action. The model is overfit after 6 epochs.</em></figcaption></figure><p>Let’s see what that looks like in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb65a14e242694999416e600de1ccd1c/href">https://medium.com/media/cb65a14e242694999416e600de1ccd1c/href</a></iframe><h3>Fitter, happier, more productive</h3><p>That’s it for this week. We’ve covered the concept of overfitting and how to avoid it with cross-validation.</p><p>The cross-validation implementation I’ve introduced in this post is a very basic one — it’s far more common to train multiple models (usually up to ten) with a different chunk of test data each time. This is known as <strong>k-fold cross-validation</strong>. You can try extending the above example into a k-fold cross validator if you’re up for it.</p><p>As always, you can find the source code for all the above examples on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>To begin your AI-coding training at day one, go <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>. And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a3a9f67c74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/youre-fit-and-you-know-it-overfitting-and-cross-validation-90a3a9f67c74">You’re fit and you know it: overfitting and cross-validation</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to increase user immersion with (mostly) audio]]></title>
            <link>https://medium.com/the-sound-of-ai/how-to-increase-user-immersion-with-mostly-audio-2c7ba6f8777b?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c7ba6f8777b</guid>
            <category><![CDATA[sound]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[gaming]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Thu, 25 Apr 2019 13:23:41 GMT</pubDate>
            <atom:updated>2019-04-25T13:23:41.348Z</atom:updated>
            <content:encoded><![CDATA[<p>A truly authentic, engaging virtual reality (VR) experience hinges on ‘immersion’ and ‘immersion multipliers’. These are highly valued by players and developers alike, but what do they really mean? What exactly is immersion and why is it seen as the holy grail for VR? Let’s explore what makes someone feel immersed, and tap into some quick strategies you can use to radically increase the immersion of your VR experiences — by only thinking about audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*Q4DWOUDt92nYRIw6" /><figcaption><em>Handling sound correctly in VR can massively improve immersion (image: </em><a href="http://www.shutterstock.com/de/pic-423066913/stock-vector-omg-emotions-from-virtual-reality-retro-girl.html?src=UC0SlEC2KQawz-7E1izeLA-2-106"><em>Shutterstock</em></a><em>)</em></figcaption></figure><h3>What is immersion?</h3><p>Immersion is a state of mind. It’s what happens when you lose the sense of your physical self in an artificial simulation, experience, or fiction, so the simulation appears real and you momentarily forget about the ‘real’ word. The focus of your consciousnesses shifts from the ‘real’ world to the artificial one presented to you. It doesn’t only happen in VR, but it might happen when reading a book or watching a film, or even (for me) when performing a difficult cognitive task, like writing some code. Put another way, in a state of immersion your senses of <em>presence</em> and <em>attention</em> shift into the virtual world, and the more you believe the world you’re in, the more your brain convinces you that what you’re seeing is real.</p><p>When it comes down to it, it’s hard to specifically define <em>exactly</em> what causes immersion. If you’re scientifically inclined like me, you’ll look to the existing body of research in the area. You’ll then find that there’s a substantial amount of research out there, but no real consensus on the specific components that lead to an immersive experience. And when even the academics can’t agree, you know you’re on shaky ground.</p><p>Staffan Björk and Jussi Holopainen’s four categories of immersion, as defined in their excellent book <a href="https://www.amazon.com/Patterns-Game-Design-Development/dp/1584503548">Patterns In Game Design</a>, seems like an appropriate point of departure. It’s not exhaustive, but it’s still a practical way to think about immersion specifically in games and VR.</p><p>Björk and Holopainen’s categories are:</p><h4><strong>Sensory-motoric immersion</strong></h4><p>This occurs when you perform actions with your hands or limbs and get feedback through all of your senses — sight, sound and touch — and even smell and taste!</p><h4><strong>Spatial immersion</strong></h4><p>When the simulated world is perceptually convincing, you are said to feel spatially immersed, which directly affects your sense of presence. There are subtle nuances to this, including the scale and environmental cues of the world (such as sound).</p><h4><strong>Cognitive immersion</strong></h4><p>This occurs when you’re focused on a specific task that requires mental exercise — it’s perhaps the most common form of immersion, as most people experience it when learning something new.</p><h4><strong>Emotional immersion</strong></h4><p>This is another common immersive state, often induced when you watch a film or read an engrossing book. It occurs when players become emotionally invested in the experience.</p><h3>Why is immersion so important for VR?</h3><p>Many people think that the act of simply having content in VR guarantees a magical boost in ‘immersion’, but this is only true to a certain extent. While it’s definitely easier to achieve a state of immersion in VR, immersion itself is actually a fickle beast that’s difficult to maintain for a longer period of time.</p><p>During a VR experience, your senses are bombarded with an overwhelming variety of conflicting information. Usually, players will have most of their senses covered; their eyes enclosed by the headset, their ears in some kind of headphones, and their hands holding one or more controllers. Some companies <a href="http://www.rotovr.com/">add more bells and whistles to this setup</a>, but that’s beyond the typical VR rig.</p><p>Even with this default sensory-motoric immersion, if something happens in the ‘real’ world, or the simulated experience conflicts with your senses, then the level of immersion can come crashing down — often with nasty side-effects such as disorientation, confusion and motion sickness. Not the virtual roller-coaster ride you signed up for.</p><p>As VR developers we can’t fully control the external rigs and environment our players use, so instead we rely on in-experience tricks to playfully coax the user into a deeper sense of immersion. The more immersed a user, the more engaged they’ll feel, and the less likely they are to experience cognitive dissonance between the real and simulated worlds.</p><p>Ultimately though, if the experience is deeply immersive, your players will feel happier and find themselves continuously returning to satisfy that need for ‘“just a bit more”. This continued demand is essential to increasing the widespread adoption of VR.</p><h3>How to increase user immersion with (mostly) audio</h3><p>As an audiophile, it seems sensible for me to focus on ways to increase the feeling of immersion with only audio techniques. I often feel that audio generally doesn’t receive the attention it deserves, probably because, like the best film soundtracks, if the audio is working well it <em>shouldn’t</em> be noticeable.</p><p>Well-implemented audio seamlessly blends into the experience and feels like the real thing. But when this goes wrong it, it’s horrifyingly bizarre — something happens in your brain that most people can’t put their fingers on, they just know it feels ‘wrong’. To avoid this uncomfortable disconnect, a few simple things can be implemented.</p><h3>Use spatial audio for diegetic sounds…</h3><p>Diegetic sound is a term stemming from film — it basically means the sounds made by real-world objects, characters, environments etc. When you hear sound in the real world, your brain is doing a lot of complicated stuff to figure out the direction and distance of the sound When this ability is taken away it creates an extremely disorienting effect. Most people won’t be able to pinpoint what’s wrong — the world will just feel odd and fake. This problem boils down to a lack of <strong>spatial immersion. </strong>However, by using spatial audio techniques you can eliminate this for your players.</p><p>Consider film once again. Lack of spatial immersion was also a problem for film-goers, which was the reason for the invention of surround sound. Even with a huge screen in a dark room, hearing audio out of two fixed speakers was a sure-fire way to remove yourself from the experience. The inventors of surround sound placed more speakers around the audience, so that sound actually plays behind you if a character is out of shot. This problem exists in VR, except we can’t just add more speakers to the headset… or can we?!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jxM76zBJkbq-0W2g" /><figcaption><em>This is one way to do VR surround sound, but it might be a bit heavy to pull off. (image: </em><a href="http://mikekimindustrialdesign.com/Audionauts-Hi-Fi-Marketing-Campaign"><em>Mike Kim</em></a><em>)</em></figcaption></figure><p>You don’t need a sci-fi-looking piece of technology from an advanced civilisation to solve this problem. Spatial audio is a tech that’s been around for quite some time in games, and is really taking on a life of its own in VR titles. With spatial audio, sound sources can be placed into the 3D world, and the engine figures out how to manipulate these sounds so they sound like they’re coming from that spot, even through a stereo mix. If you have ambient sound effects in-game, you should definitely spatialise them for their full effect.</p><h3>…and ambisonic audio for non-diegetic sounds</h3><p>Spatial audio is great for diegetic sounds that are visible on the screen, such as a babbling brook or a gunshot, but when it comes to non-diegetic sounds — like the game’s soundtrack — we run into another issue. It’s often undesirable to have the music coming out of fixed points in the 3D world; instead, the player should feel enveloped by the music. However, if the music mix is fixed (e.g., the guitar is always in front of you, no matter where you turn), then this can cause feelings of discomfort that lead to a break in <strong>sensory-motoric immersion</strong>.</p><p>To tackle this, we can use ambisonic audio. This is where we have a set of points around the listener in 3D space, that are relative to the listener rather than in absolute positions. The 3D points move <strong>with </strong>the listener, but changes in the mix can be heard when the player turns around or moves their head. This simulates the experience of being in a real-life environment, almost as if you were at a real-life concert standing in the center of an orchestra. Bravo!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z7IBJUctvn8Umotc" /><figcaption><em>Placing sound sources in ambisonic space (image: </em><a href="http://vr.amp.amsterdam/"><em>Amp Audio</em></a><em>)</em></figcaption></figure><h3>Ease the learning curve with UI audio</h3><p>One of the most painful, immersion-destroying experiences in VR for players is learning a complicated control scheme. Most players will struggle with pressing more than one button at once, especially if it’s an unnatural gesture. This is an area where VR actually shoots itself in the foot a little bit. Since players can’t see their hands, it’s even harder to learn the new controls.</p><p>The control scheme obviously affects<strong> sensory-motoric immersion</strong>, but also has a strong effect on <strong>cognitive immersion</strong>. Somewhat counter-intuitively, hard-to-learn controls don’t lead to cognitive immersion, but actually hinder it. This is because, in order to feel cognitively immersed, you also need to feel in control of your own actions and therefore get less frustrated!</p><p>But don’t fret, the answer once again lies in the audio. Having simple audio cues that respond to the user’s actions is a method of positive-reinforcement. It aids cognitive immersion, reducing the frustrations of not knowing if you’re even doing the right thing or pressing the right buttons.</p><p>An excellent example of well-executed UI audio in VR is Funomena’s <a href="http://www.funomena.com/"><em>Luna</em></a>. A very simple control scheme, coupled with a few effective gong sounds providing audio feedback, eases the player into the controls, so they feel more engaged from the outset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kJzpsA0BhA0MWsHI" /><figcaption><em>Luna: a fantastic example of UI audio in VR (image: </em><a href="https://www.wired.com/story/robin-hunicke-vr-game-luna/"><em>Wired</em></a><em>)</em></figcaption></figure><h3>Use (deep) adaptive music for your soundtrack</h3><p>We all know that music is amazingly powerful at conveying emotions, which you’ve no doubt noticed in the real world everywhere you turn. When was the last time you watched an advert on TV with no music, for instance? In VR, though players have their own agency and behaviours — they can choose where to go and how to act. This means that if we want to increase their <strong>emotional immersion</strong>, we need to dynamically respond to what they do with the music. This is called adaptive music, and is fundamental to interactive media.</p><p>The work I do has focused on developing a new way to score interactive media by deepening the adaptive music experience with the help of AI. <a href="https://medium.com/the-sound-of-ai/30-more-immersion-in-vr-an-adaptive-music-experiment-735b3e3614be">In our research</a> we’ve found that adaptive music can boost immersion by 30%, most likely due to the increased emotional immersion.</p><h3>Sound off</h3><p>So, there are some textbook suggestions for how to improve immersion in VR. Next time you hear the phrase “immersion multiplier”, try to ask yourself which one of the four categories it addresses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c7ba6f8777b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/how-to-increase-user-immersion-with-mostly-audio-2c7ba6f8777b">How to increase user immersion with (mostly) audio</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jumping into hyperparameters]]></title>
            <link>https://medium.com/the-sound-of-ai/jumping-into-hyperparameters-5b72dfa0c29?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b72dfa0c29</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Thu, 18 Apr 2019 14:31:00 GMT</pubDate>
            <atom:updated>2019-04-22T08:08:12.914Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back, gradient descenders! <a href="https://medium.com/the-sound-of-ai/training-to-train-artificial-neural-networks-part-ii-b1b4efd944be?source=friends_link&amp;sk=374bda84b7abd5826079dd164c68ad61">Last time</a> we introduced the backpropagation algorithm to train our neural networks. I strongly encourage you to read that post if you haven’t already, as this week we’ll pick up straight where we left off — by exploring probably the most sci-fi sounding aspect of machine learning: hyperparameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PqIbg8DGAbLAIkm5" /><figcaption><em>Hyperparameters: almost as exciting as hyperspace?</em></figcaption></figure><p>A quick side note before we begin: from this week forward we’ll be publishing a new Code of AI post every two weeks instead of every week. This will hopefully give me enough time to deeply address some more complex concepts and models, and also give you enough time to digest them.</p><h3>What are hyperparameters?</h3><p>We left off last week with an exploration challenge — I asked you to tweak various parameters of our neural network and its training: the network size, the amount of training data and the learning rate. These parameters (and others) are generally referred to as <strong>hyperparameters</strong>. But what does that mean exactly, and what’s the difference between a hyperparameter and a normal parameter?</p><p>To understand this, let’s remember what we said in the last post about what we mean when we say that our machine learning model is <em>learning.</em> This is a process of <strong>optimising </strong>a model by adjusting<strong> </strong>it’s <strong>parameters</strong> to <strong>minimise the error</strong>. With an ANN, the model is a bunch of neurons and connections, and the parameters are the connection weights. The weights are a set of parameters that are <em>internal</em> to the model. We don’t directly set them from the outside, and their value is set by the training algorithm. These are called <strong>model parameters</strong>.</p><p>Hyperparameters are parameters that we do have ‘control’ over as machine learning programmers. Depending on the model you’re using, you’ll have a number of different hyperparameters to tweak — but for an MLP, you only really have the abovementioned ones to play with.</p><p>Let’s now explore how these hyperparameters work together. For each one we’ll l train ten different networks and use the average error as an indication of which one performed best. “Why train ten different networks?”, I hear you ask. Well, since each MLP is initialised with random weights, sometimes the network will take longer to find an optimal solution or, in some cases, never find a good solution at all. Running the training multiple times reduces the chance of this happening. (This idea is similar to a concept known as cross-validation which we’ll cover in a later Code of AI post.) For now, remember this: <strong>always train multiple models before you stick with a hyperparameter choice</strong>.</p><h3>Network size</h3><p>The network size — the number of hidden layers and how many neurons there are in each layer — is a perfect example of a hyperparameter which has a direct impact on the model parameters. If a multilayer perceptron has one input, one output and one hidden layer with three nodes, we know that the network has six (1x3 + 3x1) trainable weights. However, if we add a second hidden layer of three neurons, we know that the network has 15 (1x3 + 3x3 + 3x1) trainable weights. As you add more nodes and more layers, the number of parameters can grow faster than you might expect!</p><p>In this next code snippet we’ll explore a number of different network sizes and report the error for each size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06e45a911db8b212cda9d2fdf1f9e1a5/href">https://medium.com/media/06e45a911db8b212cda9d2fdf1f9e1a5/href</a></iframe><p>The results will look something like this. The first number refers to the hidden layers; the second is the number of model parameters and the last number is the average error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/485a94f93deb5a7a66c653c7b2470850/href">https://medium.com/media/485a94f93deb5a7a66c653c7b2470850/href</a></iframe><p>As you can see, for our toy dataset the network size doesn’t really make too much of a difference. Although there <em>is </em>an important lesson here: <strong>sometimes a simpler architecture is better</strong>. Or, to put it another way, you should optimise the size of your network to be the smallest network possible that achieves your goal. You can see this in the final example, where the error is actually bigger for the largest network. Adding more layers and nodes increases the complexity of the network, which not only makes it more difficult to train, but also increases the RAM and CPU requirements for the model. Is one more layer really worth that 0.001 improvement? You be the judge — but only if you’re 99.999% sure.</p><h3>Amount of training data</h3><p>One of the easiest ways to play with a hyperparameter is to control the amount of data that is fed into the model during training. Simple problems like the often-used XOR function have complete datasets of every possible input and output pair, but most of the time this isn’t feasible. Instead, we have to work with a sample of data and hope that the ML model will generalise well after training.</p><p>The next snippet of code explores a range of dataset sizes and shows the results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d087bd3cafa847df18e06fc06fed54f/href">https://medium.com/media/8d087bd3cafa847df18e06fc06fed54f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ecdfb3c06210b617f020ec36dad98b2/href">https://medium.com/media/2ecdfb3c06210b617f020ec36dad98b2/href</a></iframe><p>Even in this simple example, the trend is clear: <strong>more data = better results</strong>. I’ve lost count of the amount of times I’ve told a client, “We need more data”, or read in a research paper’s conclusion that “collecting more data may yield better results” (I think I’m guilty of that one myself).</p><p>Adding more data helps the model learn in two ways. First, it avoids the problem of <strong>overfitting</strong>, which is where the model doesn’t generalise well to new inputs — we’ll talk more about overfitting in the next Code of AI post. Secondly, it helps the model learn by giving it more backpropagation runs to do in one epoch. This means that the more data you add, the more training time you’re giving the model.</p><h3>Learning rate</h3><p>The learning rate is the one and only hyperparameter for our implementation of backpropagation gradient descent. There are more complex gradient descent trainers and optimisers available that have more parameters to play with, but learning rate is a simple input that controls how much to follow the gradient and adjust the weights when learning. The general rule of thumb is that bigger learning rates will learn faster, but may step over the optimal points, whereas lower learning rates will learn more slowly but may get stuck in <em>local optima</em>.</p><p>ML guru Andrew Ng has a great rule of thumb for how to go about optimising hyperparameters such as learning rate, called <em>the rule of 3</em>. Essentially, you pick a number to start with (usually 1 or 0.1 for learning rate) and then try multiplying it or dividing it by three, rounding where it makes sense, until you find the optimum. This is the approach we’ve taken in the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86e052f53e6bbe42a121b9298821f83b/href">https://medium.com/media/86e052f53e6bbe42a121b9298821f83b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e842a3c0b5483987654dbf8441b2687/href">https://medium.com/media/1e842a3c0b5483987654dbf8441b2687/href</a></iframe><p>The learning rate is an interesting hyperparameter to explore because it can greatly affect your model’s performance. Here we can see that the optimal learning rate seems to be around 0.3, but will depend strongly on the network size and complexity of the problem. Now, if only there was a learning rate hyperparameter for human brains…</p><h3>Hyperparameters optimised</h3><p>That’s where we’ll leave it for this week. We’ve introduced the concept of <strong>hyperparameters</strong>, and explored three hyperparameters associated with our MLPs and gradient descent training.</p><p>Next week, we’ll finally be able to train a model on some real-world data. We’ll also discuss some of the perils of overfitting and how to mitigate that with cross-validation.</p><p>As always, you can find the source code for all the above examples on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>To begin your AI-coding training at day one, go <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>. And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b72dfa0c29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/jumping-into-hyperparameters-5b72dfa0c29">Jumping into hyperparameters</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training to train: Artificial Neural Networks, part II]]></title>
            <link>https://medium.com/the-sound-of-ai/training-to-train-artificial-neural-networks-part-ii-b1b4efd944be?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1b4efd944be</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Wed, 03 Apr 2019 13:27:43 GMT</pubDate>
            <atom:updated>2019-04-03T13:27:43.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back, networks-in-training! <a href="https://medium.com/the-sound-of-ai/thinking-artificially-artificial-neural-networks-part-i-fb0ea78a9f6">Last week</a> we introduced the Multilayer Perceptron (MLP) — our first Artificial Neural Network (ANN). We built a fairly strict implementation (it had one fixed hidden layer), and I challenged you to make it more flexible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCFRzEyX7eWKkUSP9ddNNg.jpeg" /><figcaption>Training an ANN with gradient descent is like trying to find the quickest path down a mountain.</figcaption></figure><p>While there are lots of ways this could have been done, here’s my solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca4dab0d0d4da6e4889f5d41aca8e87/href">https://medium.com/media/6ca4dab0d0d4da6e4889f5d41aca8e87/href</a></iframe><p>This new solution makes it easier to experiment with our network’s <strong>architecture </strong>(the number of inputs, outputs, hidden layers and their sizes) to see what works best for the problem we’re trying to solve. We can also create a oh-so-popular <strong>deep network</strong>, by inputting large numbers like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a46ac7984c9d69ec646ed0f67da3ef30/href">https://medium.com/media/a46ac7984c9d69ec646ed0f67da3ef30/href</a></iframe><p>This code would create an MLP instance with one input, five hidden layers — each with 1024 neurons — and one output.</p><h3>Apropos propagation</h3><p>Part of the elegance of ANNs lies in the fact that each layer of the network is “activated” sequentially. This can be seen in the ‘activate’ method above — data is flowing through the network in a simple for-loop, and the output from the previous layer is used as the input to the next. This is known as <strong>forward propagation</strong>. Here’s where things get really interesting — the network can <strong>learn</strong> from it’s mistakes by running in reverse, which is known as <strong>backwards propagation </strong>or <strong>backpropagation</strong>.</p><p>This isn’t a matter of just running the network in reverse, though. While forward propagation propagates the <strong>input </strong>value(s) from left to right, backpropagation propagates the <strong>error </strong>value(s) from right to left. For backpropagation to work, we need to calculate the error (a.k.a. cost or loss) by comparing the <em>actual</em> output with the <em>desired</em> output. This calculated error is what is back propagated to the previous layer(s), from right to left. The connection weights of each node are then adjusted by changing the weights to reduce the prediction error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*jR_z3MlOEqPThvNH" /><figcaption>An ANN showing the propagation of input and error.</figcaption></figure><h3>Training ANNs with supervised learning</h3><p>For an ANN to learn with backpropagation, we need a dataset of training examples. Each example needs to be made up of the input data and the desired output for that input.</p><p>Training an ANN is an iterative process in which training data examples are presented to the network one by one, and the values of the weights are adjusted each time. After all examples get run through the network, one <strong>training epoch</strong> is finished and the process often starts again. During this phase, the ANN learns to predict the correct output, given the input examples, and, hopefully, is able to generalise the prediction to other data similar to the input examples. This is known as <strong>supervised learning</strong> (SL).</p><p>During the training phase, we pass a training example to the network and then compare the network’s calculated values of the output node(s) against the ‘correct’ values. Then, we calculate an error value. This error can then be backpropagated, and the connecting weights in the hidden layers can be adjusted, with the hope that the output values calculated next time will be closer to the correct values.</p><h3>The mechanics of backpropagation</h3><p>Enough theory — let’s get back to the code!</p><p>The first thing we need is an error function, since we need to keep track of the network’s performance. There are a lot of error functions to choose from, but for now we’ll stick to the commonly used <strong>mean squared error</strong>. With numpy, the implementation is pretty straight forward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81d4fa4bbc3ab009d5e2dbef39bd7320/href">https://medium.com/media/81d4fa4bbc3ab009d5e2dbef39bd7320/href</a></iframe><p>When we say that the network is learning, what we really mean is that we’re minimising this error in the network with a <strong>gradient descent algorithm</strong>. Understanding gradient descent is a little complex to explain mathematically — but essentially it’s a way we can iteratively tweak the weights in the network to reduce the error. If you’re interested in learning more about the maths behind how this works, check out <a href="https://www.youtube.com/watch?v=tIeHLnjs5U8">this awesome explanation</a> from 3Blue1Brown.</p><p>The magic piece of the puzzle that makes gradient descent work is the <strong>derivative of our activation function </strong>(sometimes called the <strong>prime</strong>). Luckily for us, the sigmoid function has a simple derivative:</p><blockquote>y = x * (1.0 — x)</blockquote><p>Using this deceptively simple code, we can take a step down the error gradient, adjust the weights in the network and improve the performance. We do this by stepping in reverse through each layer in the network, calculating the derivative of the output with respect to the input, and then backpropagating the error to the next layer. Here’s some code that does all that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01f2403198b2c657ebbb1e8ad36e2326/href">https://medium.com/media/01f2403198b2c657ebbb1e8ad36e2326/href</a></iframe><p>Once we have the derivatives for each layer, we can take one final pass through the network to update the weights with gradient descent. There are many versions of gradient descent you could use, but in this lesson we’ll stick to simply integrating the derivative with a learning rate, and then adjusting the weights accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd883f0498bcc0566e1f176fa8eb0d95/href">https://medium.com/media/bd883f0498bcc0566e1f176fa8eb0d95/href</a></iframe><h3>Putting it all together</h3><p>We now have all the components in place for backpropagation. All we need to finish our implementation is a controlling algorithm that performs a number of training epochs on some data.</p><p>Let’s start with the data by creating a toy dataset of numbers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1472797efdbd2b594777d567fdaa77ed/href">https://medium.com/media/1472797efdbd2b594777d567fdaa77ed/href</a></iframe><p>We’ll try to get our network to learn this simple mapping with a training routine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbc3fb7c76e14aec8cf6ac23da8ae89e/href">https://medium.com/media/bbc3fb7c76e14aec8cf6ac23da8ae89e/href</a></iframe><p>When you run this code, you should notice the error decreasing with each epoch.</p><h3>Epoch complete</h3><p>We’ll leave it there for this week. We’ve covered backpropagation and gradient descent for training our MLPs with supervised learning and a labelled dataset. You might have noticed that the network isn’t particularly good at approximating this toy dataset we made. Next week we’ll dig into why this might be, when use our newly-acquired skills on some more realistic data.</p><p>In the meantime, I have a simple investigative challenge for you:</p><ol><li>Play around with different values of the network size, amount of training data and learning rate. What do you notice about how each number affects the performance of the model</li></ol><p>As always, you can find the source code for all the above examples on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>To begin your AI-coding training at day one, go <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>.</p><p>And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1b4efd944be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/training-to-train-artificial-neural-networks-part-ii-b1b4efd944be">Training to train: Artificial Neural Networks, part II</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking artificially: Artificial Neural Networks, part I]]></title>
            <link>https://medium.com/the-sound-of-ai/thinking-artificially-artificial-neural-networks-part-i-fb0ea78a9f6?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb0ea78a9f6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 14:19:31 GMT</pubDate>
            <atom:updated>2019-03-28T09:04:10.985Z</atom:updated>
            <content:encoded><![CDATA[<p>The latest tutorial in our AI coding series.</p><p>Welcome back, neurons. This week we’re introducing a new AI topic. Over the next few tutorials, you’ll learn the basic theory behind Artificial Neural Networks (ANNs) — a powerful and versatile AI model — and how to build and train one from scratch.</p><p>You could just use a library like <a href="https://www.tensorflow.org/">TensorFlow</a> to create and train a powerful, ‘deep’ ANN in a few lines of code. While handy for creating efficient ANNs, this isn’t ideal if you want to <em>really </em>understand the system and how to build them yourself. So let’s go deeper, and explore the wonderfully simple-yet-complex world of ANNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jj6AsSP9c9hZiuASYic7Eg.jpeg" /><figcaption>A visual representation of an ANN.</figcaption></figure><h3>What is an Artificial Neural Network?</h3><p>ANNs are vaguely inspired by the way biological brains like our own work. Our brains are made up of individual cells called <strong>neurons</strong>. On their own, these neurons don’t do that much; they can receive some electrical input and become activated with some output. But when these neurons are <strong>connected </strong>together, they exhibit higher-level behaviour that gives rise to all of our cognitive processes and abilities such as thought, consciousness and memory. While the human brain has around 100 billion neurons, ANNs use far fewer, massively simplifying matters. Even the deepest of ‘deep’ networks in use today only contain around one million neurons. ANNs simulate the behaviour of their biological counterparts with nonlinear mathematical functions that map a given input onto a desired output.</p><p>ANNs consist of the following elements:</p><ul><li>An <strong>input layer</strong>;</li><li>One or more <strong>hidden layers</strong>;</li><li>An <strong>output layer</strong>;</li><li>A set of <strong>weighted connections</strong> between the layers; and</li><li>An <strong>activation function</strong> for each layer (except the input layer).</li></ul><h3>Artificial neurons under the microscope</h3><p>Neurons are the computational units of an ANN — its building blocks. An artificial neuron, like its biological counterpart, receives one or more <strong>inputs, adds </strong>them up and passes that sum through an <strong>activation function</strong> to produce an <strong>output</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*6ZNeWhTAfHHn8RKs" /><figcaption>An artificial neuron</figcaption></figure><p>Let’s see how this works mathematically. We have the following elements to consider:</p><ul><li>xk are the k input signals (from other layers);</li><li>wk are the weights of the connections between the inputs and the neuron;</li><li>f is the activation function</li></ul><p>The output of the neuron is <em>y = f(x1w1 + x2w2 + … + xkwk).</em></p><p>There are several types of activation functions we can use in ANNs. ReLU, tanh and sigmoid are some of the most common. For now, we’ll be using the <strong>sigmoid function</strong>, a beautiful nonlinear function, with some nice mathematical properties like differentiability and continuity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/0*Fqd6S1XlQzBLbjKa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*xdDZfbwowZFlHP2w" /><figcaption>The sigmoid activation function and its output.</figcaption></figure><p>An artificial neuron can be simply implemented like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2bb246f406361b90bcfbad3bd645dd0/href">https://medium.com/media/c2bb246f406361b90bcfbad3bd645dd0/href</a></iframe><h3>Connecting the dots</h3><p>Single neurons by themselves are not particularly powerful processing units. The strength of a NN becomes clear when we <strong>connect </strong>several neurons in a <strong>layered network</strong>.</p><p>ANNs consist of a number of layers. The first layer is called the <strong>input layer</strong>. Then we have at least one, but often more, <strong>hidden layers</strong>. Finally, there is an <strong>output layer</strong>. One of the simplest ANNs is called a <strong>Multilayer Perceptron</strong> (MLP). This is a type of <strong>feedforward </strong>network, meaning that the data is processed in one direction, from input to output. We start from the input nodes, moving through the hidden layers and, eventually, arriving at the output layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*I3-3hy6WngJYMX7R" /><figcaption>Architecture of a Multilayer Perceptron.</figcaption></figure><p>In an ANN, each connection between the layers is <strong>weighted</strong>. Usually the network will undergo a process of <strong>training</strong>, which is nothing more than iteratively tweaking the values of the weights of the connections, so that the network behaves the way you want it to. We’ll cover how to train our networks next week, but for now let’s look at an object-oriented implementation of an MLP.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d95b5690484bed8d9ea7dfea6ec76e/href">https://medium.com/media/05d95b5690484bed8d9ea7dfea6ec76e/href</a></iframe><h3>Brain freeze</h3><p>That’s it for this week! We learned about <strong>ANNs</strong> and their architecture, and implemented our first ANN — an <strong>MLP</strong>. Right now the network isn’t very useful, because it just produces noise. To do anything exciting, we need to <strong>train </strong>it — and that’s exactly what we’ll do next time.</p><p>In the meantime I have a challenge for you: the MLP implementation above only works with one hidden layer. Can you extend it to have any number of hidden layers that differ in size?</p><p>We’ll go through the solution to this next week, and as always you can find the source code on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>To begin your AI-coding training at day one, go <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>.</p><p>And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb0ea78a9f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/thinking-artificially-artificial-neural-networks-part-i-fb0ea78a9f6">Thinking artificially: Artificial Neural Networks, part I</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sing a song of data: Markov chains, part II]]></title>
            <link>https://medium.com/the-sound-of-ai/sing-a-song-of-data-markov-chains-part-ii-d7134e903869?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7134e903869</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 16:11:13 GMT</pubDate>
            <atom:updated>2019-03-20T16:11:13.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back, machine learners. This week we’ll continue with Markov chains, and use our first dataset to do what you’ve all been waiting for: machine learning. Again, it’s better if you warm up with the <a href="https://medium.com/the-sound-of-ai/they-call-me-mr-stochastic-markov-chains-part-i-6f178b5b5192">previous post</a>, as we’re picking up from where we left off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEVQBzXZhBDyaXiT1I3HFg.jpeg" /><figcaption>Meet HRP-4, a singing robot from Japan</figcaption></figure><h3>Scrambled eggs</h3><p>First, let’s look at the solution to last week’s tasks. You were asked to automatically create a Markov chain transition matrix from the famous nursery rhyme “Humpty Dumpty”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58544550b3782f09ca01c995af832670/href">https://medium.com/media/58544550b3782f09ca01c995af832670/href</a></iframe><p>To use this text in a Markov chain, we first need to <strong>tokenise </strong>it. This is where we split the single string of text into a list of individual words. We can do this with a simple <a href="https://www.regular-expressions.info/">regular expression</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/425f7980ed35d39c38690737b2b69add/href">https://medium.com/media/425f7980ed35d39c38690737b2b69add/href</a></iframe><p>Running the above code will output the following list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e81d22bfff5180bab6a39b155e159175/href">https://medium.com/media/e81d22bfff5180bab6a39b155e159175/href</a></iframe><p>Next, we can create our transition matrix by iterating through this list and updating discrete distributions for each word depending on their previous word. Here’s a function that implements the full procedure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b81878326f4372a2fa66826363bb4f05/href">https://medium.com/media/b81878326f4372a2fa66826363bb4f05/href</a></iframe><p>Finally, we need an initial distribution, which in our case is quite simple, because we know that we always want to start with the word “Humpty”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7a993c3aa799d9a6709d11932f72cf/href">https://medium.com/media/af7a993c3aa799d9a6709d11932f72cf/href</a></iframe><p>Now that we’ve constructed our Markov chain, we can use it to generate a new version of Humpty Dumpty:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f182bfd02b55b77016635acc8a876d/href">https://medium.com/media/29f182bfd02b55b77016635acc8a876d/href</a></iframe><p>Here’s an example output from our Humpty Dumpty generator:</p><blockquote>Humpty Dumpty sat on a great fall All the king’s horses and all the king’s horses and all the king’s horses and all the king’s men couldn’t put Humpty together again</blockquote><h3>Data wrangling</h3><p>Many AI algorithms rely on creating a statistical model of some dataset. This subset of AI is what’s referred to as Machine Learning (ML) and — guess what — the Humpty Dumpty example above is <em>already</em> a simple application of ML. (How easy was that?).</p><p>However, most ML tasks are a little trickier — the dataset will often contain information that’s not important, or need to be cleaned or transformed in some way before it becomes useful and can be given to the algorithm. This process is called <strong>data wrangling</strong>. Often, the success or failure of many ML projects comes down to data wrangling</p><blockquote>Machine Learning is the process of manipulating your dataset so that the algorithm does what it’s supposed to do — Me</blockquote><p>Let’s start by looking at a simple example of data wrangling. We’ll use a dataset from the data science portal <a href="https://www.kaggle.com/">Kaggle</a>, <a href="https://www.kaggle.com/mousehead/songlyrics/home">mousehead’s Song Lyrics dataset</a>. This dataset contains lyrics for 55000+ songs in English. We’ll use data wrangling to count how many songs this dataset contains for a specific artist.</p><p>The dataset is in a simple <a href="https://en.wikipedia.org/wiki/Comma-separated_values">CSV format</a>, similar to a spreadsheet, and contains 4 columns:</p><ol><li>Artist</li><li>Song name</li><li>Link to a webpage</li><li>Lyrics of the song</li></ol><p>So to find the number of songs a specific artist has, we need to loop through the rows in the dataset, check the first column against the artist we’re looking for, and increment the song count if it’s a match.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b1aba984c906adc8945e9c624d47108/href">https://medium.com/media/9b1aba984c906adc8945e9c624d47108/href</a></iframe><h3>Outro</h3><p>Let’s leave it there for this week. We’ve had our first crack at <strong>machine learning</strong>, and learned how to perform some simple <strong>data wrangling</strong> to extract useful information from a dataset.</p><p>I’ll leave you with a fun challenge for next week:</p><ol><li>Can you use this week’s code to read the Song Lyrics dataset, create a Markov chain for the entire discography of a single artist, and generate a new song with that Markov chain?</li></ol><p>Good luck and, as always, you can get the source code for this week on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>Continue your training to supreme master-level AI coding <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>.</p><p>And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7134e903869" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/sing-a-song-of-data-markov-chains-part-ii-d7134e903869">Sing a song of data: Markov chains, part II</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[They call me Mr Stochastic: Markov chains, part I]]></title>
            <link>https://medium.com/the-sound-of-ai/they-call-me-mr-stochastic-markov-chains-part-i-6f178b5b5192?source=rss-5e7590883be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f178b5b5192</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Andy Elmsley]]></dc:creator>
            <pubDate>Wed, 13 Mar 2019 14:11:09 GMT</pubDate>
            <atom:updated>2019-03-13T14:11:09.318Z</atom:updated>
            <content:encoded><![CDATA[<p>The latest post in our AI coding tutorial series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4f2Jz8QuWzdDEel56W_0w.png" /><figcaption>A random walk through a Markovian space.</figcaption></figure><p>Welcome back, AI artisans. This week, we’ll continue the theme of stochastic models by implementing our own Markov chain. Before continuing, make sure you’ve warmed up by understanding the basics of probabilistic terminology, systems and some of the helper functions I covered in the <a href="https://medium.com/the-sound-of-ai/ai-probably-3af3bc5c5ca?source=friends_link&amp;sk=0464ff61c34fa9e6bd29b22c58cad9cf">previous post</a>.</p><h3>The trouble with simple distributions</h3><p>Let’s consider the following sequence:</p><blockquote>AEEAAAEAAA</blockquote><p>At first glance, there’s not much logic to the sequence. It appears fairly random — a classic case of a stochastic process.</p><p>Just like we did in the previous post, we can create a simple, discrete distribution by counting up the As and Es and then normalising the sum. The distribution for this sequence would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369e3b3dff11b704f3ee40c7430b4786/href">https://medium.com/media/369e3b3dff11b704f3ee40c7430b4786/href</a></iframe><p>We could use this to re-generate a sequence and we might get something like the following:</p><blockquote>AEAEAAEEAA</blockquote><p>This seems reasonable enough at first glance; but isn’t it missing something from the sequence? It’s hard to tell with something as meaningless as As and Es, so let’s look at this more semantic sequence instead:</p><blockquote>red flower red car red car red flower</blockquote><p>The discrete distribution for the above sequence would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b50c79ecd79c8d815ba3f7cc5c3d84ad/href">https://medium.com/media/b50c79ecd79c8d815ba3f7cc5c3d84ad/href</a></iframe><p>If we were to use this distribution, it’s entirely possible that we might randomly generate the following sequence:</p><blockquote><em>red red car red red red car flower</em></blockquote><p>Not quite what we’re looking for! What’s gone wrong here is that the simple probability distribution is not capturing any of the <strong>local structure</strong> of the sequence. In other words, <strong>the next word in the sequence depends on the current word</strong> — this dependency can’t be captured by this simple frequency distribution approach, which should only be used for independent outcomes.</p><h3>Markov models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*UZFDgaGaihky2uRe" /><figcaption>Andrey Markov. Great beard, also good at maths.</figcaption></figure><p>Andrey Markov was a turn of the 20th century Russian mathematician, best known for his work in differential calculus and stochastic processes. As you might’ve guessed, he’s the inventor of the Markov chain, which he first used to model alliteration in Russian literature.</p><p>Generally speaking, a Markov chain can be used to model a stochastic process where <strong>the next state is influenced by the current state</strong>, and, optionally, any number of its previous states. Markov chains belong to a wider set of similar systems, collectively known as Markov models. In a later Code of AI tutorial we’ll delve into the Hidden Markov Model, but for now, we’ll stick with the simpler Markov chain.</p><p>Markov chains have two components: an <strong>initial distribution</strong> and a <strong>transition matrix</strong>. The initial distribution is a discrete probability distribution that tells us what state to start with. The transition matrix is a set of nested discrete probability distributions, differing depending on the current state.</p><p>Let’s think of our initial ‘AE’ sequence in terms of its states. We could visualise the sequence like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*fNTuzPyThK595m-C" /><figcaption>A Markov chain with two states</figcaption></figure><p>The initial distribution in this case is easy; A and E both have equal chance of being the first state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5297567455ba0c495998b52db102d8e7/href">https://medium.com/media/5297567455ba0c495998b52db102d8e7/href</a></iframe><p>Now, if we are in A, we have a 60% chance of staying in A, and a 40% chance of moving to E. If we are in E, we have a 30% chance of staying in E and a 70% chance of moving back to A. We can represent that quite simply as a transition matrix with nested dictionaries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60f0d06def2ea78848a3a848e36508fd/href">https://medium.com/media/60f0d06def2ea78848a3a848e36508fd/href</a></iframe><p>And that’s all the data we need to represent a Markov chain!</p><p>Now, when we’re using the chain to predict or generate new values, we can sample from the initial distribution to get our starting state, and then sample again from the transitionMatrix from that point on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dec837cbb56186c687f9066159a27a27/href">https://medium.com/media/dec837cbb56186c687f9066159a27a27/href</a></iframe><p>Running this code gives us an output sequence very similar to what we’re after, with the added benefit that we can pick up on some <strong>dependent local structure</strong> in the sequence. And <em>that, </em>is a Markov chain.</p><h3>Mark-off</h3><p>This week, we’ve seen the limits of discrete probability distributions for modelling sequences, and how Markov chains can solve that issue by <strong>modelling probabilistic state dependencies</strong>.</p><p>I’ll leave you with a couple of tough nuts to crack for next time:</p><ol><li>Can you write a Markov chain to describe the ‘red flower red car red car red flower’ sequence?</li><li>Can you write a function that automatically creates a transition matrix from the words of the popular nursery rhyme Humpty dumpty?</li></ol><blockquote>Humpty Dumpty sat on a wall</blockquote><blockquote>Humpty Dumpty had a great fall</blockquote><blockquote>All the king’s horses and all the king’s men</blockquote><blockquote>couldn’t put Humpty together again</blockquote><p>3. Can you use this transition matrix along with an initial distribution to create a new remix of Humpty Dumpty?</p><p>Next time we’ll walk through the solution to these tasks (which, by the way, is your first machine learning task) and start to work with <strong>datasets</strong>.</p><p>As always, you can get the source code for this week on our <a href="https://github.com/melodrivemusic/CodeOfAI">GitHub</a>.</p><p>Continue your training to supreme master-level AI coding <a href="https://mailchi.mp/92b85e5ebbb8/thecodeofai">here</a>.</p><p>And give us a <a href="https://twitter.com/melodrivemusic">follow</a> to receive updates on our latest posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f178b5b5192" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-sound-of-ai/they-call-me-mr-stochastic-markov-chains-part-i-6f178b5b5192">They call me Mr Stochastic: Markov chains, part I</a> was originally published in <a href="https://medium.com/the-sound-of-ai">The Sound of AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>