<?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 Tom Titcombe on Medium]]></title>
        <description><![CDATA[Stories by Tom Titcombe on Medium]]></description>
        <link>https://medium.com/@t.j.titcombe?source=rss-b24b8d417018------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*CPsR3aIWFLPrzT2xnwk22g.png</url>
            <title>Stories by Tom Titcombe on Medium</title>
            <link>https://medium.com/@t.j.titcombe?source=rss-b24b8d417018------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:08:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@t.j.titcombe/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[A Gentle Introduction to Differential Privacy]]></title>
            <link>https://medium.com/data-science/a-gentle-introduction-to-differential-privacy-330434437cdf?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/330434437cdf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[differential-privacy]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[privacy]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 20:15:15 GMT</pubDate>
            <atom:updated>2020-01-24T14:48:29.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pi0k_GPVIO7x6pPw7Kw_qw.png" /></figure><h4>What is differential privacy? Why might we want it? How can we achieve it?</h4><p>Imagine you’ve been approached by a sociologist who wants you to answer yes/no questions on a variety of topics to gain an understanding of the demographic of your town. Most of the questions you have been asked are quite mundane, but there are a few to which you would rather not disclose your answers. “Don’t worry about privacy”, the researcher reassures you, “before I publish the data I will remove any information that will allow your answers to be traced back to you. It will be totally anonymous.”</p><p>Being a privacy-conscious individual, you know that this isn’t strictly true: the Netflix Prize dataset, for example, was successfully de-anonymised by comparing Netflix movie ratings to IMDB ratings, despite being stripped of identifying features like names and addresses [1]. Perhaps you have <em>publicly</em> released answers to enough of the mundane questions through various social media that somebody could trace your answers back to you. After all, how many anime and cheese loving free market capitalists who studied oceanography can there be?</p><p>You decide to protect yourself by embellishing your answers with a little bit of randomness. For every question, you flip a coin. If it’s heads, you answer truthfully; if it’s tails, you flip again to determine which answer you will give.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*xgFp3pUnc6SPcCYGZDRw0A.png" /><figcaption>Trick question. The answer’s “yes”.</figcaption></figure><p>Now, <em>even if</em> somebody works out that you’re record X in the sociologist’s dataset, they cannot know if the answers linked to you are true. You’ve also made it much more difficult for somebody to link your anonymous answers to any existing information. By adding noise to your data in this way, you have unwittingly ensured your data is <em>locally differentially private </em>to some degree<em>.</em></p><h4>Define privacy</h4><p>The definition of privacy which differential privacy strives for is that results of something (a dataset, a model, a statistic etc.) do not change when any individual is removed from or added to the data. That is to say that it is not possible to discover any one person’s contribution because the data you’re looking would be the same regardless of whether or not their data was present.</p><p>Some people may feel that such a requirement is going above and beyond what should be considered “private”: perhaps it would be acceptable that at least half of the individuals in the dataset are kept secure, not every one of them. There is nothing inarguably wrong with that — privacy is a question of ethics and policy, not an absolute constant of the universe — but differential privacy is a gold standard for privacy in business, government and research.</p><p>The mathematical concept of differential privacy (which we will not express here — this is a gentle introduction, after all) is not a single algorithm — you can’t simply “run differential privacy” on something. Rather, it is a bound that, if met, means your data is protected from exposure to some degree. In practice, things won’t hit the ultimate definition of privacy (that nothing changes when somebody is removed), but it is possible to make it far more difficult to learn an individual’s data.</p><p>To make something differentially private is “simply” a case of adding noise to the data from very specific distributions. The difficulty is working out whether you have added the correct level of noise and applied it in the correct way. This can get very tricky for complex datasets and functions.</p><h4>Just a couple of numbers</h4><p>There are two number which determine the level of protection, <em>epsilon </em>(ε) and <em>delta </em>(δ)<em>. </em>Private <em>mechanisms</em> (the thing you do to your dataset/model/statistics to make it differentially private) are stated as being (ε, <em>δ</em>)-differentially private. These numbers are selected to determine the trade-off between privacy and accuracy in the results which is acceptable for the specific situation.</p><p>ε relates to the level of private information which is leaked. If you want your data to be more protected (a smaller ε), you have to add more noise to your mechanism. A bigger ε<em> </em>means there is less privacy protection, but it also means the results are more valid as they are closer to their true values.</p><p><em>δ </em>is essentially the chance of something going catastrophically wrong and somebody’s privacy being leaked anyway. For a dataset of <em>N</em> individuals you want <em>δ</em> to be<strong> at most</strong> 1/N so the expected number of catastrophes will be fewer than 1.</p><p>The amount of noise required to preserve privacy is dependent not only these two values but also the data and the <em>query</em> you run on the data. For example, consider a list of people’s ages with the values <em>[10</em>, <em>20, 30</em>]. If you’re trying to find the mean (20), removing the 10-year old or the 30-year old would change the mean by 5. However, if you instead wanted to know the greatest value (30), removing the 30-year old would change your query by 10. For a given value of ε and <em>δ </em>you would have to add more noise for the max query than the mean query to account for the relative impact of individual contributions. If the ages were [<em>11, 12, 13</em>] instead, you would have to add less noise because the query changes less than when you have [<em>10, 20, 30</em>].</p><p>Obfuscating individual data does skew the results of the bulk data, but as the dataset grows individual noise cancels out and statistics calculated from the population are closer to the noise-less values.</p><h4>How hard can it be</h4><p>In our first example, randomly changing your answers is locally differential privacy because it is applied directly to the data, before anything is done with it. An alternative formulation is global differential privacy, in which noise is added to the query made on the dataset as a whole — in the mean/max examples above, we would achieve global differential privacy if we added noise to the statistic on the population. In general, global differential privacy produces more accurate answers for the same level of protection than with local differential privacy. The drawback is that you have to be able to trust the data collector to properly apply global differential privacy and protect your data up until that point. Building trust is a far more difficult task than differential privacy, which is why local differential privacy is a popular solution.</p><p>Although differential privacy isn’t a recent concept, it has only started becoming a common concern of governments and businesses in the last couple of years. If you use Apple or Google products, the data you send to them is likely being made differentially private [2]. Apart from a few examples in large tech companies, the field of differential privacy is one sparsely tended to. Although, this is slowly changing: the 2020 US census will be the first to be differentially private [3], and open-source tools for differential privacy are being actively developed [4].</p><p>As implied earlier, the great difficulty in differential privacy is ensuring that something you think is differentially private, is. Using an imperfectly implemented noise distribution can make differential privacy mechanisms insecure [5], and the infrastructure for plug-and-play privacy does not yet exist for those without Google-esque resources to make privacy guarantees.</p><p>Of course, issues of privacy and anonymity remain even in the presence of provably correct differential privacy. In the example of the sociologist’s questionnaire, if somebody knows the randomised answer you gave there is nothing stopping them from acting as if it were the truth; something being differentially private will not shield you from negative consequences if people choose to ignore it. If you were asked the same question in one hundred other questionnaires your noisy answers would begin to converge to the truthful value as the noise cancels itself out. Even knowing merely that somebody is in a dataset can, in some circumstances, expose private information.</p><p>For these reasons it is important to understand that differential privacy does not “solve” privacy. Privacy is an issue which needs political will to legislate, a widespread cultural drive to implement and promote privacy and technical expertise to build the infrastructure for privacy. There is a way to go before our data is truly private, but without differential privacy we won’t get very far.</p><h4>Resources</h4><p>[1] <a href="https://www.cs.utexas.edu/~shmat/shmat_oak08netflix.pdf">https://www.cs.utexas.edu/~shmat/shmat_oak08netflix.pdf</a></p><p>[2] <a href="https://machinelearning.apple.com/2017/12/06/learning-with-privacy-at-scale.html">https://machinelearning.apple.com/2017/12/06/learning-with-privacy-at-scale.html</a></p><p>[3] <a href="https://www.census.gov/about/policies/privacy/statistical_safeguards/disclosure-avoidance-2020-census.html">https://www.census.gov/about/policies/privacy/statistical_safeguards/disclosure-avoidance-2020-census.html</a></p><p>[4] <a href="https://www.openmined.org/">https://www.openmined.org/</a></p><p>[5] <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.366.5957&amp;rep=rep1&amp;type=pdf">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.366.5957&amp;rep=rep1&amp;type=pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330434437cdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-gentle-introduction-to-differential-privacy-330434437cdf">A Gentle Introduction to Differential Privacy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polynote: the new Jupyter?]]></title>
            <link>https://medium.com/data-science/polynote-the-new-jupyter-c7696a321b09?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7696a321b09</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Sat, 21 Dec 2019 19:09:49 GMT</pubDate>
            <atom:updated>2019-12-22T01:39:11.672Z</atom:updated>
            <content:encoded><![CDATA[<h4>There is a lot of buzz surrounding Polynote, Netflix’s multi-language notebook. But is it the Jupyter-killer, or is it all hype?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*eWBh0kllYasHb_OczuqTVA.png" /><figcaption>Source: <a href="https://polynote.org/">https://polynote.org/</a></figcaption></figure><p>If you’ve done any kind of analytical work with Python in the last few years, there is a good chance you have come across <a href="https://jupyter.org/">Jupyter notebooks</a>. The ability to execute new code without needing to re-run the entire script have made notebooks a ubiquitous part of the analytical workflow, but Jupyter notebooks are not without issues. For example, code editing, hints and linting is not supported; this can lead to messy, difficult to debug code and cause some developers to avoid the tool entirely. In 2019, tech behemoth Netflix open-sourced their notebook tool, <a href="https://github.com/polynote/polynote">Polynote,</a> which many people are touting as the Jupyter-killer.</p><p>Like Jupyter, Polynote has multi-language support, however Scala has been included as a “first-class language” in Polynote, with additional support for Python (+ Spark), SQL and Vega. While Jupyter allows you to create a notebook in one of its supported languages (JUlia, PYThon, R), Polynote facilitates multi-language support in a single notebook and even allows for interoperability between code executed in different languages.</p><h3>Installation</h3><p>Unlike Jupyter, Polynote is built with JVM-based languages at its core, which makes the installation process slightly more involved than pip install polynote. Problematically, Polynote is currently only available on Linux and OSX; there is some discussion about the <a href="https://github.com/polynote/polynote/issues/671">inclusion of Windows,</a> however it is not an aim of the development team. Given how open-source Windows ports of popular tools like Swift <a href="https://github.com/SwiftForWindows/SwiftForWindows/issues/76">have failed to bloom</a>, it would be foolish to expect a seamless experience of Polynote on Windows anytime soon.</p><p>That being said, let us assume you have a Linux or OSX machine. I will outline the steps I took to get Polynote working on Ubuntu 18.04.</p><ol><li>Go to the <a href="https://github.com/polynote/polynote/releases">releases</a> and download the latest polynote-dist.tar.gz under “Assets” of the latest release</li><li>Extract polynote with tar -zxvpf polynote-dist.tar.gz</li><li>Install Java: sudo apt install default-jre and sudo apt install default-jdk</li><li>Set JAVA_HOME with export JAVA_HOME=/usr/lib/jvm/default-java/</li><li>pip3 install jep jedi virtualenv</li></ol><p>Additional installation is required for Spark support. You can read more about installing Polynote <a href="https://polynote.org/docs/01-installation.html">here</a>.</p><p>Go into the polynote directory and execute polynote.py , then navigate in a browser to the local address provided (I’ve tested on Firefox and Chrome without problems).</p><h3>Polyglot notebooks</h3><p>The eponymous feature of Polynote is language interoperability: if you define a variable in one language, you can use it in another. This will clearly have limitations as not all languages share the same concepts of types and objects, however most important types, including numpy arrays and pandas dataframes, are supported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ADUqHvQWxsGwHWaEzZYldg.png" /></figure><p>I must confess to having only a tangential knowledge of Scala so I am uncertain of the specific use-cases which would require it to work in tandem with Python, but it is evident that removing the need to convert data between the two languages would make such a project run far more smoothly.</p><p>The majority of projects I have worked on have only required one language (mostly Python, some R) so it is easy to believe that, outside of large projects, language mixing would be a superfluous tool for most data scientists. Of course, as an open-source project, it is likely that the community will extend the suite of supported languages (there is already interest in <a href="https://github.com/polynote/polynote/issues/664">R,</a> <a href="https://github.com/polynote/polynote/issues/542">Julia</a>, and <a href="https://github.com/polynote/polynote/issues/454">Java</a>), which would make Polynote a more appealing tool to a great number of developers; personally, I would love to be able to run statistical tests on Python data in R, rather than spending time trying to find a valid, maintained Python port of the test.</p><h3>Visualisation</h3><p>Data visualisation is a crucial part of data science, yet is it a skill often neglected. Polynote emphasises high quality visualisation by generating Vega specifications from Scala data.</p><blockquote>Vega is a <em>visualization grammar</em>, a declarative language for creating, saving, and sharing interactive visualization designs. With Vega, you can describe the visual appearance and interactive behavior of a visualization in a JSON format, and generate web-based views using Canvas or SVG. — <a href="https://vega.github.io/vega/">https://vega.github.io/vega/</a></blockquote><p>Vega can easily generate aesthetic, complex visualisations. The popular Python visualisation library <a href="https://altair-viz.github.io/">Altair</a> is built upon Vega-lite, the statistical visualisation part of Vega (you can read about generating interactive maps in Altair <a href="https://towardsdatascience.com/interactive-election-visualisations-with-altair-85c4c3a306f9">here</a>).</p><p>Unfortunately, there is no direct support for visualisations of Python data, so there is little benefit for the Python natives. You can still enter the schema directly of course, but in most cases it would be far easier to use a tool like Altair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*VAllEhMhXZthZsAXJZ3CKA.png" /><figcaption>An interactive bar chart? Try producing that in matplotlib</figcaption></figure><h3>Code Editing</h3><p>A large disadvantage of Jupyter notebooks is how opaque the code is: there are no visual cues for incorrect code, as you would find in any decent IDE, nor code completion for functions (which causes my API usage to increase markedly). Polynote, however, bridges the gap between script and notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Dp9N0SUliVd_Or8PFduAhQ.png" /><figcaption>With Polynote, there is no need to memorise swathes of functions</figcaption></figure><p>Type errors in Scala will be underlined, however Polynote does not care about Python type hints (much like the Python community).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*Jc_AmhT8vEu3Z0k8anbd3g.png" /></figure><p>Polynote does not compete with the best code editors, but it is a vast improvement on Jupyter notebooks in this regard.</p><h3>Summary</h3><p>I was intrigued by the possibilities of Polynote. There was a lot of buzz in the data science community and features like in-built Vega plot generation and inter-language communication sounded like game changers. However, I don’t believe Polynote offers enough to draw most data scientists away from Jupyter. Firstly, the lack of Windows support puts it out of reach of a great number of people; Windows is the most popular operating system and its usage is mandated by many businesses and organisations. Secondly, while Scala has its benefits, it is not a vastly used language for everyday data science. Most analytics projects can be and are adequately carried out solely in Python, so language mixing and in-built Vega are of no benefit.</p><p>Polynote’s code editing is a great improvement upon Jupyter and I hope Jupyter improves in this regard. However, as a more established and more actively developed project, I find Jupyter the stronger offering of the two. Polynote is certainly one to watch. It just needs a little more time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7696a321b09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/polynote-the-new-jupyter-c7696a321b09">Polynote: the new Jupyter?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interactive Election Visualisations with Altair]]></title>
            <link>https://medium.com/data-science/interactive-election-visualisations-with-altair-85c4c3a306f9?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c4c3a306f9</guid>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Sat, 26 Oct 2019 12:41:03 GMT</pubDate>
            <atom:updated>2019-10-28T09:14:13.493Z</atom:updated>
            <content:encoded><![CDATA[<h3>Interactive Election Visualisations in Python with Altair</h3><p>In a <a href="https://towardsdatascience.com/visualising-elections-with-python-4973c0c60bbe">recent post</a>, I showed how we can generate hexmaps with matplotlib to visualise elections. While these maps are a great demonstration of how to convey geographic information, they are not without flaws. For example, it can be difficult to identify which constituency is which from the static image, because of the manipulations applied to constituencies to make them of equal size.</p><p>In this post we will use <a href="https://altair-viz.github.io/">Altair</a>, a declarative Python plotting library, to deliver improved, interactive versions of the hexmaps. You can follow along with this post <a href="https://github.com/TTitcombe/ConstituencyMap/blob/master/examples/altair_examples.ipynb">using the notebook</a> on my <a href="https://github.com/TTitcombe">GitHub</a>.</p><p>First, let us remind ourselves what we were left with after the last post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUbpb-Holf8Bt8OxWE4BiQ.png" /></figure><h3>Altair</h3><blockquote>Altair is a declarative statistical visualization library for Python</blockquote><p>Essentially, this means we define our data and the output (what the chart looks like) and Altair will do all the manipulations which take us from input to output.</p><p>Compare that to packages like matplotlib, the staple of Python visualisation: for the hexmap we had to explicitly specify the coordinates, rotation, size and colour <em>of each hexagon</em>.</p><p>While matplotlib provides more control over the final state of graphs, implementing even basic customisation usually takes far more time, knowledge and effort than with Altair (and certainly more than people are willing to give it).</p><p>Altair is built on <a href="https://vega.github.io/vega/">Vega,</a> a JavaScript plotting library. To render the interactive plots, you need a frontend application such as Jupyter lab.</p><p>Altair can be installed via pip (pip install -U altair vega_datasets jupyterlab) or conda (conda install -c conda-forge altair vega_datasets jupyterlab).</p><h3>Data</h3><p>In this post we will be visualising the makeup of the UK parliament immediately after the 2017 general election. This data is freely available from the <a href="https://data.gov.uk/dataset/b77fcedb-4792-4de4-935f-4f344ed4c2c6/general-election-results-2017">gov.uk website</a>. This data has the constituency name, <em>Constituency</em>, and the name of the winning party, <em>Party</em>.</p><p>We have assigned hex coordinates, <em>p</em> and <em>q</em>, of constituencies using <a href="https://odileeds.org/projects/hexmaps/constituencies/">ODILeeds’ fantastic hexmap</a>.</p><h3>A Basic Map</h3><p>It should be simple to generate the basic hex map in Altair due its declarative style. Let’s put that to the test.</p><pre>import altair as alt</pre><pre>alt.Chart(data)<br>    .mark_circle()<br>    .encode(<br>        x=&quot;q&quot;,<br>        y=&quot;r&quot;,<br>        color=alt.value(&quot;lightgray&quot;),<br>        size=alt.value(50),<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*KCWYwoma1CgWqVYcL7rQiQ.png" /></figure><p>It took many lines (and many hours of StackOverflowing) to get the basic matplotlib map working; for Altair, it’s seven lines.</p><p>In Altair, we first create a Chartobject which contains the data we wish to use. We specify what type of marks to make on the chart with mark_circle(). Then we <em>encode </em>the features of the mark with aspects of the data they should be represented by, in this case we set the <strong>x</strong> values to come from the data column <strong>q</strong> and the <strong>y</strong> values to come from the data column <strong>r</strong>. Additionally, we have set the size of each circle to a constant value using size=alt.value(50).</p><p>After defining these few, simple rules, Altair does all the dirty work and produces a brilliant plot.</p><p>Granted, the colour is uninformative and dull at the moment. To remedy this, we need to provide Altair a recipe for linking the party names to a specific colour.</p><pre>parties = [&quot;Conservative&quot;, &quot;Labour&quot;, &quot;Lib Dem&quot;, &quot;Green&quot;, ...]<br>party_colours = [&quot;darkblue&quot;, &quot;red&quot;, &quot;orange&quot;, &quot;green&quot;, ...]  #etc.</pre><pre>colours_obj = alt.Color(<br>    &quot;Party:N&quot;, <br>    scale=alt.Scale(domain=parties, <br>                    range=party_colours)<br>)</pre><pre>alt.Chart(data)<br>    .mark_circle()<br>    .encode(<br>        x=&quot;q&quot;,<br>        y=&quot;r&quot;,<br>        color=colours_obj,<br>        size=alt.value(50),<br>)</pre><p>The alt.Color object tells Altair to get colours from the <strong>Party</strong> column in the data. However, the parties are strings and therefore cannot be interpreted as a colour; alt.Scale translates all of the parties in the <em>domain</em> parameter into the corresponding colour in the <em>range</em> parameter. This is in direct contrast to matplotlib where a colour must be defined <em>for every object</em>.</p><p>One of the negative properties of the matplotlib graph was that it was legend-less: I could not figure out how to produce a legend which could link the colours of the iteratively drawn hexagons with a party name. Knowing matplotlib, even if it were possible to add a label to each hexagon, the resulting legend would have an entry <em>for every single hexagon</em>, paying no notice of repetitions.</p><p>Perhaps unsurprisingly, legends are a trivial matter in Altair — the Color object generates one automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*oJacum03Zpxdm0uvXkvuJA.png" /></figure><h3>Basic Interactivity</h3><p>At this point we have generated a map which supersedes the matplotlib version. However, it still suffers from the issue of the warped geographic boundaries being difficult to identify. Unless you’re looking for a coastal constituency, the chances are you will not be able to locate it.</p><p>We could add text to each hexagon denoting the constituency name, but that will either be too difficult to read or make the plot too large to appreciate. What we need to is to take the static graph and make it interactive. Fortunately for the purposes of this blog post, Altair excels at interactivity.</p><pre>alt.Chart(data)<br>    .mark_circle()<br>    .encode(<br>        x=&quot;q&quot;,<br>        y=&quot;r&quot;,<br>        color=colours_obj,<br>        size=alt.value(50),<br>        tooltip=[&quot;Constituency:N&quot;],<br>)</pre><p>Altair has integrated support for tooltips in a single additional line of code. This is a powerful feature than can instantly elevate the usability of a graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L1vHPwmQAhoD4qiY7fOpQ.gif" /><figcaption>Oxford: definitely not north of Twickenham</figcaption></figure><h3>Even More Interactivity</h3><p>Of course, <a href="https://altair-viz.github.io/gallery/index.html#interactive-charts">Altair has far more interactivity to offer </a>than tooltips. We will sample some of these additional offerings by getting the chart to highlight all constituencies of a certain party on a mouse-click. This behaviour is useful to help identify the distribution of a party throughout the land in what could otherwise be an overwhelming display of colour.</p><p>We start by creating a selection object and telling it that the important information we care about is the <strong>Party </strong>of the selection. We add this interaction selection element to the chart with add_selection.</p><p>To get changing behaviour, we need to replace the static mark parameters with conditional ones. alt.condition takes a condition, a value to display when the condition is met, and a value to display when it is not. Note that the condition in this case is the selection object. The condition is met when the selection object’s <strong>Party</strong> parameter is the same as the <strong>Party</strong> parameter of a mark Altair is attempting to display.</p><pre>selector = alt.selection_single(empty=&#39;all&#39;, fields=[&#39;Party&#39;])</pre><pre>colours_condition = alt.condition(selector, <br>                                  colours_obj,       <br>                                  alt.value(&quot;lightgray&quot;)</pre><pre>alt.Chart(data)<br>    .mark_circle()<br>    .encode(<br>        x=&quot;q&quot;,<br>        y=&quot;r&quot;,<br>        color=colours_condition,<br>        size=alt.value(50),<br>        tooltip=[&quot;Constituency:N&quot;],<br>).add_selection(selector)</pre><p>This example highlights how much pain Altair takes away from complex plotting. We don’t even have to use conditional code to get conditional behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtZ4mlqUmolBNaKNNLyr6w.gif" /></figure><h3>Combining Charts</h3><p>We end this post by showing how multiple charts can be displayed together. We will add a bar graph showing the total number of MPs of each party - information which is difficult to draw from the throng of circles and colour we currently have.</p><p>First, we create the bars. This is a similar process to before, except we are using mark_bars to signal to Altair that, shockingly, we wish to mark bars on the chart object. Notice also that we assign this object to a variable; we will do the same to our map chart.</p><p>The y value for the bars is the count of occurrences of each Party. In other plotting libraries, we would be required to calculate these before plotting; Altair will do this for you with the count() <a href="https://altair-viz.github.io/user_guide/transform.html#user-guide-aggregate-transform"><em>aggregation</em></a>.</p><p>We will also add a horizontal line to the graph to show the point at which a party has a majority. Unfortunately this is an area where Altair stumbles: simply giving the line the y value of alt.value(325)* would not produce the correct result. Instead, we must add the threshold value to our data object and tell Altair to use it.</p><p><em>*Non-technical side-note: 325 is technically the threshold for a majority in the House of Commons, but due to “features” of our democratic system, such as the Speaker and Sinn Fein, the practical requirement is slightly lower.</em></p><pre>df[&quot;threshold&quot;] = 325<br><br>bars = base.mark_bar().encode(<br>    x=&quot;Party:N&quot;,<br>    y=alt.Y(&quot;count()&quot;, title=&quot;Number of MPs&quot;),<br>    color=colours_condition<br>)<br><br>majority = base.mark_rule(color=&quot;black&quot;, strokeDash=[1, 1]).encode(<br>    y=&quot;threshold:Q&quot;,<br>    size=alt.value(3)<br>)</pre><pre>map | (bars + majority)</pre><p>Altair chart objects can easily be combined, stacked or concatenated. The | operator horizontally stacks chart objects, &amp;vertically stacks them, and +adds objects to the same chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nardObmm4dQo8g2Yy4ZGw.gif" /></figure><h3>Next Steps</h3><p>In this quick tour of Altair we created powerful visualisations which would have taken far more time to produce in other libraries, if they are even possible.</p><p>Despite the ease with which Altair handles custom and complex plots, it is a woefully underutilised package. Its interactivity and hands-off approach to plotting could, and should, make it the go-to plotting library for Python users.</p><p>In a later post we will expand upon these plots to visualise how the UK’s political geography may evolve under different voting systems.</p><p>You can find the code used in this post on my <a href="https://github.com/TTitcombe/ConstituencyMap">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85c4c3a306f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/interactive-election-visualisations-with-altair-85c4c3a306f9">Interactive Election Visualisations with Altair</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weight Agnostic Neural Networks]]></title>
            <link>https://medium.com/data-science/weight-agnostic-neural-networks-fce8120ee829?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce8120ee829</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Sun, 08 Sep 2019 09:58:32 GMT</pubDate>
            <atom:updated>2019-09-09T15:13:34.289Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how most mammals are capable of fairly complex tasks, like walking, straight after being born? They haven’t had time to experience the world yet so they’ve clearly not learnt how to perform the actions. Their brains must be pre-wired to enable them to walk, but if the brain structure relies on specific weights then an individual learning from its experiences could lose the ability to act shortly after birth, or never have the ability to begin with.</p><p>Inspired by this, Adam Gaier and David Ha introduced the world to <a href="https://arxiv.org/pdf/1906.04358.pdf">Weight Agnostic Neural Networks</a> (WANN), an evolutionary strategy for developing neural networks which can perform a task <em>independent of the weights of the connections</em>.</p><p>In this post, we’ll briefly look into Weight Agnostic Neural Networks and use a code implementation to train our very own WANNs on the Lunar Lander gym environment.</p><h3>NEAT</h3><p>The evolutionary strategy of this paper is built on <a href="http://nn.cs.utexas.edu/downloads/papers/stanley.cec02.pdf"><em>NeuroEvolution of Augmented Topologies</em></a> (NEAT). NEAT is a type of <em>genetic algorithm</em> (GA) in which the agents are mutated by changing their structure: nodes and connections can be added or removed, and activation functions of nodes and connection weights can be changed; in other words, their <em>topologies</em> are <em>augmented</em>.</p><p>Agents, which in this context are neural networks, are ranked according to their performance on a specified task.</p><h3>WANN</h3><p>The intent of the paper is use the evolutionary strategies of NEAT to develop networks which perform well on a given task with a range of weight values. Rather than having weights finely tuned to perform the task as happens in standard backpropagation, the network structure will evolve to facilitate the task solution.</p><p>The authors build on NEAT by removing mutation of connection weights, instead evolving networks by adding connections, adding weights or changing a node’s activation function. Connection weights are set to a shared value.</p><p>Furthermore, agents have their performance evaluated with various shared weights. By using an average of the performances to rank the agents, networks in which the <em>structure</em> enables the task to be completed, <em>not the weights</em>, can be developed.</p><h3>Exploring the code</h3><p>The authors have open-sourced their code, which you can find on the <a href="https://github.com/google/brain-tokyo-workshop">Google GitHub</a>. We’ll be using an <a href="https://github.com/TTitcombe/brain-tokyo-workshop">adapted version of this code</a> to train and probe the networks.</p><p>The nature of WANN’s evolutionary strategy produces sparse networks with many skip connections. This structure isn’t easily compatible with the popular ML libraries like PyTorch and TensorFlow, which prioritise backpropagation as the learning mechanism. As a result, the code is written without use of these libraries, and doesn’t make use of GPUs. However, as the WANN generation evaluation procedure is <em>embarrassingly parallel</em>, as the authors put it, we can make use of multiple cores when training.</p><p><em>Note: If you’re not sure how many CPU cores your machine has, go to System Settings (Windows) or type </em>lscpu <em>in a terminal (Ubuntu)</em></p><p>To begin, we’ll explore one of the pre-trained networks provided with the code. T<a href="https://github.com/google/brain-tokyo-workshop/tree/master/WANNRelease/WANN/champions">here are “champions” of BipedalWalker, CartpoleSwingUp, CarRacing environments, as well as solving MNIST</a>.</p><p>Get a local copy of the code using git clone https://github.com/TTitcombe/brain-tokyo-workshop.git and navigate to the <strong>brain-tokyo-workshop/WANNRelease/prettyNeatWann </strong>directory.</p><p>The authors have provided a series of pre-trained “champions” in a selection of gym environments. We can run the <em>CartPoleSwingUp</em> champion with</p><pre>python wann_test.py -p p/swingup.json -i champions/swing.out --nReps 1 --view True</pre><p>This code run the network, cycling through shared weight values in the range [-2, 2], demonstrating that the network is capable of performing independent of the weight value, as we can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Us_jrlFs26vMyE_DBdY-IA.gif" /><figcaption>All shared weight values perform equally, but some perform more equally than others</figcaption></figure><p>The model evidently does not perform equally well for all shared weight values, and its best performance is not a perfect one, however we have semi-successful policies for a wide range of weights — non-WANN models are not as robust to weights changes as this.</p><p>The final fitness values show that, while there is some variation in performance across the shared weight values, the network performs generally well regardless of the specific value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*HBL0B0ssISbZr_0CGUYh-g.png" /></figure><h3>Visualising the network</h3><p>The team have also provided code to visualise the network. We can execute a short script to see the <em>SwingUp </em>champion:</p><pre>import matplotlib.pyplot as plt</pre><pre>from vis.viewInd import viewInd</pre><pre><br>viewInd(&quot;champions/swing.out&quot;, &quot;swingup&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*K2Z0kKKba0CV7e6Jxa0RHQ.png" /></figure><p>It’s more chaotic than a traditional neural network due to the sparse connectivity and skip connections, but it is more explainable since the activation functions and structure have been explicitly optimised.</p><p>The most striking feature of the network is the x parameter (position of the cart) has an almost direct line to the output node, which calculates force, intercepted only by a single hidden neuron with an inverse activation function. This line has the effect of providing a force towards the centre of the screen <em>regardless of the sign of the shared weight value</em>: the network has learned how to get the cart to the centre in a weight-agnostic way.</p><p>In fact, this pattern occurs twice; perhaps the network learned that the weight values occupy a small range and so does not generate a strong force, therefore the network doubles the inward force by doubling the pattern. If this is the case, the network is not entirely weight agnostic, but training the network over a greater range of weight values may remedy this.</p><p>Secondly, several nodes go through a node with a gaussian activation function in an early layer. The gaussian activation function is symmetric about the y-axis so outputs the same result for <em>x</em> and <em>-x: </em>this node is agnostic to the sign of the weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74wGOwY_nvXTZeJ7baOfgw.png" /><figcaption>The gaussian activation function</figcaption></figure><p>Another activation function which appears frequently is the sinusoidal function (<em>sin</em>). Its cyclical pattern makes outputs somewhat independent of input magnitude. The prevalence of activation function with input-independent regions is likely a direct result of the network optimising for weight agnosticism.</p><h3>Training our own WANN</h3><p>The code provides training scripts for <em>SwingUp</em>, <em>CarRacing</em>, <em>BipedalWalker</em>, and an MNIST classification task. We’ll be training a WANN on the <a href="https://gym.openai.com/envs/LunarLanderContinuous-v2/"><em>LunarLander</em> OpenAI gym environment</a> to demonstrate that those tasks were not selected for some innate suitability to WANN.</p><p>To begin, we create a “lunar” task in the <a href="https://github.com/TTitcombe/brain-tokyo-workshop/blob/master/WANNRelease/prettyNeatWann/domain/config.py">domains config</a> which specifies that there are 8 inputs and 2 outputs. Furthermore, we set a linear activation function to all input and output neurons, and allow hidden neurons to use any of the activation functions.</p><p>We then define the parameters of the training algorithm by making a copy of the <a href="https://github.com/TTitcombe/brain-tokyo-workshop/blob/master/WANNRelease/prettyNeatWann/p/laptop_swing.json">“laptop_swing” configuration json</a>, which we’ll call “laptop_lunar”, only changing the task from “swingup” to “lunar”. This configuration file specifies the number of generations to run for and the number of agents in a population, among other factors. We are only running a lightweight experiment to demonstrate how this can be done, so we can keep the parameters small.</p><p>Now, we start training:</p><pre>python wann_train.py -p p/laptop_lunar.json -n 2 -o lunar</pre><p>-n 2 specifying that my two cores should be used; if you have more, use them.</p><p>On my somewhat outdated i7, an average generation took around a minute to run (this started at 10 seconds but steadily increased as the networks became more adept at the task and therefore did not fail as quickly). As a result, I only completed 300 epochs before I had to commandeer my CPU for other tasks. The networks succeed at the task fairly early, however: after 300 epochs the lander can be brought down safely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iSe0xPvaXnyxFxYua52Jzw.gif" /></figure><h3>Conclusions and Next Steps</h3><p>The weight-agnostic neural network paper presents a method for developing more interpretable networks by encoding the solution directly in the network architecture. Compared with backpropagation, WANNs are robust to changes in node inputs, which could form the foundations to a strong defence against adversarial attacks or even against corrupted networks.</p><p>For the purposes of those working on <em>artificial general intelligence</em>, WANNs demonstrate a way for us to encode intelligence and behaviour from creation, as occurs in much of the animal kingdom.</p><p>Providing agents with non-zero intelligence from the start could allow them to capitalise on their experiences much more quickly than would otherwise be possible. I’m interesting in seeing how the fine-tuning of WANNs through backpropagation compares to training of models from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce8120ee829" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/weight-agnostic-neural-networks-fce8120ee829">Weight Agnostic Neural Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventures in Reinforcement Learning II: DQN]]></title>
            <link>https://medium.datadriveninvestor.com/adventures-in-reinforcement-learning-ii-dqn-9673e4349516?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/9673e4349516</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[deepmind]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 18:57:27 GMT</pubDate>
            <atom:updated>2019-09-10T15:38:16.130Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last installment, I laid out plans to undertake a reinforcement learning curriculum and implementing several definitive algorithms along the way. We implemented a basic search algorithm which easily found a neural network capable of solving the CartPole environment.</p><p>In this post, we’ll implement a <em>Deep Q Network</em> (DQN) and <em>Double Deep Q Network</em> (Double DQN)*. As we solved CartPole last time, there is little benefit in applying a far more complex model on the same challenge: we step things up by working on the custom <em>CartPoleSwingUp</em> environment.</p><p><a href="https://www.datadriveninvestor.com/2019/01/23/deep-learning-explained-in-7-steps/">Deep Learning Explained in 7 Steps - Updated | Data Driven Investor</a></p><p><em>*To ensure I’m learning reinforcement learning in a manageable way, I’ve decided to first implement a version of DQN which takes state information directly as input. The full DQN model — learning to play Atari games from visual information — will be covered in a later post.</em></p><p>We’ll implement DQN, and likely all future work, in PyTorch, making use of automatic differentiation and GPU optimization.</p><p><a href="https://github.com/TTitcombe/DQN">The code is available here.</a></p><h3>DQN — The Basics</h3><p>Let’s begin with a brief dive into the theory behind DQN.</p><p><a href="https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf">First published in 2014</a>, the Deep Q-Network extends the classic Q-Network into the age of deep learning.</p><p>Q values represent the greatest reward which can be given after making an action <em>a</em> when in state <em>s</em>.</p><p>DQNs use a deep neural network to estimate Q values <em>directly from state information</em>. The model outputs one Q value for each action, and we select the action which gives the highest Q value in order to perform the best in the environment.</p><p>The model learns by calculating the loss between our future reward and the reward the model expected when in a given state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*yqyBkEQ708w-3V_RC3GhRQ.png" /></figure><p><em>s </em>is initial state, <em>a</em> is the action performed, <em>r</em> is the reward received, <em>s`</em> is the next state, and <em>gamma</em> is a discount factor (usually 0.99).</p><p>To encourage exploration, we use an <em>epsilon-greedy</em> policy to select an action; on each step, we generate a random number, if it’s less than the epsilon value, we take a random action, otherwise, we take the action from the model. Epsilon starts at 1 (randomness guaranteed) and is annealed linearly to a small value over a number of frames.</p><p>A key factor in the success of this work was not the deep network, but using a <em>replay memory</em>: sampling from past actions and training the model on these historic states. Replay memory is crucial in breaking the otherwise highly-dependent experiences the model would learn from. Without replay memory, the model would never re-evaluate past states and would get stuck in local minima.</p><p>The second crucial adaptation introduced by DQN was using a <em>target model</em> to calculate target values and to update the target model with the primary model’s weights every <em>C</em> frames. Having the target model lag behind reduces the correlation between targets and Q values.</p><p>DQN is a <em>model-free</em> algorithm because it is provided no information on the transitions between states — it has to learn that for itself.</p><h3>DQN — The Implementation</h3><p><em>Note: The code has been adapted for Medium; for the full code, see the </em><a href="https://github.com/TTitcombe/DQN"><em>GitHub repo</em></a></p><p>The base network is a simple feedforward neural net (remember, at this stage, we’re only taking state information, not the rendered frame of the environment, as the input). The DQN paper uses the same hyperparameters and model for all Atari tasks, which suggests that there is a level of robustness to the algorithm which makes the exact format of the model non-critical.</p><pre>import torch.nn as nn<br>import torch.nn.functional as F</pre><pre>class DQN(nn.Module):<br>    def __init__(num_inputs, num_actions):<br>        super().__init__()<br>        self.linear1 = nn.Linear(num_inputs, 128)<br>        self.linear2 = nn.Linear(128, 256)<br>        self.linear3 = nn.Linear(256, 64)<br>        self.linear4 = nn.Linear(64, num_actions)</pre><pre>    def forward(self, x):<br>        x = F.relu(self.linear1(x))<br>        x = F.relu(self.linear2(x))<br>        x = F.relu(self.linear3(x))<br>        return self.linear4(x)</pre><p>We adapt replay memory from <a href="https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html">this PyTorch implementation</a>. We use a <em>deque</em> to easily create a rolling window of memories.</p><pre>from collections import deque, namedtuple</pre><pre>Transition <strong>=</strong> namedtuple(&#39;Transition&#39;,<br>                        (&#39;state&#39;, &#39;action&#39;, &#39;next_state&#39;, &#39;reward&#39;))</pre><pre>class ReplayMemory:<br><br>    def __init__(self, capacity):<br>        self<strong>.</strong>capacity <strong>=</strong> capacity<br>        self<strong>.</strong>memory <strong>=</strong> deque(maxlen=capacity)</pre><pre><strong>    </strong>def update(self, <strong>*</strong>args):<br>        self.memory.append(Transition(*args))<br><br>    def sample(self, batch_size):<br>        return random<strong>.</strong>sample(self<strong>.</strong>memory, batch_size)<br><br>    def __len__(self):<br>        return len(self<strong>.</strong>memory)</pre><p>We select an action from our model at each step using a linearly-annealed epsilon-greedy policy and update the replay memory with our observation. Note that we apply a wrapper to the environment to stack 4 frames together when we call step .</p><pre>import random<br>import torch</pre><pre>from cartpoleswingup import CartPoleSwingUpEnv</pre><pre>SKIP_N = 4  # We feed four frames into the model together</pre><pre>eps_max = 1.0<br>eps_min = 0.1<br>eps_frames = 10_000<br>eps = lambda x: max(0.1, eps_max - x*(eps_max-eps_min)/eps_frames)</pre><pre>memory = ReplayMemory(10_000)<br>model = DQN(4 * SKIP_N, 2)</pre><pre>env = CartPoleSwingUpEnv()<br>state = env.reset()<br>is_done = True<br>frame = 0</pre><pre>while not is_done:<br>    if random.random() &lt; eps(frame):<br>        action = env.action_space.sample()  # choose randomly<br>    else:<br>        with torch.no_grad():<br>            action = model(state).max(1)[1].item()</pre><pre>    next_state, reward, is_done, _ = env.step(action)<br>    memory.update(state, action, reward, next_state)</pre><p>max(1) returns the maximum element along the 1st axis and [1] returns the 1st element of the torch Tensor: the index of the maximum element.</p><p>It’s trivial to extend this code to run on a loop for a continuous number of frames.</p><p>The final piece of DQN is to train the model on past experiences after every step.</p><pre>def update_model(model, target_model, memory):<br>    # Get a sample of Transitions<br>    samples = memory.sample(32)<br>    # Turn it into a Transition of samples<br>    samples = Transition(*zip(*samples))</pre><pre>    # Get rewards    <br>    rewards = torch.cat(samples.reward)</pre><pre>    # Find indices of non-final states<br>    non_terminal_indices = torch.tensor(tuple(map(lambda s: s is not      None, samples.next_state)))</pre><pre>    # Get the non-final states<br>    next_states = torch.cat([ns for ns in samples.next_state if ns is not None])</pre><pre>    # Get highest Q values of next states<br>    max_q = target_model(next_states).max(1)[0].detach()            </pre><pre>    # Targets are rewards + Q values (for non-final states)<br>    additional_qs = torch.zeros(32)<br>    additional_qs[non_terminal_indices] = max_q<br>    y = rewards + additional_qs.unsqueeze(1) * gamma</pre><h3>Double DQN — The Basics</h3><p>Published shortly after DQN, Double DQNs attempt to minimize the problem of over-estimating Q values, caused by max operators in the target values.</p><p>The Double DQN introduces a very simple change to the target values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*LaNZTQ1zfI9SUEz6GA_qig.png" /></figure><p>Notice that we use the primary model to select the best action, and then the target model to evaluate the reward. This decoupling of actions and values leads to a significant reduction in value estimation error.</p><p>A trivial change to implement for a significant performance boost!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*WvFMf8BOfDWG5goe92ONZg.png" /><figcaption>van Hasselt, Guez, Silver (2015)</figcaption></figure><h3>CartPoleSwingUp</h3><p>As stated earlier, we will be trying our Double DQN on the CartPoleSwingUp environment, the slightly more complex big brother of CartPole. In <em>SwingUp</em>, the pole starts by hanging down from the cart. The agent must move the cart two swing the pole into an upright position and then balance it as in CartPole.</p><p>This environment is not included in the gym, so we must use a custom implementation. I’ve <a href="https://github.com/TTitcombe/CartPoleSwingUp">created a version</a>, adapted from <a href="https://github.com/hardmaru/estool/blob/master/custom_envs/cartpole_swingup.py">hardmaru’s</a> (which is adapted from <a href="https://github.com/zuoxingdong/DeepPILCO/blob/master/cartpole_swingup.py">this version</a>), which has been given a discrete action space necessary for compatibility with DQN. I have also altered the reward function to only yield a positive reward when the pole is within 60 degrees of upright and to yield sparse rewards to allow reward clipping; these changes have also removed the dependence of cart position on reward in order to release constraints on the solution.</p><h3>Results</h3><p>We run Double DQN on the CartPoleSwingUp environment, with a sliding replay memory containing 10&#39;000 memories, using a greedy epsilon policy in which epsilon anneals linearly from 1 to 0.1 over 10&#39;000 frames, and updating the target model every 1&#39;000 frames. After about 50&#39;000 frames, we achieve near-mastery of the environment, as you can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*cZAVPcCekfPP-8EQNylClQ.gif" /></figure><p>This model doesn’t take long to train even without a GPU, which demonstrates the benefits of having direct access to a lightweight state space compared to using rich image information.</p><p>While training, I attempted to keep the hyperparameters as close to the original paper’s as possible but scaling frame-number-related values, such as epsilon anneal, based on the relative complexity of the CartPoleSwingUp environment.</p><p>The original paper doesn’t go into much detail about how the values were selected: it merely notes that they were kept constant throughout the experiments, showing the robustness of the values to environment details.</p><p>I performed a quick investigation into the relative importance of the various hyperparameters by varying: the memory capacity; the number of frames epsilon was annealed over; the method for annealing epsilon; and the number of frames between target model updates. I additionally removed the memory initialization and ran an experiment with no frame skipping.</p><p>The following chart shows the episode rewards (smoothed over 50 episodes) against episode number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hA53GWN7nlWuqzd2Np_x3A.png" /></figure><p>The most striking feature of this graph is the catastrophic failure to learn if we keep the model continuously updated with the target model (“Frequent updates”, green line). Keeping the targets uncorrelated with the model is evidently a crucial factor in DQN’s success.</p><p>Unsurprisingly, only using information from a single frame (“Single frame”, purple line) also yields poor results: Without history, it’s impossible for the model to learn a concept of momentum, vital to swinging the pole to the upright position. The local maximum you see around episode 100 is likely from the model learning to always shoot off to one direction: if it does it quickly enough, the pole will just raise high enough to get a small score.</p><p>This graph also demonstrates how memory contributes to a successful model (“Small memory”, orange line). Importantly, because CartPoleSwingUp is a simpler environment, it takes fewer memories to capture the state space than it would for an Atari agent; therefore, as the environment increases in complexity, memory capacity becomes more vital.</p><h3>Next Steps</h3><p>This has been a big step up from the last post — what we have implemented here has sparked the modern interest in reinforcement learning.</p><p>It was comforting to find the code not too difficult to implement: the several papers covering DQN neatly and clearly explain everything you need. The difficulty lies in finding the training parameters which lead to a stable — or at the very least acceptable — solution.</p><p>As we take on increasingly complex environments/challenges, it will soon become non-trivial to train the agents. For now, we are okay, but we will have to be far more efficient with our training process as we tackle Atari games.</p><p>In the next post, we will implement dueling DQN (DDQN) and Prioritised Experience Replay (PER) on an Atari environment — attempting to replicate results from the DQN papers!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9673e4349516" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/adventures-in-reinforcement-learning-ii-dqn-9673e4349516">Adventures in Reinforcement Learning II: DQN</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Toolbox: Black + Pre-commit]]></title>
            <link>https://medium.com/@t.j.titcombe/data-science-toolbox-black-pre-commit-e586e5044a38?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/e586e5044a38</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Tue, 06 Aug 2019 19:13:47 GMT</pubDate>
            <atom:updated>2019-08-06T19:13:47.961Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’ve just completed work on a large feature: you push your work and head off to take that much deserved tea break. When you come back, you see your builds have failed almost immediately. The code quality check has failed.</p><p>Many of us won’t have to work hard to imagine; it’s an all too common occurrence. The simple fact is that it’s too hard to detect every single trailing space, or even to keep track of all the code conventions you’re meant to be following.</p><p>In this post we’ll be using the Python package <a href="https://black.readthedocs.io/en/stable/?badge=stable">Black </a>to automatically format our code. We will then take away the pain of having to remember to manually run code formatting by adding a <a href="https://pre-commit.com/">pre-commit</a> hook.</p><h3>Black</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbycVK-2veijOocpbSKLuw.png" /><figcaption>+1 for good branding (source: <a href="https://github.com/psf/black">https://github.com/psf/black</a>)</figcaption></figure><p>“The uncompromising code formatter”. Black aims to bring bliss into a Python codebase by making clean, pretty code a one line reality.</p><p>To start, we install Black:</p><pre>pip install black</pre><p>Let’s test it on an ungodly piece of code:</p><pre>import os</pre><pre>import random<br>def myLongFunction(var_a, var_b, var_c, var_d, var_e, var_f, var_g):</pre><pre>    temp_var  = var_b*var_c + var_d*var_e<br>    another_temp_var    = [&#39;one&#39;,&#39;two&#39; ,<br>                             &quot;three&quot;]</pre><pre>    <br>    yet_another_variable=(5)</pre><pre>    return var_f    +var_g</pre><p>There is obviously a lot wrong with this code: bad variable names, unused variables, random spacing, to name but a few of the more heinous offences. We can easily <em>blacken</em> this code by running black . in a command prompt/terminal in the project directory.</p><p>Black automatically formats the code to:</p><pre>import os</pre><pre>import random</pre><pre><br>def myLongFunction(var_a, var_b, var_c, var_d, var_e, var_f, var_g):</pre><pre>    temp_var = var_b * var_c + var_d * var_e<br>    another_temp = [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]</pre><pre>    yet_another_variable = 5</pre><pre>    return var_f + var_g</pre><p>The more obvious changes are the empty lines between import statements and code blocks, using double-quotes, and removing redundant parentheses. It already looks better.</p><p>As good as Black is, it’s important to realise it does not fix bad code for you, only badly formatted code. The unused variables remain, as do the unhelpful variable names. This example demonstrates that, while Black should be a key tool in your arsenal, it shouldn’t be the only one.</p><p>It’s an opinionated formatter, which means very little configuration, if any, should be required to get Black to work well on your project. Being opinionated, however, leads to the odd clash of heads; for example, Black has a default line-length of 88 characters, 8 more than commonly used.</p><p>If you do want to configure Black, you can add to a pyproject.toml file in your project root.</p><pre><strong>[tool.black]</strong><br>line-length = 80<br>target_version = [&#39;py37&#39;]<br>include = &#39;\.pyi?$&#39;<br>exclude = &quot;exclude_dir/&quot;</pre><p>This code snippet sets the line-length to 80 and tells Black to expect python 3.7 code. Additionally, we can specify which files to include or exclude from Black’s uncompromising gaze.</p><h3>Pre-commit</h3><p>Black is great, but being required to run black . every time you make a change isn’t. Enter pre-commit.</p><p>Pre-commit allows us to easily add hooks onto our git commits — that is to say, automatically run tasks on a git commit.</p><p>With pre-commit, we can perform actions such as black or flake8 linting on the files in a git commit. While there is a little bit of setup required to create a hook from scratch, most of the key use-cases, including Black, provide ready-made hooks.</p><p>To use pre-commit, we first install it via pip:</p><pre>pip install pre-commit</pre><p>We need a .pre-commit-config.yaml file in the project root. We can collect useful hooks with which to fill the config file from the documentation of popular packages and tools, such as Black. After doing so, our config file looks like this:</p><pre><strong>repos</strong>:<br>  - <strong>repo</strong>: https://github.com/ambv/black<br>    <strong>rev</strong>: stable<br>    <strong>hooks</strong>:<br>    - <strong>id</strong>: black<br>      <strong>language_version</strong>: python3.7</pre><p>Run pre-commit install and we’re all set-up. The next time you make a commit, you should be see Black automatically run. If your poorly formatted code does anger Black, it will automatically be corrected. You will have to re-add/re-commit, however.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2yvazx4MMX_5AtNFsW36g.png" /></figure><h3>To Conclude</h3><p>In a few lines of set-up, we’ve combined two packages to massively reduce the pain of maintaining high quality code.</p><p>All comments and questions are much appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e586e5044a38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning with Docker]]></title>
            <link>https://medium.com/@t.j.titcombe/reinforcement-learning-with-docker-789aa556504b?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/789aa556504b</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Wed, 31 Jul 2019 18:49:35 GMT</pubDate>
            <atom:updated>2019-07-31T18:49:35.520Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever had a problem on your system which refuses to be resolved by several fixes others have proclaimed their saviour? This is due in part to the complexity of modern computers: whether it’s the high-res image of Mr. Bean you use as a wallpaper, the Microsoft Publisher you still have installed for some reason, or the ever-so-slightly outdated OS patch, your system just isn’t in the same state as that of the fix’s author or the people who claim it worked. Therefore, the “fix” does not act in the same way on each machine.</p><p>Docker, and containerisation in general, is an attempt to remedy this problem by creating <a href="https://www.docker.com/resources/what-container">easily deployable <em>containers</em></a>, pre-loaded with all the bells and whistles required for the task at hand. Unlike virtual machines, which install a guest OS on your system, containers are lightweight and quick to develop and set-up.</p><p>Docker is being used by the computing community for all manner of tasks, from setting up environments for the test server to deploying a system into production. It’s an ideal technology for situations which require reproducible, complex environments.</p><p>For example, I’ve spent countless hours setting up gpu-enabled TensorFlow and OpenAI gym for my machine. These hurdles must be overcome in order to write a single line of a reinforcement learning agent. Clearly, machine learning needs to be containerised.</p><p>In this post we’ll be using Docker to remove a bit of the pain out of setting up an environment for reinforcement learning. The image we create will allow us to quickly start training reinforcement learning agents in OpenAI gym with Pytorch, without dirtying our machine’s own environment.</p><p><em>Note: While we can use monitors to record an episode, the image is currently not capable of live rendering of the environment (while rendering slows down training, I understand why it would be desirable). The image is still useful, but I will update this post once rendering is enabled.</em></p><h3>Creating the Image</h3><p><em>Before following on, it’s I highly recommend reading </em><a href="https://docs.docker.com/get-started/"><em>Docker’s introductory tutorials</em></a><em>, just to understand the terminology.</em></p><p>To set-up a Docker container, you need an <em>image</em>. To create the image, you need a <em>Dockerfile</em>. Dockerfiles outline the steps which must be taken to set-up the container; this can be packages to install, a directory structure to create, or what processes should be run automatically on launch.</p><p>In our Dockerfile we will use a python 3.7 image as a base, which comes with all the important python tools.</p><pre>FROM python:3.7</pre><p>Next, we need to install dependencies. Each group of environments (classic control, box2d, Atari etc.) are built in a different way and so have their own requirements. For box2d, we install curl, swig, and cmake. To record and render, we need xvfb, ffmpeg, python-opengl, among others.</p><p>We begin this by updating the linux system with <strong>apt-get </strong>because the python image may not be up to date.</p><pre>RUN apt-get update \<br>    &amp;&amp; apt-get install -y --no-install-recommends \<br>       apt-utils \<br>       build-essential \<br>       curl \<br>       xvfb \<br>       ffmpeg \<br>       xorg-dev \<br>       libsdl2-dev \<br>       swig \<br>       cmake \<br>       python-opengl</pre><p>Once the linux system dependencies are in place, we need to install the python dependencies. The primary packages are gym and Pytorch, but we include some additional data science packages which may be useful for developing RL agents, such as pandas and matplotlib.</p><pre>RUN pip3 install –upgrade pip</pre><pre>COPY requirements.txt /tmp/</pre><pre>RUN pip3 install –trusted-host pypi.python.org -r /tmp/requirements.txt</pre><pre>RUN rm /tmp/requirements.txt</pre><p>We end this segment by removing the temporary requirements file — this won’t be needed by anyone using the built image.</p><p>The final step is to set the <strong>ENTRYPOINT</strong> of the container. This is a command which is executed whenever the container is run. In a standard application we can leave this blank; developers can then choose how they want to use it. For example, they can run their container with the command /bin/bash , which launches the bash shell, or with python to go straight into the python interpreter.</p><p>Our application is complicated slightly by the need to run certain commands every time we run a container in order for recording of environments to be enabled. We <em>could</em> put the commands in a bash script and copy it over to the image, but ideally users should not be required to remember to run it.</p><p>We begin this functionality by putting the relevant commands in a bash script and setting the script as the ENTRYPOINT.</p><pre>ADD startup_script.py /usr/local/bin/startup_script.py</pre><pre># Give execution permissions<br>RUN chmod 777 /usr/local/bin/startup_script.py</pre><pre>ENTRYPOINT [&quot;/usr/local/bin/startup_script.py&quot;]</pre><p>However, Docker requires containers to be run <em>with a command</em>. Once that command has finished executing, the container stops running; this means that, if we left the script as-is, we could run no useful commands on the container.</p><p>To allow users to actually, well, use the container, we augment the startup script to either enter into the bash shell at the end or run a user provided command.</p><pre>#!/bin/bash<br>Xvfb :1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset &amp;&gt; xvfb.log &amp;</pre><pre>export DISPLAY=:1</pre><pre>if [$# -eq 0 ]<br>  then <br>    /bin/bash<br>else<br>  $1<br>fi</pre><p>For example, if we wanted to go straight into the python interpreter, we could use docker -it run image_name python . In this case, we have an optional argument ($1 , the first argument, is python ) so the else statement is executed, in which we just run $1 . On the other hand, if we ran docker run -it image_name we don’t have any optional arguments, so the if evaluates to true and we run /bin/bash to enter the bash script.</p><h3>Deploying the Image</h3><p>The image has been pushed to <a href="https://hub.docker.com/search/?type=image">DockerHub</a> and can be locally retrieved with docker pull ttitcombe/rl_pytorch:latest. Alternatively, if you wish to make your own changes you can <a href="https://github.com/TTitcombe/docker_openai_gym">clone the repository</a> and build the image with docker build --tag=my_image_name . . Confirm the image is present by listing docker images, docker image ls.</p><p>To deploy our reinforcement learning environment, we must create a container. Containers are built on an image and are the contained environment from which we run our programs.</p><p>We can create a container and enter its bash shell, the linux equivalent of <strong>cmd</strong>, with docker run -it --name=rl_container ttitcombe/rl_pytorch:latest. This should produce a screen as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*KDeqoC4KLkSSnzSxaqZuWQ.png" /></figure><p>The screen you are seeing is a window into the container’s linux system. From here we can create and move files, enter the python interpreter and run programs, just as we can in the command prompt or ubuntu terminal. This can be a useful way to access a container if we want to develop our code within the container before running it.</p><p>An alternative way to operate is to code in your host system and copy the files to the container with docker cp path/to/file/script.py rl_container:path/to/dest/script.py. We can then run the script with docker run -it --name=rl_container ttitcombe/rl_pytorch:latest “python path/to/dest/script.py&quot;. On that command the container will run the python script in the container and automatically exit once it has finished; we could then extract files the script generated using Docker’s <strong>cp</strong> command.</p><p>This is an ideal solution if you need a hands-on way to train agents which is not possible on your own system. For example, I have been unsuccessful at installing Box2d OpenAI gym environments on my Windows laptop, so I can use the container to train on the LunarLander environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LIVZc5Uq-8h3w7wXHY6uIw.gif" /><figcaption>A random agent playing LunarLander on our Docker container!</figcaption></figure><h3>Testing the Image</h3><p>An oft-neglected part of machine learning, automated unit testing is crucial to ensuring the system works as we expect. To test the Docker Image we’ve setup <a href="https://travis-ci.com/">Travis-CI</a>, a cloud-based continuous integration tool which is free to use for open source GitHub projects.</p><p>The test script begins by installing docker:</p><pre>dist: xenial</pre><pre>services:</pre><pre>    - docker</pre><p>We begin our test with the basics: checking that the image builds. By running this step in <strong>install</strong>, the build will not continue if it fails; in <strong>script</strong>, the test can continue after failed steps, which would be a pointless exercise in the case of an unbuilt image.</p><pre>jobs:</pre><pre>  include:</pre><pre>      - stage: “Test Docker Image”</pre><pre>        install:</pre><pre>          - docker build –tag=test_image .</pre><p>Once this has been confirmed to work, we move onto the main test script. We start by starting a container and confirming that it is running.</p><pre>        script:</pre><pre>          - docker run -it -d –name=test_container test_image</pre><pre>          - docker ps | grep -q test_container</pre><p>The first line in the script launches a container called <em>test_container</em>. The second line checks that the list of running containers, docker ps , contains the word test_container.</p><p>Next, we test the functionality of the container itself. This container is fairly simple — it’s main job is to build and run OpenAI gym environments. We’ve written a python test script using <strong>unittest</strong> to check that certain environments can be run.</p><pre>import gym<br>import torch  # this confirms that PyTorch is included<br>import unittest</pre><pre>class TestImage(unittest.TestCase):</pre><pre>  def test_can_make_classic_control_env(self):<br>    gym.make(“CartPole-v1”)</pre><pre>  def test_can_make_box2d_env(self):<br>    gym.make(“LunarLander-v2”)</pre><pre>  def test_envs_can_be_recorded(self):<br>    env_to_wrap = gym.make(&quot;CartPole-v1&quot;)<br>    env = gym.wrappers.Monitor(env_to_wrap, &quot;tmpFolder&quot;)<br>    env.reset()<br>    env.step(0)<br>    env.close()<br>    env_to_wrap.close()</pre><pre>if __name__ == “__main__”:<br>  unittest.main()</pre><p>We run this script <em>within the container</em>. A failing test will point out which environments were unsuccessfully loaded, helping us to track down the packages which were not installed correctly.</p><pre>- docker cp test/test_image.py test_container:/tmp/test_image.py</pre><pre>- docker exec -it test_container python /tmp/test_image.py</pre><p>Thanks to Travis-CI, we get automatic and quick feedback as to the health of our image whenever we open a PR.</p><h3>Next Steps for the Image</h3><p>This has been a rapid tour of using Docker for machine learning. It’s obviously not exhaustive and there are many ways this image could be improved: including <a href="https://gym.openai.com/envs/#mujoco">MuJoCo</a> environments, for example. I do plan on expanding the image to work with the full suite of gym environments and setting up rendering.</p><p>As this short article hopefully shows, Docker is a powerful technology which could transform the ease with which machine learning development can occur. There is much I still have to learn about it, but it is exceedingly simple to create a basic development container and the short time investment is well worth the possible utility.</p><p>For me, the need the develop this image came from the difficulty I had setting up Box2D gym environments. I’m currently undertaking a personal reinforcement learning curriculum and this image opens up the door to a wider variety of challenges — <a href="https://medium.com/@t.j.titcombe/adventures-in-reinforcement-learning-i-spinning-up-6f0c26a9b507">you can follow my progress here</a>.</p><p>Finally, check out the code for the <a href="https://github.com/TTitcombe/docker_openai_gym">Docker image here</a>. All comments and suggestions are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=789aa556504b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventures in Reinforcement Learning I: Spinning Up]]></title>
            <link>https://medium.com/@t.j.titcombe/adventures-in-reinforcement-learning-i-spinning-up-6f0c26a9b507?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f0c26a9b507</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[openai-gym]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Sun, 21 Jul 2019 14:04:22 GMT</pubDate>
            <atom:updated>2019-07-21T14:04:22.856Z</atom:updated>
            <content:encoded><![CDATA[<p>The last couple of years have seen dramatic progress for reinforcement learning, with various research groups hitting a series of headline-dominating milestones: <a href="https://deepmind.com/research/alphago/">beating the world champion Go player</a> showed that we can navigate an incomprehensible state space; <a href="https://openai.com/five/">beating world champion Dota II players</a> showed that our existing techniques can learn cooperation and complex strategy; and <a href="https://eng.uber.com/go-explore/">solving Montezuma’s Revenge</a> has demonstrated an ability to explore complex environments.</p><p>Don’t be tricked, however, into thinking these milestones only serve to further our ability to play video games: these algorithms will be crucial to solving a diverse field of problems, from <a href="https://deepmind.com/blog/alphafold/">protein folding</a> to city planning.</p><p>Despite the undoubtable importance of reinforcement learning (RL) to our future lives, I don’t have much experience in its techniques. I want to change that.</p><p>I’m embarking on an exploration of the key developments in reinforcement learning of the past few years, working my way through the algorithms and challenges which have driven this field forward. To set a slightly more concrete target than <em>“learn things”</em>, I aim to finish this adventure by implementing a lightweight version of <em>AlphaGo</em>,<em> </em>capable of beating me at chess.</p><h3>Getting Started</h3><p>Before we can implement anything, we need to get an RL environment up and running. The go-to set of tasks for any budding reinforcement learning engineer can be found in <a href="https://gym.openai.com/"><em>OpenAI gym</em></a>. <em>Gym</em> is a python package which neatly wraps up several <em>environments</em> of varying difficulty, easily providing your RL <em>agents </em>with states and rewards — the rough equivalent of the training data and labels you would use in a supervised learning task.</p><p>Unfortunately for many of us (including me), despite OpenAI’s missions statement being to ensure AI benefits of all humanity, they don’t make their tools easily available for the operating system used by the majority of humanity. <em>Fortunately for us</em>, we’re not the first people to face this problem. I strongly suggest Windows users check out <a href="https://towardsdatascience.com/how-to-install-openai-gym-in-a-windows-environment-338969e24d30">this article</a> on setting up gym; I could get everything working except Box2D — we’ll tackle this problem at a later stage. For the rest of you, it should be a trivial process of following <a href="https://gym.openai.com/docs/">OpenAI’s documentation</a>.</p><h3>The First Algorithm</h3><p>Now that we’ve setup our learning environment, we’ll ease into RL by implementing one of the simplest algorithms around: random search. We’ll start by working on the <em>CartPole</em> task, in which we must balance a pole upon a cart by applying a constant force in one of two directions.</p><p>Our agent will be a small neural network, which takes the four state values of the environment (cart position, cart velocity, pole angle, pole velocity at tip) as input, passes it through a single hidden layer, and contains two output nodes, corresponding to the two possible actions. We choose the action with the greatest value.</p><pre>import numpy as np</pre><pre>class BasicNet:<br>    def __init__(self, input_size, hidden_size, output_size):<br>        self.input_layer = np.random.normal(0, 10., size=(input_size, hidden_size))<br>        self.output_layer = np.random.normal(0, 10., size=(hidden_size, output_size))</pre><pre>    def __call__(self, data):<br>        hidden = self.relu(np.matmul(data, self.input_layer))<br>        return np.matmul(hidden, self.output_layer)</pre><pre>    @staticmethod<br>    def relu(data):<br>        return np.maximum(data, 0, data)</pre><p>We search for an optimal network by drawing each weight from a normal distribution. We’ll keep going until we achieve a score of 500, the highest score possible.</p><pre>def play(model, env):<br>    state = env.reset()<br>    is_done = False<br>    score = 0.</pre><pre>    while not is_done:<br>        actions = model(np.array([state]))<br>        action = np.amax(actions, dim=1)<br>        state, reward, is_done, _ = env.step(action)<br>        score += reward</pre><pre>    return score</pre><pre>import gym</pre><pre>env = gym.make(&quot;CartPole-v1&quot;)</pre><pre>for iteration in range(10000):<br>    model = BasicNet(4, 100, 2)<br>    score = play(model, env)<br>    if score == 500:<br>        print(&quot;Achieved the max score after {} searches&quot;.format(iteration))<br>        break</pre><p>As you will see, CartPole is a simple enough task that we can randomly stumble upon a basic neural network capable of “solving” it.</p><h3>Showing Off</h3><p>Feedback is important and waiting for the algorithm to run behind-the-scenes is neither informative nor interesting. We end this post by saving a video of our model in action. This will be important going forward, as we will want to check if our agents are learning any bizarre behaviour, or are getting stuck in locally optimal solutions.</p><p>To do this, we first wrap the environment in a <em>Monitor </em>before playing as before.</p><pre>env_to_wrap = gym.make(&quot;CartPole-v1&quot;)<br>env = gym.wrappers.Monitor(env, &quot;random_search_CartPole&quot;)</pre><pre>play the environment</pre><pre>env.close()<br>env_to_wrap.close()</pre><p>Finally, we convert this to a gif using <a href="https://ffmpeg.org/">ffmpeg</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*XkqoePt9I_rtAnu-iIKa_Q.gif" /><figcaption>A wobbly, but successful, CartPole-playing agent.</figcaption></figure><h3>Next Steps</h3><p>This algorithm is hardly efficient, and is so unintelligent as to not really be reinforcement learning at all. That’s okay; this was, after all, an introduction. In the next post we will get into RL-proper by implementing <em>deep Q learning </em>on the custom <em>CartPoleSwingUp</em> environment.</p><h3>Resources</h3><p>Here are some of the resources I’m using/ will use to learn reinforcement learning:</p><ul><li><a href="https://spinningup.openai.com/en/latest/spinningup/keypapers.html">OpenAI’s key papers</a></li><li><a href="https://mitpress.mit.edu/books/reinforcement-learning-second-edition">Sutton and Barto</a></li><li><a href="https://twitter.com/hardmaru?lang=en">Following hardmaru on twitter</a> to stay up to date with RL developments</li><li><a href="https://eng.uber.com/category/articles/ai/">UberAI blog</a></li><li><a href="https://deepmind.com/blog/">DeepMind blog</a></li><li><a href="https://openai.com/blog/">OpenAI blog</a></li></ul><p>I’ll add to this list as I discover more resources.</p><p>I hope you’ve enjoyed this initial foray into reinforcement learning. Please don’t hesitate to get in touch with questions or comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f0c26a9b507" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualising Elections with Python]]></title>
            <link>https://medium.com/data-science/visualising-elections-with-python-4973c0c60bbe?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/4973c0c60bbe</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[elections]]></category>
            <category><![CDATA[brexit]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Sun, 02 Jun 2019 15:20:43 GMT</pubDate>
            <atom:updated>2019-06-07T07:03:21.319Z</atom:updated>
            <content:encoded><![CDATA[<p>It would be fair to say that the global political landscape has a lot going on right now, whether you’re <a href="https://www.nytimes.com/interactive/2019/us/politics/2020-presidential-candidates.html">American</a>, <a href="https://www.nytimes.com/2019/05/30/world/middleeast/israel-elections-netanyahu.html">Israeli</a>, Venezuelan, or anything in-between (as a Brit, I have my own hellscape to endure, in the form of Brexit). Regardless of the nuances of any political situation, one thing they all have in common is the wealth of <strong>diverse, complex data</strong> they produce, waiting to be explored. For example, consider what you might need to know to perfectly predict an election night performance: comprehension of manifesto <strong>policies </strong>and their consequences; a <strong>psychological </strong>understanding of how people will react to the policies and the politicians; <strong>sociological </strong>knowledge of demographic shifts and how people vote as a community; and <strong>game theory</strong> to predict how people will vote under the given system.</p><p>But before all of that, a would-be political scientist must be able to capture and visualise the mood of the people. In this post, we will be taking that first small step towards election night supremacy, by plotting an election map of the UK.</p><p>Such maps, formally known as <strong>choropleth </strong>maps, come in many flavours. I will detail how I used Python to create two types of choropleth maps: <strong>geographically realistic</strong> maps of the UK, and <strong>hex maps</strong>, as seen below. Analysis of the visualisations created here will be covered in a further post. The code used to generate the maps can be seen on <a href="https://github.com/TTitcombe/ConstituencyMap/">my Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*xESZA2x4BlQz1ganLiIT_w.png" /><figcaption>A giant election map on the BBC piazza. I’ve opted for a slightly higher-tech approach.</figcaption></figure><h4>Creating Geographical Maps</h4><p>To create a basic choropleth of the UK, I opted to use the Python package <a href="http://geopandas.org/"><strong>GeoPandas</strong></a>, which extends Pandas to work with geospatial data.</p><p>GeoPandas makes it trivial to plot a map using a <strong>shapefile</strong>, a popular format for GIS data. Luckily for those attempting to map the UK, maps divided into constituencies — the UK’s voting boundaries — are made freely available by the <a href="https://geoportal.statistics.gov.uk/datasets/westminster-parliamentary-constituencies-december-2017-generalised-clipped-boundaries-in-the-uk">Office of National Statistics</a>. Just download the map of whichever granularity you choose as a shapefile from the site.</p><p><em>Note: shapefiles consist of several individual files, which contain separate information. You need to keep all the files which are provided in the zip folder.</em></p><p>To load and plot the shapefile in GeoPandas:</p><pre>import geopandas as gpd<br>import matplotlib.pyplot as plt</pre><pre>map_df = gpd.read_file(&quot;uk_generalized_2015.shp&quot;)<br># map_df is a Pandas dataframe</pre><pre>f, ax = plt.subplots(1, figsize=(6, 6))<br>ax = map_df.plot(ax=ax)<br>ax.set_axis_off()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*8nx_HO15oMFwO3_c_JbNYw.png" /><figcaption>Sorry, Northern Ireland.</figcaption></figure><p>As we can see, GeoPandas turns the shapefile into the dataframes we all know and love.</p><h3>Adding some zest</h3><p>We have started off well, but the map looks quite uninteresting. We now need to get hold of some constituency-level variable by which we can colour the map.</p><p>For the purposes of this post we’ve decided to use the percentage of the electorate who signed the petition to <em>Revoke Article 50</em>. A brief primer for those who were unaware: UK citizens can start petitions, through an official government website, which bind the government to debate the topic of the petition in parliament if a certain number of signatures are reached. In March 2019, a petition to revoke <strong>Article 50</strong>, the legal mechanism by which the UK leaves the EU, reached millions of signatures in just a couple of days.</p><p>Each petition is accompanied by a <strong>JSON</strong> which, among other things, breaks down the signature count by parliamentary constituency, thus we can easily plot a map to visualise the national mood on any petition. Before we can add this data to the dataframe, however, we need to convert the JSON to a csv.</p><pre>import csv<br>import json</pre><pre>file = &quot;petition_data.json&quot;<br>with open(file, &quot;r&quot;, encoding=&quot;utf-8&quot;) as json_file:<br>  data = json.load(json_file)<br>data = data[&quot;data&quot;][&quot;attributes&quot;][&quot;signatures_by_constituency&quot;]</pre><pre>keys = data[0].keys()<br>save_file = &quot;petition_data.csv&quot;<br>with open(save_file, &#39;w&#39;) as f:<br>  dict_writer = csv.DictWriter(f, keys)<br>  dict_writer.writeheader()<br>  dict_writer.writerows(data)</pre><p>Now we need to combine the data, and calculate the signature count as a percentage of electorate. Note that to do this we also need information on the size of the electorate in each constituency, data which can also be obtained on the <a href="https://www.ons.gov.uk/peoplepopulationandcommunity/elections/electoralregistration/datasets/electoralstatisticsforuk">ONS website</a>.</p><pre>import pandas as pd</pre><pre>data_df = pd.read_csv(&quot;petition_data.csv&quot;)</pre><pre># Combine the two dataframes by their constituencies<br>combined = map_df.set_index(&quot;pcon15nm&quot;)<br>           .join(data_df.set_index(&quot;name&quot;))<br>           .reset_index()</pre><pre># Also join the dataset containing electorate numbers<br># Not included here for brevity</pre><pre># Clean the data<br>combined[&quot;electorate&quot;].fillna(1e8, inplace=True)<br>combined[&quot;mp&quot;].fillna(&quot;No MP&quot;, inplace=True)<br>combined[&quot;signature_count&quot;].fillna(0, inplace=True)</pre><pre># Calculate the percentage votes<br>combined[&quot;signature_pc&quot;] = 100 * combined[&quot;signature_count&quot;] /           <br>                           combined[&quot;electorate&quot;]<br></pre><p>While the petition from which we retrieved this data was extremely popular, the maximum signature percentage of any constituency was only around 40%. We set the colourmap maximum to to this value, otherwise the majority of constituencies are shifted so far to one end of the colour spectrum as to be indistinguishable.</p><pre>fig, ax = plt.subplots(1, figsize=(6, 6))<br>combined_data.plot(column=&quot;signature_pc&quot;, cmap=&quot;viridis&quot;, <br>                   linewidth=0.8, ax=ax)<br>ax.axis(&quot;off&quot;)<br><br>vmin = 0.<br>vmax = 40.<br>sm = plt.cm.ScalarMappable(cmap=&quot;viridis&quot;, <br>                           norm=plt.Normalize(vmin=vmin, <br>                           vmax=vmax))<br>sm._A = []<br>cbar = fig.colorbar(sm)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*0UX6WA04pduSUCZMyd6vcw.png" /><figcaption>Overly large colourbars are in this year.</figcaption></figure><p>While it’s not the prettiest map you’ll ever see, it allows us to quickly and easily visualise the popularity of something throughout the country.</p><h4>Creating Hex Maps</h4><p>Looking at the above map, you would be forgiven for thinking that, because the petition only reached a high percentage of signatures in a few constituencies, it was, on the whole, unpopular. However, those of you familiar with the country may recognise the bright spot towards the bottom right of the map. That bright spot is London, and is home to several million people.</p><p>This perfectly demonstrates how maps plotting percentage, rather than absolute, popularity can mislead people when drawing conclusions. While maps such as these are great for demonstrating the geographic distribution of a thing, we are biased to lending more importance to larger regions.</p><p>Endeavoring to create unbiased visualisations, however futile this may ultimately be, we will now plot hex maps — maps in which each constituency is represented by an <strong>equally sized</strong> hexagon. These maps <strong>trade geographic realism</strong> for equalising the importance of each region of the map.</p><p>To begin, we need coordinates of each constituency hexagon. Because the sizes of regions are massively distorted in hex maps (in the UK, the smallest constituency is a single square mile, and the largest is over 4000), it will not be possible to align constituencies as you would on a more realistic map.</p><p>For this post, we get the base map from ODILeeds, who have created a fantastic tool to generate your own <a href="https://odileeds.org/projects/petitions/?241584">hex map of the UK.</a> Once you’re happy with the map, download the <strong>HexJSON </strong>and convert it to a CSV, as before.</p><p>Unfortunately, researching out-the-box ways to plot such maps in Python did not yield success: Matplotlib’s hexbin, while similar in intent, bins data points under the hood and proved too difficult to organise correctly. It became necessary to draw individual hexagons, for which Matplotlib Patches were used. Below is a simple example of how this can be achieved:</p><pre>from matploblit.patches import RegularPolygon<br>import numpy as np<br><br>d = 0.5 / np.sin(np.pi/3)  # radius of poylgon<br>o = 0.5 * np.tan(np.pi/3)  # orientation of polygon<br>y_diff = np.sqrt(1 - 0.5**2)  <br># difference in y location for consecutive layers<br><br>colors = [&quot;red&quot;, &quot;blue&quot;,&quot;green&quot;]<br>hcoord = [0.5, 0, 1]<br>vcoord = [y_diff, 0, 0]<br><br>fig, ax = plt.subplots(1)<br><br>for x, y, c in zip(hcoord, vcoord, colors):<br>    hex = RegularPolygon((x, y), numVertices=6, radius=d,<br>                         facecolor=c, alpha=0.2, edgecolor=&#39;k&#39;)<br>    ax.add_patch(hex)</pre><pre>ax.set_xlim([-0.5, 1.5])<br>ax.set_ylim([-0.6, 1.45])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*W-do4_RS9lj9UA3gOIcYIw.png" /><figcaption>Great maps, like great food, are built on honeycombs.</figcaption></figure><p>Before creating the full-UK map, one remaining challenge is to work out the coordinates of the hexagons: <strong>consecutive rows have an alternating start point</strong>, as is the nature of the honeycomb. The map provided by ODILeeds uses the “<strong>odd-r</strong>” formation, which means odd numbered rows contain the rightmost hexagons.</p><pre>def calc_coords(row, column):<br>  if row % 2 == 1:<br>    column = column + 0.5<br>  row = row * y_diff<br>  return row, column</pre><p>To create the UK, we iterate through the constituencies and draw a hexagon for each region. However, manually providing the colour, as above, would be a tedious task when attempting to create a smooth colourmap. We make use of <strong>PatchCollection</strong> to group the hexagons, and provide a Matplotlib colourmap to do the heavy, colourful lifting.</p><pre>from matplotlib.collections import PatchCollection</pre><pre>fig, ax = plt.subplots(1, figsize=(6, 6))<br>ax.axis(&quot;off&quot;)</pre><pre>patches = []<br>colours = []<br>for i in range(combined.shape[0]):<br>  # here, combined is a join of hex csv and petition data<br>  # creating combined has been omitted for brevity<br>  row = combined.loc[i, &quot;r&quot;]<br>  col = combined.loc[i, &quot;q&quot;]<br>  row, col = calc_coords(row, col)<br>  c = combined.loc[i, &quot;signature_pc&quot;]</pre><pre>hexagon = RegularPolygon((col, row), numVertices=6, radius=d, <br>                         edgecolor=&#39;k&#39;)<br>patches.append(hexagon)<br>colours.append(c)</pre><pre>p = PatchCollection(patches, cmap=plt.get_cmap(&quot;viridis&quot;), <br>                    alpha=1.0)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fR2-au0jtGteh6IgH87HWw.png" /><figcaption>Title and labels not included.</figcaption></figure><p>With this map, we can see the full extent of London and how it compares to surrounding areas. Knowing that constituencies have roughly similar populations, we can see much more clearly how widespread this petition was in the UK.</p><h4>Final Thoughts and Next Steps</h4><p>Beyond what’s shown in this post, I have used data taken from the <em>Revoke Article 50</em> petition at regular intervals to visualise the spread of the petition throughout the UK. The resulting maps can be seen on the <a href="https://github.com/TTitcombe/ConstituencyMap/">GitHub</a>. My <strong>sincerest thanks to Stuart Lowe</strong> at ODILeeds for collecting and providing the petition data.</p><p>While I would consider this a successful exercise in retrospect, the process of creating the hex map has convinced me that using exotic maps to visualise elections is not a job for which Matplotlib is well suited. If I or anyone reading this decides to create more complex maps, it would probably be necessary to look to other tools, such as <a href="https://d3js.org/">d3</a> or <a href="https://altair-viz.github.io/">altair</a>.</p><p>Unsurprisingly, the world of election coverage and analysis extends far beyond the scope of this post. There are a great variety of maps used to cover elections around the world, each one deployed to <a href="https://www.wired.com/story/is-us-leaning-red-or-blue-election-maps/">convey slightly different meaning</a>. However, the two types explored here could form the basis for quite informative political analysis.</p><p>After this project, I, for one, am looking forward to the next election in the UK, for a chance to make use of these maps, if nothing else. Until then, I’ll have to be satisfied with petitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vklLNLnYMByZJL8Y97Bcfg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4973c0c60bbe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/visualising-elections-with-python-4973c0c60bbe">Visualising Elections with Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Neural Arithmetic Logic Units]]></title>
            <link>https://medium.com/@t.j.titcombe/understanding-neural-arithmetic-logic-units-5ca9d0041473?source=rss-b24b8d417018------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ca9d0041473</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[nalu]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deepmind]]></category>
            <dc:creator><![CDATA[Tom Titcombe]]></dc:creator>
            <pubDate>Tue, 21 Aug 2018 19:26:45 GMT</pubDate>
            <atom:updated>2018-10-05T14:37:08.126Z</atom:updated>
            <content:encoded><![CDATA[<p>A <a href="https://arxiv.org/pdf/1808.00508.pdf">recent paper</a> from DeepMind researchers has introduced a new neural network module capable of <strong>counting objects</strong> and numbers and <strong>keeping track of time</strong>.</p><p>In this piece, we’ll found out why this is important, how it works, what they achieved, and finally recreate some of the experiments in the paper using TensorFlow. This first part covers the problem the paper set out to solve, and the novel contribution it made.</p><h3>The Problem</h3><p>Neural networks are great, aren’t they? Plug in some input data, give it appropriate target labels to match, and sit back as it learns to represent whatever function it needs to. But if you’ve ever trained your own nets, you may have noticed a little (really big) problem: if you test it on data outside the range you would find in the training data, it will perform poorly.</p><p>In this regard, it can be said that neural networks aren’t really <em>learning </em>the concepts which determine the output vector, they’re just memorising the question-answer responses you gave it. Then, when seeing a new data point, it’s mapped to the closest example found in training, and outputs the corresponding label.</p><p>An extreme example of this failure is in an auto-encoder which learns the identity function. This particular model is a neural network with 1 input data point, 3 hidden layers with 8 neurons each, and a single output neuron, where the target number is the same as the input number. This seems like an easy problem to solve, but with any of the common activation functions, the net works <em>okay </em>within the training range, but awfully outside of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*q1N8Dk_3pEUzOIxnqtZbUA.png" /><figcaption>Error of neural networks on a identity mapping task</figcaption></figure><p>This problem is clearly activation function-dependant. The authors note that the sharply non-linear functions perform the most poorly. While non-linear activation functions are key to neural networks’ success, it’s evident that, to be capable of tackling extrapolation, other types of layers are required.</p><p>Extrapolation is an important challenge for neural networks to overcome. After all, we extrapolate every single day of our lives: imagine you’ve just learned to read and explain pieces of TensorFlow code, say 100 lines long. Would you fall apart if I presented you with the same program, just spread over more lines? Even if you did, I’d wager you would perform less pitifully than a neural network would.</p><h3>The Solution — Addition and Subtraction</h3><p>The authors present two modules, capable of adding and subtracting quantities of numbers (neural accumulator — NAC), and multiplication, division, and powers (the eponymous neural arithmetic logic unit — NALU). Let’s start with the NAC.</p><p>Like most neural network layers, the NAC contains a weight matrix, <strong>W</strong>. This matrix, however, consists only of values equal to -1, 0, or 1. This means its outputs are simple linear combinations of the inputs, and does not subject them to arbitrary re-scaling.</p><p>Unfortunately, if we sharply constrain <strong>W </strong>to contain {-1,0,1} values, it would not be continuously valued, therefore non-differentiable. Consequently, we couldn’t learn what <strong>W</strong> should be via backpropagation. So, we’ll make <strong>W</strong> a learnable function (of course, we could try something other than backprop, but we’ll save that for another post). We define:</p><pre><strong>W</strong> = tanh(<strong>V</strong>) * sigmoid(<strong>M</strong>)</pre><p>Where <strong>V</strong> and <strong>M</strong> are two weight matrices. Both tanh and sigmoid are differentiable functions, so we can now learn <strong>W</strong>! But why this representation? You can see below an image of this function with two dimensional inputs. Importantly, it gets flat near -1,0,1 valued inputs. These are the <strong>stationary points</strong> of the function- using an update algorithm like gradient descent, any point will eventually be taken to the region of -1, 1, or 0. Once in one of these regions, it cannot escape easily due to the near 0 gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*zGuKsWttJWSh7A6c0zvqLg.png" /><figcaption>Thanks to <a href="https://imgur.com/a/vyfE2PQ">https://imgur.com/a/vyfE2PQ</a></figcaption></figure><h3>More Complex Functions</h3><p>Yeah, addition and subtraction are cool, but you know what’s really cool? Multiplication. Enter NALU. The NALU can learn multiplication in the exact same way as learning addition, using the simple trick of changing the input domain.</p><p>If you’re something of a mathematician, then you’ll know that additions of natural logarithms is equivalent to the natural logarithm of the product of the numbers.</p><p>ln(x) + ln(y) = ln(xy)</p><p>So if we take the log of the inputs, apply a NAC module, and then transform it back by taking the exponential, the inverse function of the natural logarithm, we can perform multiplication using only a weight matrix of 1s and 0s!</p><pre>exp(ln(a) + ln(b)) = exp(ln(ab)) = ab</pre><p>The complete NALU is comprised of one NAC for addition and subtraction, and the log-NAC-exp combination for multiplication and division. The outputs of these two parts are combined as:</p><pre><strong>y</strong> = <strong>g </strong>*<strong> a </strong>+ (1 - <strong>g</strong>)<strong> </strong>*<strong> m<br>g </strong>= sigmoid(<strong>Gx</strong>)</pre><p><strong>a</strong> is the addition module, and <strong>m</strong> the multiplication. <strong>g</strong> weights the output between the addition and multiplication modules.</p><p>Through these calculations, the NALU can learn functions consisting of addition, subtraction, multiplication, division. Modelling power function can be achieved by stacking layers of NALU modules. E.g Imagine a NALU which takes a single input to a 2 neuron hidden layer, and then a NALU which takes it back to a single value, where the multiplication weight matrices are all 1s (ignoring the addition matrices):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*_DTbeVdPPpz7LcmN98bmww.png" /></figure><p><em>Edit: </em><strong><em>g</em></strong><em> in the above image was a very poorly chosen variable. It merely represents the intermediate output of this stacked-NALU example. DON’T confuse it with </em><strong><em>g</em></strong><em> in the NALU module.</em></p><p>Interestingly, the NALU is comprised of a single NAC module — the multiplication and addition operations are performed by the same weight matrix. The authors introduced the weighting gate <strong>g </strong>to allow the NALU module to learn to do either multiplication or addition. Consequently, while a NALU could perform equally well on addition/subtraction tasks as NAC, it empirically performs worse because it <em>also </em>has to learn g perfectly to ignore multiplication. There may be local optima during training that allow NALU to perform well with some combination of addition and multiplication.</p><p>As far as I’m aware, the choice for a shared NAC cell was an empirical one — such models were found to train better than NALUs which used separate NACs for the different operations. The theory of why this is the case may make for interesting further research.</p><h3>Limitations of NALU</h3><p>While the log-nac-exp trick is a great way to perform multiplication of inputs in a differentiable manner, it limits the inputs to positive numbers as one cannot take the log of a negative number. Still, allowing a network to learn complex operations on half of all real numbers isn’t a bad start.</p><h3>Next Time</h3><p>In the next post we’ll look at the experiments made in the paper — showing how a NALU can learn to count sums of numbers it sees in images and how it can help a reinforcement learning agent learn to tell the time. We’ll then implement some of these ourselves.</p><p>Props to Andrew Trask, Felix Hill, Scott Reed, Jack Rae, Chris Dyer, and Phil Blunsom for a great paper!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ca9d0041473" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>