<?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 Peter Adam on Medium]]></title>
        <description><![CDATA[Stories by Peter Adam on Medium]]></description>
        <link>https://medium.com/@padam0?source=rss-e4afb73432fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RFqtqIibHluEWT-k.</url>
            <title>Stories by Peter Adam on Medium</title>
            <link>https://medium.com/@padam0?source=rss-e4afb73432fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:33:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@padam0/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[25 Weeks of Code]]></title>
            <link>https://medium.com/@padam0/25-weeks-of-code-f8305786950f?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8305786950f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[consulting]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 14:26:38 GMT</pubDate>
            <atom:updated>2019-01-29T14:26:38.923Z</atom:updated>
            <content:encoded><![CDATA[<p>17 months since my previous post, and about as long since I have really thought deeply about Data Science and coding. Back in September 2017 I had just handed in the <a href="https://hackernoon.com/a-year-in-business-analytics-at-ucd-smurfit-school-of-business-e4a151843aa2">Masters thesis</a> and was living in Dublin, Ireland waiting for my girlfriend’s contract to finish so we could move back to Australia. I was also job hunting, but without any really clear idea of what I wanted to do. I had applied for McKinsey &amp; Company’s Business Analyst position and similar roles, including a consulting position at Boston Consulting Group (BCG).</p><p>I interviewed with BCG the week before we left Ireland, flying down to London twice - the second time during a hurricane which left me 2 hours late for my interview 🤦🏼‍♂️ I ended up getting an offer as a Consultant in Perth, Australia. It was a ‘generalist’ position, meaning I wouldn’t be doing Data Science (or necessarily any analytics work) day-to-day, but have the opportunity to work alongside specialist data scientists and engineers as part of Gamma - BCG’s advanced analytics arm.</p><p>I knew that meant saying goodbye to a lot of the code and problem solving that I’d enjoyed during my Master’s, but the opportunity to work for one of the worlds best companies and solve problems at a really senior level was too good to pass up. I started in Feb 2018, and was immediately staffed on a 9-month long transformation (redesigning a company’s operating model).</p><p>For the most part, this project was tough (80 hour weeks were the norm) and between May and October I didn’t really have a chance to think outside of work. I did end up getting to deploy Python to solve some of our problems, like producing 100 personalised spreadsheets to go out to business leaders, and rolling them up when they came back. Not too complicated, but a good solution to a problem which otherwise would’ve been outsourced (with accuracy concerns) or done manually!</p><p>While the project almost killed me, I got to work with some amazing people and learned so much in those 9 months which has set me up for success at BCG. Subsequently, I’ve been involved in some more traditional analytics, using Alteryx to analysed the self-assessed capabilities of a 2000 person workforce and developing ‘no-regrets’ suggestions to get around the fact that the data was anonymised. This project was also MUCH more sustainable, and more representative of what life at BCG is like.</p><p>So, at the end of January 2019, I’m facing options around where to go from here. The Gamma arm of BCG has grown dramatically in Australia in the last year, and I’ve definitely got the itch to get involved at some stage in the future. My biggest concern is being out of touch with the kids, which is why I’m going to attempt my variation of the #100daysofcode challenge to get my skills fresh over the coming 6 months!</p><p>100 days in a row is pretty infeasible given the fluctuating demands of my job, so I figure an average of 4 hours a week is an achievable goal. I also want to work on projects rather than training courses, so I’ll be focusing more on my own ideas than prescribed curriculums like Datacamp or Codecademy. The driving force behind any time spent will be to develop my coding and solve business problems (however contrived the implementation).</p><p>First up, I want to revive ippe.ie, the property price prediction website I built (with <a href="https://twitter.com/Mcsweena">Andy McSweeney</a>) in 2016. It had a short-lived online presence, but we had a long list of features to build out. My initial product backlog:</p><ul><li>Re-deploy the site and get a reliable development — production server relationship going</li><li>Update the data displayed to 2019 and deploy a script to do this automatically every time the Irish property price register is updated</li><li>Retrain the model to use current data, and deploy a script to do this automatically every time the Irish property price register is updated</li><li>Build out an admin section of the site with some basic analytics and site management dashboards</li><li>Play around with some different scoring algorithms to give older prices a ‘decay-factor’</li></ul><p>And who knows after that! If there are any awesome courses / projects you’ve done or been wanting to try, drop me a response!</p><p>If you liked this post, please click and hold the 👏 button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0J8nrlZcxO4mBZdoiENgzg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8305786950f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A job ready Data Science curriculum]]></title>
            <link>https://medium.com/@padam0/a-job-ready-data-science-curriculum-74b9868e3290?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b9868e3290</guid>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Wed, 27 Sep 2017 08:42:36 GMT</pubDate>
            <atom:updated>2017-09-27T08:42:36.683Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently graduated from the <a href="http://www.smurfitschool.ie/programmes/masters/mscinbusinessanalytics/">MSc Business Analytics</a> at the UCD Michael Smurfit Graduate School of Business in Dublin, Ireland. Getting us from having little to no programming ability, to being entry-level data science candidates in a year was a great achievement for the course, and I thoroughly enjoyed my time (<a href="https://hackernoon.com/a-year-in-business-analytics-at-ucd-smurfit-school-of-business-e4a151843aa2">which you can read more about here</a>).</p><p>I’m moving back to Perth, Australia and have started the job hunt (<a href="https://www.linkedin.com/in/peteradam02/">hire me?</a>), and looking at job specs I realise there’s a many areas of analytics that we didn’t cover. I’ve also spoken to classmates who have already come into contact with topics they’re scrambling to learn.</p><p>While no curriculum can cater for every taste and whim, and while my course packed a lot into a year, I’ve been thinking a lot about what expansions / changes could be made that would produce my ‘ideal’ curriculum for Data Science, with the hope of producing the most ‘job ready’ graduates for jobs in Data Science, Data Strategy, Data Consulting, Business Analytics and Web Analytics, all areas requiring a similar skillset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dL-45k29jYybzTc2BfWBHg.png" /><figcaption><a href="http://www.skilledup.com/articles/list-data-science-bootcamps">Generic Data Science Image</a></figcaption></figure><h3>Semester One — The basics</h3><p>Units:</p><ul><li>Introduction to Programming</li><li>Statistics and Simulations</li><li>Project Management</li><li>Calculus</li><li>Numerical Analytics and Software</li></ul><h4>Introduction to Programming</h4><p>Introduce students to Python (or R) and SQL, and get quality up to a level where students are comfortable handling data with numpy and pandas, and understanding how to retrieve/edit data from databases. Very basic introduction to JavaScript, HTML and CSS.</p><h4>Statistics and Simulations</h4><p>Theoretical introduction to statistics and random sampling, up to parameter estimation and hypothesis testing. Practical applications using hacker statistics (simulation modelling).</p><h4>Project Management</h4><p>Agile IT project management discussion and critique. Understanding biases in collection and analysis of data. Git and collaborative software projects.</p><h4>Calculus</h4><p>Theoretical basis for understanding machine learning algorithms. Logic, linear algebra, matrices, vectors, differential calculus, optimisation.</p><h4>Numerical Analytics and Software</h4><p>Finite precision computing, algorithmic complexity, condition &amp; stability, systems of linear equations, optimisation, deeper discussion of certain in algorithms mathematical context (SVMs etc).</p><h3>Semester Two — Building the base</h3><p>Units:</p><ul><li>Introduction to Data Mining and Machine Learning</li><li>Big Data and Distributed Computing</li><li>Data Visualisation and Design</li><li>Research Methods and Analysis</li><li>Data Engineering and Strategy</li></ul><h4>Introduction to Data Mining and Machine Learning</h4><p>Theoretical and practical introduction to supervised and unsupervised learning using either R or Python. Understanding popular algorithms for regression, classification, clustering and association mining, as well as overfitting and parameter estimation.</p><h4>Big Data and Distributed Computing</h4><p>Introduction to Spark and Map/Reduce and their APIs. Practical experience setting up and managing cloud servers, as well as sample system of Raspberry Pi’s in class.</p><h4>Data Visualisation and Design</h4><p>Expand on introduction to JavaScript, and explore the Django web framework for dashboards. Data vis and design theory, as well as practical examples with D3. Introduction to geospatial visualisation with GMaps V3 and Leaflet.</p><h4>Research Methods and Analysis</h4><p>Understanding how to read and critique academic papers, and how to conduct a review of literature.</p><h4>Data Engineering and Strategy</h4><p>Business experience in how to identify and produce data collection, aggregation, and analysis plans, as well as how to deploy machine learning models in Django. Aim to give students an understanding of the business strategy behind data stacks. Introduction to Blockchain and other innovations with significant business impact.</p><h3>Semester Three — Advanced Topics</h3><p>Units:</p><ul><li>Network Analysis (Graph Theory)</li><li>Optimisation Problems</li><li>Natural Computing and Deep Learning</li><li>Web and Marketing Analytics</li><li>Real Time Analytics and IOT</li></ul><h4>Network Analysis (Graph Theory)</h4><p>Understanding graph theory and how network models can be evaluated using different metrics and optimised. <a href="https://medium.com/towards-data-science/utilising-epidemic-modelling-to-improve-advertising-click-rates-on-facebook-6f294205a43f">Focus on social network analysis</a>.</p><h4>Optimisation Problems</h4><p>Introduction to Linear and Integer Programming for optimisation in Python, and types of optimisation problems that can be solved at scale, including TSP, constrained optimisation and goal programming.</p><h4>Natural Computing and Deep Learning</h4><p>Introduction to the field of nature inspired algorithms, with a specific focus on neural networks using Tensorflow or Keras. Understanding the types of optimisation problems suited for such methods, and gain experience in deploying neural networks on machine vision problems.</p><h4>Web and Marketing Analytics</h4><p>Introduction to Google Analytics and other data gathering and analysis services which are available for websites and advertising. Explore marketing metrics and KPIs, along with algorithms for improving the efficiency of targeted advertising and an introduction to SEO.</p><h4>Real Time Analytics and IOT</h4><p>Understanding the challenges of dealing with a real time data flow from multiple sources, and the challenges this poses for outlier detection and analysis. Build solutions which can handle this constant flow of information in an appropriate manner.</p><h3>Semester Four-Dissertation or Practicum</h3><p>Single extended research or practical project to satisfy Masters level study requirements. Focus on messy, real world datasets to build data munging and complementary data collection skills</p><p>I’m interested to hear your thoughts, is there anything else that you’ve seen that employers are looking for, or from data scientists, what skills do graduate hires lack that could be taught at a Masters level?</p><p>If you liked this post, please click and hold the 👏 button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0J8nrlZcxO4mBZdoiENgzg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b9868e3290" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-clustering Google Maps Markers using KMeans in Django]]></title>
            <link>https://medium.com/@padam0/pre-clustering-google-maps-markers-using-kmeans-in-django-aeabc6eb2c0b?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeabc6eb2c0b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Sun, 03 Sep 2017 13:08:11 GMT</pubDate>
            <atom:updated>2017-09-03T13:08:40.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was attempting to display many (&gt;1000) markers on an interactive Google Maps V3 API, with marker clustering turn on, so that above a certain zoom level, markers would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*27tX9lsO_3RX2P-_lmjEbg.png" /></figure><p>instead of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*UGIAt3IUyhVIprLHOHkv1g.png" /></figure><p>Google makes this pretty easy, using the <a href="https://developers.google.com/maps/documentation/javascript/marker-clustering">MarkerClusterer</a> library. However, if you’re using a non-Javascript backend, it requires loading all of the points into the browser, and then clustering. This can take up a lot of bandwidth, and slow things down pretty badly. If only there was a way to do the clustering in the backend, and only send the cluster locations and size forwards?</p><p>After a lot of searching, I found a bit of an awkward solution, involving altering the MarkerClusterer library using code from <a href="https://stackoverflow.com/questions/4811042/manually-draw-a-cluster-with-markerclusterer-for-maps-v3">Stack Overflow</a>, and using SKLearn in Python to cluster the points. This dramatically reduced the amount of data being sent forward, and page load times (especially on very large numbers of markers).</p><p>All code is available for download on my <a href="https://github.com/Padam-0/KMeans-Marker-Clusterer">Github</a>.</p><p>The first step is to download the <a href="https://github.com/googlemaps/v3-utility-library/blob/master/markerclusterer/src/markerclusterer.js">markercluster.js</a> file and import it into the base HTML. Then take the following code and add it into the markerclusterer.js file (I did it starting at line 316):</p><pre>MarkerClusterer.prototype.AddCluster = function(<em>clat</em>, <em>clng</em>, <em>csize</em>) {<br>  // this.setZoomOnClick(false);<br>  if (typeof this.aAddClusterIcons == &quot;undefined&quot;){<br>      this.aAddClusterIcons = [];<br>  }<br><br>  this.activeMap_ = this.getMap();<br>  var clusterlocation = new google.maps.LatLng(<em>clat</em>, <em>clng</em>);<br>  var CI = new ClusterIcon(new Cluster(this), this.getStyles, this.getGridSize());<br>  var index = 0;<br>  var dv = <em>csize</em>;<br>  while (dv !== 0) {<br>      dv = parseInt(dv / 10, 10);<br>      index++;<br>  }<br>  var style = this.styles_[index-1];<br>  $.extend(CI, {sums_ : {text : <em>csize</em>, index: index}, url_ : style[&#39;url&#39;], width_ : style[&#39;width&#39;], height_ : style[&#39;height&#39;], averageCenter_: style[&#39;averageCenter&#39;], anchorIcon_: [<em>clat</em>, <em>clng</em>]});<br>  CI.setCenter(clusterlocation);<br>  CI.setMap(this.activeMap_);<br>  CI.show();<br><br>  this.aAddClusterIcons.push(CI);<br>};<br><br>MarkerClusterer.prototype.RemoveClusters = function(<em>clat</em>, <em>clng</em>, <em>csize</em>) {<br>  if (typeof this.aAddClusterIcons == &quot;undefined&quot;){<br>      this.aAddClusterIcons = [];<br>  }<br><br>  $.each(this.aAddClusterIcons, function(<em>iIndex</em>, <em>oObj</em>){<br>      <em>oObj</em>.onRemove();<br>  });<br>  this.aAddClusterIcons = [];<br>};</pre><p>Forgive the way that Medium formats code, but it’s best to do a straight copy-paste to get line spacing correct. Make sure the m_.png files are in a file called media at the same level as the HTML.</p><h3>AJAX and Django</h3><p>Lets assume that the markers are being refreshed using an AJAX call whenever the map is dragged or the zoom is changed. As part of the AJAX call, we’re sending to the back end the map boundaries and current zoom:</p><pre>function ajax_update_markers(){<br>    var r = <em>map</em>.getBounds().getNorthEast().lng();<br>    var l = <em>map</em>.getBounds().getSouthWest().lng();<br>    var t = <em>map</em>.getBounds().getNorthEast().lat();<br>    var b = <em>map</em>.getBounds().getSouthWest().lat();<br><br>    $.ajax({<br>        type: &quot;GET&quot;,<br>        url: &quot;/ajax-response-markers/&quot;,<br>        data: {&#39;right&#39;: r, &#39;left&#39;: l, &#39;top&#39;: t, &#39;bottom&#39;: b, &#39;zoom&#39;: <em>map</em>.getZoom()},<br>        async: true,<br>        dataType: &#39;json&#39;,<br>        success: function (<em>data</em>) {<br>            drawMarkers(<em>data</em>);<br>        }<br>    });<br>}</pre><p>In the view, we can first filter points by the constraints from the database (called Sale in this case, as it contains information on property sales):</p><pre><em>def </em>return_response_markers(<em>request</em>):<br>    top = <em>request</em>.GET[&#39;top&#39;]<br>    bottom = <em>request</em>.GET[&#39;bottom&#39;]<br>    right = <em>request</em>.GET[&#39;right&#39;]<br>    left = <em>request</em>.GET[&#39;left&#39;]<br><br>    database_list = Sale.objects.\<br>        filter(latitude__gte=bottom).\<br>        filter(latitude__lte=top). \<br>        filter(longitude__gte=left).\<br>        filter(longitude__lte=right)</pre><p>Then, if the zoom level is above a certain level, or there are not enough points in the view to warrant clustering, the data can be sent as usual. For me this value was under 2000, but I was using custom markers which were smaller and were still visually acceptable at higher zooms.</p><pre><em>from </em>django.core.serializers <em>import </em>serialize</pre><pre><em>if </em>int(request.GET[&#39;zoom&#39;]) &gt; 13 <em>or </em>len(database_list) &lt; 2000:<br>    result = serialize(&#39;json&#39;, database_list,<br>                   fields=(&#39;uid&#39;, &#39;latitude&#39;, &#39;longitude&#39;))</pre><pre>    return HttpResponse(result)</pre><p>Otherwise, KMeans could be used to cluster the markers into 40 clusters:</p><pre>cluster_data = {&#39;lat&#39;: [], &#39;lng&#39;: []}<br><br><em>for </em>point <em>in </em>database_list:<br>    cluster_data[&#39;lat&#39;].append(point.latitude)<br>    cluster_data[&#39;lng&#39;].append(point.longitude)<br><br>df = pd.DataFrame(cluster_data, columns=[&#39;lat&#39;, &#39;lng&#39;], index=<em>None</em>)<br><br>kmeans = KMeans(n_clusters=40).fit(df)<br>samples = kmeans.predict(df)<br><br>centroids = kmeans.cluster_centers_</pre><p>And a list of cluster centroids and size of clusters sent forwards:</p><pre>response_data = []<br><em>for </em>i <em>in </em>range(len(centroids)):<br>    response_data.append([centroids[i][0], centroids[i][1], len([j <em>for </em>j <em>in </em>samples <em>if </em>j == i])])<br><br>response = {&#39;data&#39;: response_data, &#39;cluster&#39;: &#39;true&#39;}<br><br><em>return </em>HttpResponse(json.dumps(response))</pre><p>That was fairly straightforward, we’ll do some optimisation later, but let’s look at the Javascript.</p><p>Our drawMarkers function takes the AJAX response, and first clears all current markers and clusters on the map:</p><pre>while(<em>current_markers</em>.length &gt; 0) {<br>    <em>current_markers</em>.pop().setMap(null);<br>}<br><br>if (<em>markerCluster</em>.aAddClusterIcons != null){<br>    while(<em>current_clusters</em>.length &gt; 0){<br>        a = <em>current_clusters</em>.pop();<br>        <em>markerCluster</em>.RemoveClusters(a[0], a[1], a[2]);<br>    }<br>}</pre><p>Then if clustering is required, uses the new methods added by the Stack Overflow code to draw these:</p><pre>if (<em>data</em>[&#39;cluster&#39;] == &#39;true&#39;){<br>    <em>cluster_data </em>= <em>data</em>[&#39;data&#39;];<br>    for (var i = 0; i &lt; cluster_data.length; i++){<br>        if (<em>data</em>[&#39;data&#39;][i][2] != 0) {<br>            <em>markerCluster</em>.AddCluster(cluster_data[i][0], cluster_data[i][1], cluster_data[i][2]);</pre><pre>            <em>current_clusters</em>.push([cluster_data[i][0], cluster_data[i][1], cluster_data[i][2]])<br>        }<br>    }<br>}</pre><p>Otherwise, adds the markers as normal:</p><pre>{ else {<br>    for(var i = 0; i &lt; <em>data</em>.length; i++) {<br>        var lat = parseFloat(<em>data</em>[i][&#39;fields&#39;][&#39;latitude&#39;]);<br>        var lng = parseFloat(<em>data</em>[i][&#39;fields&#39;][&#39;longitude&#39;]);<br><br>        var pos = new google.maps.LatLng(lat, lng);<br><br>        var marker = new google.maps.Marker({<br>            position: pos,<br>            map: <em>map<br>        </em>});<br><br>        <em>current_markers</em>.push(marker)<br>    }<br>}</pre><p>Finally, we add the map event listeners to the initMap() function and call ajax_update_markers() :</p><pre>google.maps.<em>event</em>.addListener(<em>map</em>, &#39;dragend&#39;, function () {<br>    ajax_update_markers();<br>});</pre><pre>google.maps.<em>event</em>.addListener(<em>map</em>, &#39;zoom_changed&#39;, function () {<br>    ajax_update_markers();<br>}</pre><pre>google.maps.<em>event</em>.addListener(<em>map</em>, &#39;idle&#39;, function () {<br>    ajax_update_markers();<br>});</pre><p>Again, all of this code is available on <a href="https://github.com/Padam-0/KMeans-Marker-Clusterer">Github</a>.</p><p>One word of caution, is that for some reason, turning ‘Zoom on click’ on for these clusters doesn’t zoom as expected, for some reason centres the view in the middle of the ocean nowhere near what was wanted. I looked into a lot of different workarounds for this, but couldn’t find anything that worked. It’s up to you and your application about the UX tradeoff between load times and this functionality.</p><h3>Optimisation</h3><p>This was working much better already, but are there tweaks to the clustering algorithm that can help us get even better results?</p><p>The first thing I looked at was choice of database. I originally used sqlite3, the Django default, and compared it to PostgreSQL. Information retrieval didn’t see much change between the two technologies, but information processing was quite different. Above 10,000 data points, functions like len(database_list) took up to 10 times longer when using sqlite3. I haven’t looked too much more into this, but it seems that Django plays a bit better with PostgreSQL than sqlite3.</p><p>Next were the KMeans parameters. Looking at the documentation <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html">here</a>, the parameters that control the speed/accuracy trade-off include:</p><ul><li><strong>n_init:</strong> Number of time the k-means algorithm will be run with different centroid seeds.</li><li><strong>max_iter: </strong>Maximum number of iterations of the k-means algorithm for a single run.</li><li><strong>tol: </strong>Relative tolerance with regards to inertia to declare convergence.</li><li><strong>n_jobs: </strong>The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel.</li></ul><p>The default values for these parameters usually give pretty good accuracy in an acceptable run time, but the truth is for this application we can probably accept a much lower accuracy. A 10% error in the number of points per cluster is hardly going to be noticed by the user, and all points are shown after the user zooms in anyway. After playing around with parameters, I realised that the clustering time could be reduced by half, and from a few test cases, I couldn’t see any errors in the final cluster locations or counts per cluster!</p><p>My final parameter choices were:</p><ul><li><strong>n_init:</strong> 1 vs a baseline of 10</li><li><strong>max_iter:</strong> 30 vs a baseline of 300</li><li><strong>tol:</strong> 1e-2 vs a baseline of 1e-4</li><li><strong>n_jobs:</strong> -1 (this made no difference on my local machine, but appears to work on the deployed clusters. As speed changes were recorded on my local machine, the impact is not included).</li></ul><p>All of these are drastic reductions, but it turns out that the KMeans algorithm is actually pretty good, and a lot of the parameter settings are redundantly high when accuracy is not the main concern. As for the speedup, a table of results is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVQu6q_ke6Qaa9vFtikNtA.png" /></figure><p>This is pretty remarkable, as speed ups of 2–3 times are seen by reducing the accuracy of the clustering, and even more when combining with PostgreSQL. There are definitely more efficiencies to be realised for this application, but this example shows what a dramatic effect understanding where on the accuracy / runtime curve you need to be, and prioritising your objective.</p><p>Again, all of the code is on my github. If you liked this post, please click and hold the 👏 button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0J8nrlZcxO4mBZdoiENgzg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeabc6eb2c0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Dropdown Alternatives]]></title>
            <link>https://blog.prototypr.io/implementing-dropdown-alternatives-568c6d3464ed?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/568c6d3464ed</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Sat, 19 Aug 2017 12:02:32 GMT</pubDate>
            <atom:updated>2017-08-29T06:36:58.594Z</atom:updated>
            <content:encoded><![CDATA[<p>A few weeks ago I came across <a href="https://medium.com/u/f65d13a73151">Zoltan Kollin</a>’s excellent article, <a href="https://medium.com/@kollinz/dropdown-alternatives-for-better-mobile-forms-53e40d641b53">Dropdown alternatives for better (mobile) forms</a>. As someone who’s quite new to web design, it was eye opening and I realised that my site had three unsightly dropdown menus which were impeding user access to information. A combination of techniques was required to replace them, and although I had the inspiration I needed from the above article, implementing them was not as straight foward.</p><p>Below is a recount of how I went from this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMLqzzx1hmFOrtObQGW0JQ.png" /></figure><p>to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdQ90yVgYdYY5c9tSnH_qg.png" /></figure><p>and removed my dependence on dropdown menus forever!</p><p>All the code is available in full on my <a href="https://github.com/Padam-0/dropdown-alternatives">Github</a>.</p><h3>Segmented Controls</h3><p>I found a CSS only example <a href="https://codepen.io/fstgerm/pen/Jafyj">here</a>, which was exactly what I needed, but unfortunately written in SCSS, which I wasn’t really familiar enough with to get working easily. Instead I checked out the page source, and found the implemented CSS file (which you can find <a href="https://github.com/Padam-0/dropdown-alternatives/blob/master/css/seg-control.css">here</a>), which with some trial and error I managed to adapt into something I could use.</p><p>Before we dive into discussing the CSS, we need to write some HTML. All segmented controls look something like this:</p><pre>&lt;<strong>div </strong>class=<strong>&quot;segmented-control&quot; </strong>id=<strong>&quot;sc1&quot;</strong>&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-1&quot; </strong>id=<strong>&quot;sc-5-1-1&quot; </strong>checked&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-1&quot; </strong>id=<strong>&quot;sc-5-1-2&quot;</strong>&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-1&quot; </strong>id=<strong>&quot;sc-5-1-3&quot;</strong>&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-1&quot; </strong>id=<strong>&quot;sc-5-1-4&quot;</strong>&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-1&quot; </strong>id=<strong>&quot;sc-5-1-5&quot;</strong>&gt;<br><br>    &lt;<strong>label </strong>for=<strong>&quot;sc-5-1-1&quot; </strong>data-value=<strong>&quot;Map&quot;</strong>&gt;<strong>Map</strong>&lt;/<strong>label</strong>&gt;<br>    &lt;<strong>label </strong>for=<strong>&quot;sc-5-1-2&quot; </strong>data-value=<strong>&quot;Radius&quot;</strong>&gt;<strong>Radius</strong>&lt;/<strong>label</strong>&gt;<br>    &lt;<strong>label </strong>for=<strong>&quot;sc-5-1-3&quot; </strong>data-value=<strong>&quot;County&quot;</strong>&gt;<strong>County</strong>&lt;/<strong>label</strong>&gt;<br>    &lt;<strong>label </strong>for=<strong>&quot;sc-5-1-4&quot; </strong>data-value=<strong>&quot;Region&quot;</strong>&gt;<strong>Region</strong>&lt;/<strong>label</strong>&gt;<br>    &lt;<strong>label </strong>for=<strong>&quot;sc-5-1-5&quot; </strong>data-value=<strong>&quot;Country&quot;</strong>&gt;<strong>Country</strong>&lt;/<strong>label</strong>&gt;<br>&lt;/<strong>div</strong>&gt;</pre><p>And that’s it! So the underlying input elements are radio buttons, the name must be unique for each segmented control on the page. Additionally, the first number in the id must be the number of options (in this case 5), the second number can be anything, but for clarity should generally match the name, and the final number must be unique for each input in the control.</p><p>For the labels, the data value is what is displayed when the input is selected, so capitalisation is necessary, and the ‘for’ value should match the id of the corresponding input. This will give us something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hdbc2xE2o1_-kIkS-oQjNg.png" /></figure><p>If we had a second control on the page, this time with 2 options, we would create it as such:</p><pre>&lt;<strong>div </strong>class=<strong>&quot;segmented-control&quot; </strong>id=<strong>&quot;sc2&quot;</strong>&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-2&quot; </strong>id=<strong>&quot;sc-2-2-1&quot;</strong>&gt;<br>    &lt;<strong>input </strong>type=<strong>&quot;radio&quot; </strong>name=<strong>&quot;sc-2&quot; </strong>id=<strong>&quot;sc-2-2-2&quot; </strong>checked&gt;<br><br>    &lt;<strong>label </strong>for=<strong>&quot;sc-2-2-1&quot; </strong>data-value=<strong>&quot;On&quot;</strong>&gt;<strong>On</strong>&lt;/<strong>label</strong>&gt;<br>    &lt;<strong>label </strong>for=<strong>&quot;sc-2-2-2&quot; </strong>data-value=<strong>&quot;Off&quot;</strong>&gt;<strong>Off</strong>&lt;/<strong>label</strong>&gt;<br>&lt;/<strong>div</strong>&gt;</pre><p>And get something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*QwXsmT3cte5mXeG2Mxy1Gw.png" /></figure><p>Ok, so now back to the CSS. The file itself is fairly generic, but a few lines are important to change.</p><p>The code on line 4 controls the styling of non-selected elements:</p><pre>.segmented-control {<br>    /*Controls the color of the non-selected elements*/<br>    <em>background-color</em><strong>: white;</strong><br>    ...</pre><p>The code on lines 189 and 190 controls the styling of non-selected text:</p><pre>.segmented-control &gt; label {<br>    <em>margin-bottom</em>: 0;<br>    <em>color</em>: rgb(5, 8, 78);</pre><p>The code on line 224 controls the styling of selected element text:</p><pre>.segmented-control &gt; label:after {<br>    <em>color</em>: white;</pre><p>And the code on line 256 controls the styling of selected elements:</p><pre>.segmented-control &gt; label:before {<br>    /*Controls the color of the current selection*/<br>    <em>color</em>: rgb(179, 38, 80);</pre><p>There are two more changes to make, which are slightly trickier, but thankfully unnecessary unless you’re using segmented controls with more than 5 options (at which point it’s worth exploring other choices).</p><p>Lines 52 to 186 control movement between options. You can see that lines 61 to 94 control how the slider moves between the 1st element, itself, and all others (and vice versa, from each element back to the 1st). Then lines 103 to 126 control the movement from the 2nd element to itself, the 3rd, 4th and 5th (not the 1st as this is already accounted for), and so on until the 5th element which only controlling its movement to itself. Adding more options requires adding information for each existing element to each new element, and each new element to itself and other new elements.</p><p>This is really just a copy paste job, but can become a bit fiddly when replacing numbers. You can see why people use SCSS!</p><p>Lines 270 to 279 have information for segments 1 through 5, and if you’re using additional elements, you’ll need to replicate these for 6 onwards. This is a matter of copying lines 278 and 279, pasting them at line 280, changing the 5&#39;s to 6’s, and the 20% to 16.66% (1/6). Then repeat this until all your options are accounted for.</p><p>And that’s it! Link the CSS to your HTML file, and you’ll have segmented controls doing this in no time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*9ViXf04PJIfScfIzV716mw.gif" /></figure><p>Beautiful! Now, onto Javascript, how do we get the current value, or the value when clicked?</p><p>This is a little more complicated, as there’s a difference between Chrome/Safari and Firefox, and click events in jQuery register twice.</p><p>First, if your users change the control, then click a different element to change some information based on the control, getting the value of the control in Chrome and Safari is a matter of:</p><pre>$(&quot;#sc1 input[type=&#39;radio&#39;]:checked&quot;)[0].labels[0].innerHTML</pre><p>This will return the value of the control with id sc1 . However, Firefox doesn’t like this, so to distinguish between the two, you can test with the following if statement:</p><pre>if ($(&quot;#sc1 input[type=&#39;radio&#39;]:checked&quot;)[0].labels == null){<br>    // Firefox<br>    <br>} else {<br>    // Chrome - Safari<br>    val = $(&quot;#sc1 input[type=&#39;radio&#39;]:checked&quot;)[0].labels[0].innerHTML;<br>}</pre><p>Note that testing for $(&quot;#sc1 input[type=&#39;radio&#39;]:checked&quot;)[0].labels[0] or $(&quot;#sc1 input[type=&#39;radio&#39;]:checked&quot;)[0].labels[0].innerHTML will not work, as Firefox will throw an error instead of null.</p><p>So when the browser is confirmed as Firefox, the following code will extract the id of the selected input:</p><pre>if ($(&quot;#sc1 input[type=&#39;radio&#39;]:checked&quot;)[0].labels == null){<br>    // Firefox<br>    var selector = document.getElementsByName(&#39;sc-1&#39;);<br>    for (var i = 0; i &lt; selector.length; i++) {<br>        //Check if button is checked<br>        var button = selector[i];<br>        if(button.checked) {<br>            //Return value<br>            id = button.id;<br>        }<br>    }<br>    if (id.slice(id.length - 1) == 1){<br>        val = &#39;Map&#39;<br>    else if (id.slice(id.length - 1) == 1){<br>        val = &#39;Radius&#39;<br>    else if ...</pre><pre>} else {<br>    // Chrome - Safari<br>    ...<br>}</pre><p>So the segmented control is selected by the name of the inputs ( sc-1 in this case), which are then looped over and the id of the current selected is returned. The last number in this id (the unique identifier) can then tell you which element is selected. This is pretty annoying, but after a lot of searching I couldn’t find a better way to get things to work on Firefox… Thanks Firefox ¯\_(ツ)_/¯</p><p>So if we add a button, we can now do cool stuff like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*4DiC6Qi8poHCEjsRgmgrqw.gif" /></figure><p>Sweet!</p><p>Now that’s all well and good if there’s an external button, but what if you want an event to happen when the segmented control is changed. Unfortunately, if we just add a click listener to get the current selection when the segmented control is clicked, it responds twice. First time getting the current value, then the value that was clicked. This is an issue especially when making AJAX calls, as things can get messy quickly.</p><p>So if we do something like this (the function getval() is the if statement above to ensure the control works with Firefox, see the whole thing <a href="https://github.com/Padam-0/dropdown-alternatives/blob/master/js/index.js">here</a>):</p><pre>$(&#39;#sc1&#39;)<br>    .click(function(){<br>        val = getval(&#39;sc1&#39;);<br>        console.log(val);<br>        $(&#39;#result&#39;).html(val);<br>});</pre><p>We get the result we want on the page, but watching the console we see something strange:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*XSWagjkYan4rNaEZL8qfyQ.gif" /></figure><p>We’re getting the value twice per click. This is an AJAX nightmare!</p><p>The way to get around this is to add event listeners to each input individually, which can be simplified using a for loop :</p><pre>$(&#39;#sc1&#39;)<br>    .click(function(){<br>        val = getval(&#39;sc1&#39;);<br>        console.log(val);<br>        $(&#39;#result&#39;).html(val)<br>});</pre><p>That way, when we click on any part of the control, the value has already updated when we retrieve it, so we see something like this on the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*em7sRauvplhuIZIfCGGYBw.gif" /></figure><p>And this in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*KjW9DdY2Dys-p6AF1kOLQw.gif" /></figure><p>Perfect!</p><p>One final word, the transitions don’t work perfectly in Safari, and tend to be a lot jumpier than smooth. I haven’t explored a solution to this yet, but will update the post when I find one.</p><h3>Start Typing Dropdowns</h3><p>Now, as mentioned above, Segmented Controls aren’t a one size fits all solution. I’d avoid using them when there are over 5 choices, and never go for more than 8 (I’ve used 8, but only when the feature in question has no mobile application).</p><p>The alternative mentioned in Zoltan’s article is to use dropdowns where the user can start typing, and have suggestions presented to them. Fortunately, HTML5 introduces the datalist, which means it’s super easy to get these up and running. The HTML is as follows:</p><pre>&lt;<strong>datalist </strong>id=<strong>&quot;counties&quot;</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Carlow&quot;</strong>&gt;<strong>Carlow</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Cavan&quot;</strong>&gt;<strong>Cavan</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Clare&quot;</strong>&gt;<strong>Clare</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Cork&quot;</strong>&gt;<strong>Cork</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Donegal&quot;</strong>&gt;<strong>Donegal</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Dublin&quot;</strong>&gt;<strong>Dublin</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Galway&quot;</strong>&gt;<strong>Galway</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Kerry&quot;</strong>&gt;<strong>Kerry</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Kildare&quot;</strong>&gt;<strong>Kildare</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Kilkenny&quot;</strong>&gt;<strong>Kilkenny</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Laois&quot;</strong>&gt;<strong>Laois</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Leitrim&quot;</strong>&gt;<strong>Leitrim</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Limerick&quot;</strong>&gt;<strong>Limerick</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Longford&quot;</strong>&gt;<strong>Longford</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Louth&quot;</strong>&gt;<strong>Louth</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Mayo&quot;</strong>&gt;<strong>Mayo</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Meath&quot;</strong>&gt;<strong>Meath</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Monaghan&quot;</strong>&gt;<strong>Monaghan</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Offaly&quot;</strong>&gt;<strong>Offaly</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Roscommon&quot;</strong>&gt;<strong>Roscommon</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Sligo&quot;</strong>&gt;<strong>Sligo</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Tipperary&quot;</strong>&gt;<strong>Tipperary</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Waterford&quot;</strong>&gt;<strong>Waterford</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Westmeath&quot;</strong>&gt;<strong>Westmeath</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Wexford&quot;</strong>&gt;<strong>Wexford</strong>&lt;/<strong>option</strong>&gt;<br>    &lt;<strong>option </strong>value=<strong>&quot;Wicklow&quot;</strong>&gt;<strong>Wicklow</strong>&lt;/<strong>option</strong>&gt;<br>&lt;/<strong>datalist</strong>&gt;<br>&lt;<strong>input </strong>type=<strong>&quot;text&quot; </strong>list=<strong>&quot;counties&quot; </strong>title=<strong>&quot;county-selector&quot; </strong>id=<strong>&quot;county-selector&quot; </strong>placeholder=<strong>&quot;Start Typing&quot;</strong>&gt;</pre><p>A little bit cumbersome to type out, but when implemented, it presents a much improved interface for the user to find the option they’re looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*h-bJ62s2dlt_it8dUwHvYQ.png" /></figure><p>Beautiful! Now, because nothing is ever easy, Safari doesn’t support datalists, and falling back to a traditional dropdown isn’t simple or really an acceptable solution. Thankfully, there’s a great solution from <a href="https://github.com/Fyrd">Alexis Deveria</a>, which simulates pretty similar functionality in Safari. Get the polyfill.css and datalist.polyfill.min.js from the <a href="https://github.com/Fyrd/purejs-datalist-polyfill">Github Project Page</a>, import the CSS above the HTML, and import the Javascript as the last possible tag in your HTML. This is really important, and should look something like this:</p><pre>&lt;!DOCTYPE html&gt;<br>    &lt;<strong>html </strong>lang=<strong>&quot;en&quot;</strong>&gt;<br>    &lt;head&gt;<br>        ...<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        ...<br>    &lt;/body&gt;<br>    &lt;<strong>script </strong>src=<strong>&quot;js/datalist.polyfill.min.js&quot;</strong>&gt;&lt;/<strong>script</strong>&gt;<br>&lt;/html&gt;</pre><p>And that’s it! It’s not identical, and doesn’t have a button to see all options like Chrome does (or clicking twice, like in Firefox), but it’s still pretty great:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*hPWPWZlu-UAtK1vSBlxMCQ.png" /></figure><p>And there we have it, some pretty straightforward HTML, CSS and Javascript to implement the amazing dropdown alternatives outlined in Zoltan’s article! Never again will you invoke your users wrath when they’re forced to scroll through 184 countries to find United Kingdom, or overshoot Australia and end up clicking on Belgium!</p><p>If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0J8nrlZcxO4mBZdoiENgzg.gif" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff51076%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Ff51076%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252Ff51076%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b85dfbb5286d8a25cf2e754b9462cf45/href">https://medium.com/media/b85dfbb5286d8a25cf2e754b9462cf45/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=568c6d3464ed" width="1" height="1" alt=""><hr><p><a href="https://blog.prototypr.io/implementing-dropdown-alternatives-568c6d3464ed">Implementing Dropdown Alternatives</a> was originally published in <a href="https://blog.prototypr.io/">Prototypr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to PonyGE2 for Grammatical Evolution]]></title>
            <link>https://medium.com/data-science/introduction-to-ponyge2-for-grammatical-evolution-d51c29f2315a?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d51c29f2315a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[natural-computing]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 05:40:03 GMT</pubDate>
            <atom:updated>2017-07-05T05:40:03.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Grammatical Evolution is a powerful method for algorithm optimisation. Given an objective function and a search space (grammar), it is possible to use evolutionary computing methods to evolve an algorithm to optimally (or at least efficiently) maximise the objective function.</p><p><a href="https://github.com/jmmcd/PonyGE2">PonyGE2</a> is a Python3 implementation which makes GE easy. This walkthrough discusses the pros and cons of GE and provides an example of how to evolve your own algorithms with GE. A paper describing fully the operation of PonyGE2 can be found <a href="https://arxiv.org/pdf/1703.08535.pdf">here</a>.</p><p>Unfortunately, Grammatical Evolution with PonyGE2 on current computers isn’t fast enough to evolve functions from large grammars in a reasonable time quite yet, but this technique is definitely one to keep an eye on in the future.</p><h3>Grammatical Evolution</h3><p>The method was first proposed by <a href="http://ieeexplore.ieee.org/document/942529/">Dr. Michael O’Neill</a> (paywall) in 2001 as a way to apply evolutionary computing methods to problems with a Formal Grammatical Structure, such as algorithms.</p><p>A Formal Grammar can be thought of as the set of rules that define a language, or just an official way of setting out what combination of words makes sense. In English, we learn these from our parents when learning to speak, and in school. When learning a second language, it can generally be broken down into two steps:</p><ol><li>Learn vocabulary</li><li>Learn the grammar</li></ol><p>Programming isn’t much different, and the major difference between programming languages isn’t what you’re trying to achieve, but how you tell them computer to do that.</p><p>So then how do we teach grammar to computers? And how are these words then used in evolutionary optimisation?</p><p>The process works something like this:</p><ol><li>Define a Backus Naur Form (BNF) representation of the grammar;</li><li>Randomly generate linear chromosomes to encode information;</li><li>Evaluate the fitness of chromosomes by mapping the grammar to the chromosome and testing against the fitness function;</li><li>Use Genetic Operators such as Crossover, Mutation and Reproduction to generate next generation of chromosomes;</li><li>Repeat steps 3 and 4 for a certain number of generations.</li></ol><h4>Backus Naur Form</h4><p>A BNF grammar is a way of writing grammar that computers can understand (context free). In Python, it is represented by a tuple containing 4 sets:</p><ul><li>T: The terminal Set</li><li>N: The non-terminal set</li><li>P: Set of production rules</li><li>S: Start symbol (which is a member of N).</li></ul><p>This probably doesn’t clear things up, but it’s good to keep in mind. Let’s look at an example:</p><pre>T = {+, -, /, *, x, y}</pre><p>So the terminal set is the set of all operators and variables you want to use in your program.</p><pre>N = {&lt;e&gt;, &lt;o&gt;, &lt;v&gt;}</pre><p>The non-terminal set is the set of all production activities that the program can undertake. In this situation, &lt;e&gt; is an expression, &lt;o&gt; is an operator, and &lt;v&gt; is a variable.</p><p>P then is the set of production rules:</p><pre>&lt;e&gt; ::= &lt;e&gt;&lt;o&gt;&lt;e&gt; | &lt;v&gt;<br>&lt;o&gt; ::= + | - | / | *<br>&lt;v&gt; ::= x | y</pre><p>Notice that all entries inP are entries of either T or N . The pipe operator | represents or . So when an &lt;e&gt; is encountered in the chromosome, it is either replaced with &lt;e&gt;&lt;o&gt;&lt;e&gt; , or &lt;v&gt; , and likewise for &lt;o&gt; and &lt;v&gt; .</p><p>Finally, the start symbol:</p><pre>S = &lt;e&gt;</pre><p>This is probably still quite confusing, but the reason for representing the grammar in this form becomes apparent when evaluating a chromosome.</p><h4>Chromosomes</h4><p>The simplest way of describing chromosomes is as a non-negative integer array. The values don’t matter much, but the length does (more on this later).</p><p>So for our example, let us call our chromosome:</p><pre>C: [4, 15, 75, 8, 41, 12]</pre><h4>Mapping Chromosome to Grammar</h4><p>Now everything comes together. Remember our starting symbol was:</p><pre>&lt;e&gt;</pre><p>Now, according to our Production Rules P , when a &lt;e&gt; is encountered, it is either replaced with &lt;e&gt;&lt;o&gt;&lt;e&gt; or &lt;v&gt; . But how do we know which one? Well, the chromosome tells us. The first value of the chromosome is 4 , and there are 2 options for &lt;e&gt; in the production rules. 4 mod 2 is 0 , so we take the 0-th (zero-indexed, so really the 1-st entry) option from the production rules, &lt;e&gt;&lt;o&gt;&lt;e&gt; .</p><p>So now our expression has expanded to &lt;e&gt;&lt;o&gt;&lt;e&gt; , and we’re evaluating the first entry &lt;e&gt;(as it’s not a member of the terminal set, we keep evaluating each entry until it is replaced with a member of the terminal set).</p><p>We know there are 2 options for &lt;e&gt; in the Production Rules, so we take the 2nd entry in the chromosome, 15 , and 15 mod 2 gives 1, so we take the 1st (zero-indexed, so really the 2nd entry) option from the production rules, &lt;v&gt; .</p><p>We continue with the following steps:</p><ul><li>Full Expression: &lt;v&gt;&lt;o&gt;&lt;e&gt; <br>Current Expression: &lt;v&gt; <br>Number of &lt;v&gt; options in Grammar: 2 <br>Chromosome value: 75 <br>75 mod 2 = 1 <br>Replace &lt;v&gt; with y</li><li>Full Expression: y &lt;o&gt;&lt;e&gt; <br>Current Expression: &lt;o&gt; <br>Number of &lt;o&gt; options in Grammar: 4<br>Chromosome value: 8<br>8 mod 4 = 0<br>Replace &lt;o&gt; with +</li><li>Full Expression: y + &lt;e&gt; <br>Current Expression: &lt;e&gt; <br>Number of &lt;e&gt; options in Grammar: 2 <br>Chromosome value: 41<br>41 mod 2 = 1 <br>Replace &lt;e&gt; with &lt;v&gt;</li><li>Full Expression: y + &lt;v&gt; <br>Current Expression: &lt;v&gt; <br>Number of &lt;v&gt; options in Grammar: 2 <br>Chromosome value: 12<br>12 mod 2 = 0<br>Replace &lt;v&gt; with x</li></ul><p>Final Expression: y + x</p><p>So we’ve turned our chromosome (array) into a function using our grammatical representation! Feel free to re-read this a few times, as it takes a while to understand where the expressions and operators come from.</p><h4>Evaluating Fitness Function</h4><p>Now we have a grammatically correct function, we can evaluate the performance of this function against some fitness function. Those functions that perform well are then given a greater chance of passing on their DNA to the next generation of chromosomes. From this point, GE doesn’t differ greatly from other genetic algorithms, as the chromosomes are crossed-over and mutated to generate the next generation of chromosomes, which are then mapped to the grammar and tested against the fitness function.</p><p>This continues for a user-specified number of generations, at the conclusion of which the most efficient (best score on the fitness function) algorithm is returned to you.</p><h3>Analysis of GE</h3><p>Now that you (hopefully) have a bit more of an understanding of what Grammatical Evolution involves, you might be asking why it’s so good?</p><p>First of all, it’s fast, really fast. By passing down information from generation to generation, it vastly improves on random search.</p><p>Secondly, because the grammar is written by you, you can easily encode domain knowledge into the function. You might hear this a lot, and ask ‘What does that actually mean?’ (I know I do). Here are some examples:</p><ul><li>Allow access to all information you have, regardless of whether it’s useful. This can be achieved using a &lt;v&gt; expression in the grammar and include all variables you want.</li><li>Make the program as complicated or simple as required. Including lots of options in the &lt;e&gt; (including duplicated options to alter the chance of a specific operator being chosen) allows easy manipulation of the complexity of the evolved program.</li><li>Define level of accuracy of constants by setting &lt;n&gt; ::= 0|1|2|3|4|5|6|7|8|9 and then &lt;const&gt; ::= &lt;n&gt;&lt;n&gt;&lt;n&gt;.&lt;n&gt;&lt;n&gt;&lt;n&gt; to set constants between 0 and 999 with 3 decimal places of accuracy.</li><li>Include functions with expressions include &lt;fn&gt;(&lt;e&gt;) and &lt;fn&gt; ::= sin | max</li></ul><p>This is all pretty cool, but GE does have some drawbacks. First of all, as mentioned above, the length of the chromosome does result in invalid programs. For the example above, if the second to last entry in the chromosome was 42 instead of 41, the &lt;e&gt; would’ve been replaced with &lt;e&gt;&lt;o&gt;&lt;e&gt; , but with no chromosome data left to evaluate these expressions. As this chromosome is invalid, it can’t be evaluated against the fitness function. So while a chromosome may contain close to a good solution, it will never be known.</p><p>The converse of this is when the program is evolved without using the entire chromosome. The leftover data is known as a tail, and can be ignored. As such, it is generally better to construct chromosomes to have long tails, as this reduces the chance of invalid solutions occurring.</p><p>Probably the biggest drawback however, is that grammar must be very very carefully constructed, and there is a bit of an art to constructing appropriate grammars and fitness functions for a problem. On top of this, ‘large’ grammars can take a long time to evolve. Grammars that include single-level for loops, if statements, list functions and dictionary operations can take upwards of 12 hours to evolve. Hopefully this improves in the future, but is the main thing stopping Grammatical Evolution from being a replacement for human code optimisers…</p><p>So now you hopefully have a bit more of an understanding on how Grammatical Evolution, we can have a go at implementing a simple example in PonyGE2.</p><h3>PonyGE2</h3><p>PonyGE2 can be cloned or forked from <a href="https://github.com/jmmcd/PonyGE2">here</a>. There’s no setup required, and the evolution will run from the command line with the appropriate arguments.</p><p>The best way to explore the package is to work through an example. We’ll try to evolve a function to find the maximum value in a list. This is easily achieved in Python with max() or functionally:</p><pre>for val in list:<br>    if val &gt;= current_max:<br>        current_max = val</pre><p>The first step is to create a fitness function, or what we want to maximise or minimise. The terminology here is a little confusing, as we’re evolving a function, the result of which will optimise the fitness function. For now we’re just talking about the fitness function.</p><p>All my code for these examples is contained at <a href="https://github.com/Padam-0/NC-GA">https://github.com/Padam-0/NC-GA</a></p><p>There are a bunch of examples in PonyGE2/src/fitness , and to run your own, create a file called max_in_list.py in that folder, with a structure something like this:</p><pre><em>from </em>fitness.base_ff_classes.base_ff <em>import </em>base_ff<br>import random<br>import time</pre><pre><em>class </em>max_in_list(base_ff):<br>    <em>def </em>__init__(self):<br>        # Initialise base fitness function class.<br>        super().__init__()</pre><pre><em>    def </em>evaluate(self, <em>ind</em>, <em>**kwargs</em>):<br>        p = <em>ind</em>.phenotype</pre><pre>        print(&quot;\n&quot; + p)</pre><pre>        fitness = 0</pre><pre>        for trial in range(50):<br>            self.test_list = generate_list()<br>            m = max(self.test_list)</pre><pre>            d = {&#39;test_list&#39;: self.test_list}</pre><pre><em>            try</em>:<br>                t0 = time.time()<br>                exec(p, d)<br>                t1 = time.time()</pre><pre>                guess = d[&#39;return_val&#39;]</pre><pre>                fitness += len(p)</pre><pre>                v = abs(m - guess)<br>                if v &lt;= 10**6:<br>                    fitness += v<br>                else:<br>                    fitness = self.default_fitness<br>                    break</pre><pre>                if t1 - t0 &lt; 10:<br>                    fitness = self.default_fitness<br>                    break<br>                else:<br>                    fitness += (t1 - t0) * 1000</pre><pre>            <em>except</em>:<em><br>                </em>fitness = self.default_fitness<br>                break</pre><pre>        return fitness<br></pre><pre><em>def </em>generate_list():<br>    return [random.randint(0, round(random.random() * 90 + 10, 0)) for i in range(9)]</pre><p>Let’s step through it line by line.</p><p>Lines 1–3:</p><ul><li>Imports. base-ff is the class we’ll inherit from, random is used to generate the random list, and time to track execution time</li></ul><p>Line 5:</p><ul><li>Define the class, max_in_list , inheriting from base_ff . This needs to have the same name as the file you’re working in (which is max_in_list.py in this case).</li></ul><p>Line 6–9:</p><ul><li>Instance initialisation information for the class.</li></ul><p>Line 10:</p><ul><li>Create evaluate function with three parameters, self, ind, and kwargs.</li></ul><p><em>Up to this point, this is standard for each fitness function. What comes next is independent for each algorithm being evolved.</em></p><p>Line 11–13:</p><ul><li>Returns the current algorithm from the evolution as p . We can print this to the command line (as we do in line 13), and see it.</li></ul><p>Line 15:</p><ul><li>Initialise fitness to 0</li></ul><p>Line 17:</p><ul><li>Set a for loop to run 50 times. If we don’t do this, each algorithm will run on the same ‘random’ list, and may evolve a line such as m=49 which is then returned. 49 may happen to be in that list and the maximum value, so the computer thinks it has found the perfect algorithm. Short, fast and correct! But overfit to that one example. On any other list, where 49 is not in it (or not the maximum value), the algorithm would be wrong. So we give the fitness function 50 lists to look at, all with different values (and indeed maximum possible values) to avoid overfitting.</li></ul><p>Line 18:</p><ul><li>Create the random list self.test_list from the function generate_list()</li><li>Jumping forward to the last few lines, this function generates 10 random integers between 0 , and some number between 10 and 100. This is best to avoid overfitting.</li></ul><p>Line 19:</p><ul><li>Find the maximum of the current list being used. It’s important to do this here and not after the algorithm has been executed, as the list may change during the execution (if list operations have been included in the grammar), so the correct result may not be returned.</li><li>At this point you may (correctly) be asking, what’s the point of doing all this if we already have a function to find the maximum value of a list? That’s an excellent question, and the point of GE is to find a potentially more efficient way of doing this. For simple functions it’s not really worth it, but is a good learning exercise.</li></ul><p>Line 21:</p><ul><li>Create a dictionary d with one entry test_list that holds the current list. This will make more sense when we write the grammar.</li></ul><p>Line 23 / 45–47:</p><ul><li>Try/Except statement. Generally it’s not a good idea to have an open ended Except statement, as you’ll never catch errors, but in this case, all errors can feasibly occur within the evolved algorithm (because it’s just putting words together at semi-random, so there’s no way they’re all going to be perfect code) so the statement is justified.</li><li>If an error is returned, the fitness for that algorithm is set to the default (NA) and the loop broken out of, and the next algorithm tested.</li></ul><p>Line 24:</p><ul><li>Get the start time.</li></ul><p>Line 25:</p><ul><li>Execute the algorithm p and pass the parameters within d so they can be accessed. This is where the algorithm is actually evaluated. The value that is returned is written to the dictionary d as return_val (we define this in the grammar).</li></ul><p>Line 26:</p><ul><li>Get the end time.</li></ul><p>Line 28:</p><ul><li>Retrieve the maximum value guess from the current algorithm.</li></ul><p>Line 30:</p><ul><li>Increase the current fitness score by the length of the algorithm. This is to avoid bloat and unnecessary if statements. The evolution tries to keep things as short as possible.</li></ul><p>Line 32:</p><ul><li>Find the difference between the actual maximum value of the list and the guess. Best case scenario this is 0, but if not, it is a proxy for how close the algorithm was to getting the right answer.</li></ul><p>Line 33–37:</p><ul><li>There are some algorithms which may produce completely outsize guesses which will crash the evolution, so it’s best to keep an if statement to check the value isn’t above some large (but not too large) number that would never be feasible.</li><li>Again, if this check fails, set the fitness to NA and move onto the next algorithm. Otherwise, add the difference between the guess and correct value to the current fitness score.</li></ul><p>Line 39–43:</p><ul><li>Some algorithms (with multi-level for loops, or for i in range(1000) statements) take a very long time to evaluate. Unless this is expected, this indicates an error, so an if statement to catch those which take more than some time (10 seconds in this case) is recommended.</li><li>If the algorithm takes less than this, the time can be added to the fitness score, so that algorithms that work faster are rewarded with a lower fitness. Because the time-scale is so small, scaling this part of the score up by a factor of 100 or 1000 is recommended.</li></ul><p>Line 49:</p><ul><li>Return the fitness, and we’re done!</li></ul><p>That was a lot to take in, and a few bits may not make sense, but we’ll push on a write the grammar, and hopefully with the full picture it will be a bit clearer.</p><h3>Grammar</h3><p>This is the difficult part, as you have to be very precise and thoughtful with what you write. We’ll step through the base grammar required to evolve our max function, but grammar extensions that include additional logic, list functions, and dictionary functions are available at <a href="https://github.com/Padam-0/NC-GA">https://github.com/Padam-0/NC-GA</a>.</p><p>Once again, PonyGE2 provides grammar examples in the PonyGE2/grammars directory. Create yours in there (it can be called anything, but give it the extensions .pybnf ).</p><p>The first line contains the starting point for the program:</p><pre>&lt;fc&gt; ::= &lt;deff&gt;{::}&lt;callf&gt;</pre><p>In English, this says:</p><ul><li>&lt;fc&gt; is the starting symbol, which contains one option: &lt;deff&gt; followed by a newline ({::} represents a newline, {: is an indent (tab or 4 spaces) and :} closes the indent), followed by &lt;callf&gt; .</li></ul><p>The next line, we define &lt;deff&gt; :</p><pre>&lt;deff&gt; ::= def fun(li):{:m = 0{::}&lt;code&gt;{::}return m:}</pre><p>This looks a bit more like Python. We can see we have a function definition of a function called fun() with one argument li .</p><p>Next we open an indent (like Python requires), initialise our variable m=0 , start a new line, write some &lt;code&gt; , start a new line, return m , then close the indent.</p><p>Again, there is only one option for &lt;deff&gt; , so this will definitely be written. Next, &lt;callf&gt; :</p><pre>&lt;callf&gt; ::= return_val = fun(test_list)</pre><p>Again, this looks more like Python. And only one option, so regardless of the chromosome, our algorithm will always look something like this:</p><pre>def fun(li):<br>    m = 0<br>    &lt;code&gt;<br>    return m<br>return_val = fun(test_list)</pre><p>The &lt;code&gt; section is where the evolution gets done, but in most cases we’ll now have a working function. Cool hey! It gets cooler.</p><p>Remember in our fitness function, we gave our dictionary d a key called test_list? Well, because we call exec(p, d) , the program can see the contents of that dictionary d , so when it sees test_list in the algorithm, it replaces it with the value corresponding to test_list in the dictionary d , or in our case, the random list we want to find the maximum of! Cool huh, now we have a way of passing data from our fitness function into our evolved function.</p><p>And again, in our fitness function, we set guess = d[&#39;return_val&#39;] ? Well it turns out not only can we read from d , we can write to it, and the value returned from fun(test_list) is passed to d as return_val , so then we can access the returned value of the evolved algorithm in the fitness function, so we can access its fitness!</p><p>So we now can send data in both directions, I recommend going and re-reading the section on the fitness function to see if this all makes a bit more sense now. It definitely does for me.</p><p>As for the rest of our grammar:</p><pre>&lt;code&gt; ::= &lt;stmt&gt; | &lt;stmt&gt;{::}&lt;code&gt;</pre><p>Code is either a single statement, or a statement followed by some more code on a new line. This way we can give ourselves multi-line functions! This recursive nature of the grammar is very useful, and will come up quite a lot to enable us to add complexity to the evolution.</p><pre>&lt;stmt&gt; ::= &lt;var&gt; = &lt;expr&gt; | &lt;for&gt; | &lt;if&gt;</pre><p>A statement is then either assigning an expression to a variable, a for loop, or an if statement. Let’s look at these in reverse order:</p><pre>&lt;if&gt; ::= if &lt;cond&gt;:&lt;if-opt&gt;<br>&lt;if-opt&gt; ::= {:&lt;code&gt;:} | {:&lt;code&gt;:}else:{:&lt;code&gt;:} | {:&lt;code&gt;:}elif &lt;cond&gt;:{:&lt;if-opt&gt;:}</pre><pre>&lt;cond&gt; ::= &lt;expr&gt; &lt;c-op&gt; &lt;expr&gt;<br>&lt;c-op&gt; ::= &quot;&gt;=&quot; | &quot;&lt;=&quot; | &quot;&gt;&quot; | &quot;&lt;&quot;</pre><p>So the if statement takes a condition, and then an option. The condition takes the form of an expression, an operator, and an expression.</p><p>To make this clearer, it’s worth discussing the &lt;expr&gt; tag now:</p><pre>&lt;expr&gt; ::= &lt;number&gt; | &lt;var&gt; | &lt;expr&gt; &lt;op&gt; &lt;expr&gt;</pre><p>So an expression is either a number, a variable, or an operation (more on all of these later).</p><p>Back to our if statement, our condition takes the form if &lt;cond&gt;: which expands to:</p><pre>if &lt;expr&gt; &lt;c-op&gt; &lt;expr&gt;:</pre><p>Which can then expand to something like:</p><pre>if &lt;var&gt; &gt;= &lt;number&gt;:</pre><p>And we have an if statement we recognise. The &lt;if-opt&gt; are a little more complex, as they have to include elif and else functionality, but they all boil down to an if statement, a condition, and then some &lt;code&gt; being written inside them.</p><p>Next, for loops:</p><pre>&lt;for&gt; ::= for i in &lt;list-var&gt;:{:&lt;fl-code&gt;:}<br>&lt;fl-stmt&gt; ::= &lt;var&gt; = &lt;expr&gt; | &lt;fl-if&gt;<br>&lt;fl-code&gt; ::= &lt;fl-stmt&gt; | &lt;fl-stmt&gt;{::}&lt;fl-code&gt;</pre><p>So the for loop takes the form for i in list: then creates an indent (on a new line) for some statement. The statement itself could just be our &lt;stmt&gt; from above, but this would allow nested for loops, which can exponentially increase evaluation time. Unless you think nested for loops are absolutely necessary, avoid them (this is a pretty good rule for programming in general).</p><p>So our &lt;fl-stmt&gt; only includes variable assignment, and a special if statement, &lt;fl-if&gt; :</p><pre>&lt;fl-if&gt; ::= if &lt;cond&gt;:&lt;fl-if-opt&gt;<br>&lt;fl-if-opt&gt; ::= {:&lt;fl-code&gt;:} | {:&lt;fl-code&gt;:}else:{:&lt;fl-code&gt;:} | {:&lt;fl-code&gt;:}elif &lt;cond&gt;:{:&lt;fl-if-opt&gt;:}</pre><p>This is actually identical to the if statement grammar above, but instead of calling &lt;code&gt; , it calls &lt;fl-code&gt; , basically to avoid for loops inside if statements inside for loops. A little cumbersome, but better than allowing nested for loops!</p><p>Finally, variable assignment. We’ve already looked at &lt;expr&gt; , so let’s look at parts that make it up:</p><pre>&lt;var&gt; ::= m | i<br>&lt;list-var&gt; ::= li</pre><pre>&lt;number&gt; ::= &lt;num&gt;&lt;num&gt;&lt;num&gt; | &lt;num&gt;&lt;num&gt; | &lt;num&gt;<br>&lt;num&gt; ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9</pre><pre>&lt;op&gt; ::= + | - | * | / | // | %</pre><p>This should be pretty straightforward. Our variables are m which we initialised at the beginning, and i which is initialised if a for-loop is run. Numbers can go from 0 to 999, and we have all the python operators (except exponential, which can cause integer overflow and a whole bunch of very slow to execute algorithms. Like the nested for loops, only include it if you need it).</p><p>And believe it or not, that’s our grammar done! Let’s see how we can go from a &lt;code&gt; tag to our final function. A chromosome like:</p><pre>[0, 1, 0, 1, 0, 1, 1, 2, 1, 0, 0, 0, 0, 1, 1]</pre><p>Mapped out, this gives us:</p><pre>def fun(li):<br>    for i in li:<br>        if i &gt; m:<br>            m = i<br>return_val = fun(test_list)</pre><p>Sweet! Now that we have our fitness function and our grammar, how can we run this with PonyGE2?</p><p>Well, if the fitness function is in PonyGE2/src/fitness (and has the same filename as the class it holds, max_in_list in this case), and the grammar is in PonyGE2/grammars, we can run from the command line:</p><pre>python ponyge.py --fitness_function max_in_list --grammar_file max_in_list.pybnf</pre><p>This will run your evolution with your grammar and fitness function, with default parameters for other options. There are a lot, and it’s worth reading the <a href="https://github.com/PonyGE/PonyGE2/wiki">reference documentation</a>, but the two really important ones are Population size and Number of generations.</p><p>The population size is the number of chromosomes generated at the beginning, and evolved at each generation. The larger this number, the wider the search, but the slower the evolution time.</p><p>The number of generations is the number of evolutions that the chromosomes go through. Again, it widens the search but at the cost of evolution speed.</p><p>You can set these parameters with:</p><pre>python ponyge.py --fitness_function max_in_list --grammar_file MIL_e2.pybnf --population_size 500 --generations 100</pre><p>Now for simple grammars, values for these parameters in the range of 100–500 is sufficient, but as the grammars get more complex, they require more population and generations to ensure a sufficient algorithm is evolved. A good test is to add complexity to your grammar, and run it with the same fitness function as above. If you get a function which finds the maximum in a list, you can be confident that your parameters are appropriate, and then turn it onto your other fitness function for the problem you’re trying to solve.</p><p>Unfortunately, run times get large quite quickly. For me, a population of 2000 and 750 generations took around 6 and a half hours, and that wasn’t enough to evolve an appropriate algorithm with the grammar above (but also including list and dictionary operations).</p><p>And herein lies the issue with GE. The promise is that if you can write a fitness function, and a robust grammar that encompasses a wide range of Python operations, then GE will be able to evolve a more efficient way of doing things. Unfortunately, the processing power and time this takes at present is infeasible on public machines.</p><p>Regardless, this is a field to watch, as if we’re going to teach machines to code, there’s a good bet that Grammatical Evolution will have something to do with it.</p><h3>Other Examples</h3><p>The team at <a href="http://ncra.ucd.ie/index.shtml">UCD Natural Computing Research and Applications Group</a> are the cutting edge of this research, and have published many great papers showing the power of GE (albeit on supercomputers). Some include:</p><ul><li><a href="https://arxiv.org/abs/1704.04119">A Search for Improved Performance in Regular Expressions</a>;</li><li><a href="http://www.sciencedirect.com/science/article/pii/S0020025514002904">Optimising complex pylon structures with grammatical evolution</a>; and</li><li><a href="https://link.springer.com/chapter/10.1007%2F978-3-642-20520-0_21?LI=true">Combining structural analysis and multi-objective criteria for evolutionary architectural design</a>.</li></ul><p>If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*0J8nrlZcxO4mBZdoiENgzg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d51c29f2315a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introduction-to-ponyge2-for-grammatical-evolution-d51c29f2315a">Introduction to PonyGE2 for Grammatical Evolution</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[A year in Business Analytics at UCD Smurfit School of Business]]></title>
            <link>https://medium.com/hackernoon/a-year-in-business-analytics-at-ucd-smurfit-school-of-business-e4a151843aa2?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a151843aa2</guid>
            <category><![CDATA[ireland]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[masters-degree]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Tue, 06 Jun 2017 10:36:36 GMT</pubDate>
            <atom:updated>2019-05-13T04:48:57.328Z</atom:updated>
            <content:encoded><![CDATA[<p>This post was written at the request of <a href="https://www.datsciawards.ie/">datsciawards.ie</a>, presenting awards to the top Data Scientists in Ireland for 2017. I’m not nominated, but you should definitely check out the excellent people who are.</p><p>They’ve also partnered with <a href="http://www.smurfitschool.ie/">UCD Michael Smurfit Graduate School of Business</a> to give a full scholarship for the Masters of Business Analytics for 2017/18 to an EU student. If you’re thinking about a career move into Data Science, I can strongly recommend the course. More information is available <a href="https://www.datsciawards.ie/tickets/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UexQMmbNXnvQdFFtDGiMTg.png" /><figcaption>The highlight of the Smurfit Social Calendar, the Smurfit Ball</figcaption></figure><p>At the beginning of 2015, due to a prolonged downturn in the oil price, I was given a years leave of absence from my job as a Drilling Engineer in Norway. I was scheduled to go on vacation around the time I found out, so before I moved my life from Norway, I had two weeks to think about what to do next. The way I saw it I had three options:</p><ul><li>Get another job in Oil and Gas, or try and move into another field;</li><li>Go back to college and get a new set of skills; or</li><li>Travel, explore and party;</li></ul><p>There weren’t really any Oil jobs going at that time, and I didn’t feel like rushing back into work anyway (despite the downturn we were very busy in Norway, until we very much weren’t). Travel would’ve been great, but left me in a precarious position if there was not a job for me at the end of my year off.</p><blockquote>That left college, which then begged the question: What to study?</blockquote><p>I was forced to think about what it really was about my job that I enjoyed, and I realised that the most challenging and enjoyable projects I had worked on all involved data manipulation and processing. At that time, I didn’t know Data Science was a thing, but reading up on it really opened my eyes to this new world, and I realised that this was where I wanted to be.</p><p>My introduction to Data was when I was 14, and taking part in an after school maths challenge class. I remember struggling with every question that involved calculus (which was all of them), but one time I got to use Excel, and with my dads help, built a model which correctly solved the problem! I was hooked.</p><p>Throughout the rest of high school, and my undergraduate degree, my interest in how data moved and related within a model was my driving curiosity, though I never realised it was something I could do full time.</p><p>I studied Chemical Process Engineering at the <a href="http://www.uwa.edu.au/">University of Western Australia</a>, and my skills with manipulating data relationships helped tremendously in building financial and processing models for my final year project and thesis. I interned at various engineering and financial institutions, and at the time thought I wanted to be a M&amp;A analyst.</p><p>Upon graduation, I weighed my options and opted for adventure, taking a technical offshore <a href="https://hackernoon.com/tagged/engineering">engineering</a> position with <a href="http://slb.com/">Schlumberger Ltd</a>, based out of Stavanger, Norway.</p><p>My role with Schlumberger was far from Data Science (I was an offshore engineer involved with drilling and logging new wells), my interest and skills in data analysis held me in good stead. When I was asked to turn some data output from a new product into a well-site visualisation for our customers, I dived into Visual Basic and got my first taste of programming. Recording macros and <a href="https://hackernoon.com/tagged/learning">learning</a> from Microsoft forums got me pretty far, and I ended up building software to automate a previously manual task and opening up a new revenue opportunity for Schlumberger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH7Q-_kVHVn17dg-SbWlvg.jpeg" /><figcaption>One of the many amazing views I got to experience in Norway</figcaption></figure><p>With skills and experience in hand, and the decision to study Data Science, the UCD Michael Smurfit Graduate School of Business stood out for it’s academic focus (as opposed to a coding bootcamp or such), and prestige in Ireland. I applied and was accepted to the MSc Business Analytics.</p><p>The first semester was focussed on building a solid foundation of Maths, Statistics, and Project Management skills. There wasn’t as much of a focus on programming initially, but the advantage of taking the course full time was that we had ample time to develop these skills in our own time. As the semester went on, we worked in teams to build a <a href="https://github.com/Padam-0/black-scholes_opm">Black-Scholes option pricing model</a>, and explored and critiqued <a href="https://medium.com/@padam0/did-pokemon-go-try-too-hard-to-be-agile-d226456cf7a4">IT project management philosophies</a>.</p><p>We also gained a solid academic review foundation, and spent the winter thoroughly exploring an area of literature.</p><p>The second semester saw the focus shift from theoretical to applications of algorithms. Some of the projects I’ve undertaken include:</p><ul><li>Deploying <a href="https://github.com/Padam-0/Dykstras-and-Birdirectional-Variant">Dijkstra’s and Bidirectional Variants</a> for finding the shortest path through a network, using optimised data structures;</li><li>Developing an algorithm to appropriately <a href="https://github.com/Padam-0/aeroplane_seating_assign">assign aeroplane seating</a>;</li><li>Simulating a new <a href="https://medium.com/towards-data-science/utilising-epidemic-modelling-to-improve-advertising-click-rates-on-facebook-6f294205a43f">viral advertising model</a> to increase click rates on Facebook;</li><li>Undertaking a clustering case study to optimise <a href="https://medium.com/@padam0/using-unsupervised-learning-to-optimise-childrens-t-shirt-sizing-d919d3cbc1f6">children’s T-shirt sizing</a>; and</li><li>Suggesting appropriate ordering of Formula 1 races to minimise travel time for drivers.</li></ul><p>The biggest drawcard of the course for me was the opportunity to spend the summer working on an industry partnered project. I’m working on an application to display and summarise the Irish housing sector, to aid Data Scientists at <a href="http://aib.ie/">AIB</a> when providing insights.</p><p>The summer practicum gives us an opportunity to apply the skills we’ve learned over the last year. Mine involves Python, Django, Javascript, D3, web-scraping, cloud computing, SKLearn and the Google Maps API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*-GbYPdN6dW8M3rpRh0YUnQ.gif" /><figcaption>Working with D3.js animations to show changes in house prices around Dublin</figcaption></figure><p>The course itself has been thoroughly worthwhile, and I’ve improved my academic understanding of algorithms and approaches, vastly increased my coding ability, and have a wide range of tools available to me to solve many problems.</p><p>The course has also given me plenty of scope to improve my skills in areas around Data Science, such as learning Django to quickly deploy web apps and dashboards, D3 to visualise data, and cloud based data processing to push computational possibilities beyond my personal resources.</p><p>I’ve also had the opportunity to take place in 3 Hackathons, each of which opened my eyes to areas which I needed to improve my skills in:</p><ul><li>The ESB Big Energy Hack taught me the necessity of knowing your data before focussing on a solution, as well as the difficulty of balancing multi-disciplinary teams;</li><li>The AIB Datahack showed me that while my data cleaning skills were improving nicely, I needed more practical experience in Machine Learning; and</li><li>The Citadel Correlation One Datathon taught me that Data Science is as much about the question being answered as it is about the process (our solution was very business focussed, whereas the winners went for more interesting insights).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Nm8glBuEm9ZWzDO8LGopQ.png" /><figcaption>At the Correlation One Datathon</figcaption></figure><p>The Correlation One Datathon was a great culmination of skills, and showed how far I had come since the beginning of the course. In 6 and a half hours, we parsed 15gb of data and put together a model for Uber to optimise the distribution of drivers across New York at any point in time. As an extension of this, I explored a much larger subsection of the data to figure out which neighbourhood partied the hardest in New York.</p><p>The social side of my time at UCD has also been a highlight, with diverse classmates, all of whom have welcomed me to Ireland. The highlight of the social calendar was the Smurfit Ball.</p><p>I’ve also had the opportunity to represent UCD in Ultimate Frisbee, traveling to Belgium to compete in October, and placing 2nd in the Irish College Championships in April.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE5f9Np3Md-xd2axfvh6RQ.png" /></figure><p>It’s been a great year at UCD, and a great (if slightly roundabout) journey into Data Science. I’m really excited for all the opportunities I’m going to have to deploy the skills I’ve learned.</p><p>I thoroughly recommend the UCD MSc Business Analytics course and really encourage budding data scientists to apply for the <a href="https://www.datsciawards.ie/tickets/">scholarship</a>!</p><p>Good luck to all nominated for the Irish Data Science Awards in 2017!</p><p>If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%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/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a151843aa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/a-year-in-business-analytics-at-ucd-smurfit-school-of-business-e4a151843aa2">A year in Business Analytics at UCD Smurfit School of Business</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons Learned: Digital Ocean for Python 3]]></title>
            <link>https://medium.com/data-science/lessons-learned-digital-ocean-for-python-3-e2442db4246f?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2442db4246f</guid>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[lessons-learned]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Wed, 10 May 2017 14:12:14 GMT</pubDate>
            <atom:updated>2017-05-22T09:43:55.908Z</atom:updated>
            <content:encoded><![CDATA[<p>This entry is part of an ongoing series. I spend a lot of time trying out new technologies. More often than not, because of a recommendation like: “You should try [insert technology here], it’s super easy!”.</p><p>This turns out to rarely be the case, so every time I invest hours into trying to get something to work, I’ll publish my solution, and any tips and tricks I learned along the way.</p><p><a href="https://www.digitalocean.com/">Digital Ocean</a> is a cloud based server provider, with very reasonable plans that allow you to shift computation off your computer and into the cloud, saving you time and keeping your computer fresh!</p><p>I initially followed <a href="https://medium.com/u/bc17bd299bf1">Tomi Mester</a>’s tutorial to get DO set up, but quickly realised I wanted to do more (although I highly recommend the rest of the series, <a href="https://data36.com/learn-data-analytics-bash-scratch/">Data Science from the Command Line</a>). This turned out to be a little tricky, so here’s my walkthrough.</p><h3>1. The Signup</h3><p>Head over to <a href="https://m.do.co/c/701d1d25ae74">Digital Ocean</a> and create an account, using either Paypal or a Credit Card (if you use the link above you’ll get some free credit and so will I. If you don’t want to do that, just <a href="https://www.digitalocean.com/">click here</a>).</p><p>If you’re a student, you can also get $50 in credit from the <a href="https://education.github.com/pack/offers">Github Student Pack</a> (which I also highly recommend). Digital Ocean initially wouldn’t accept my code when I signed up, but I submitted a support ticket and they credited it within a few hours.</p><h3>2. Your First Droplet</h3><p>Droplets are server space which is specifically reserved for you. You’re only ever charged when you have a droplet (regardless of whether it’s on or off), but creating and destroying them is easy, so don’t worry about being charged when you’re not actively using it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*PjJmIYaBZHqkRzn_V0x2-g.png" /></figure><p>In the top right-hand corner of your DO dashboard (or in the centre if you don’t already have any droplets), look for the Create Droplet button.</p><p>Clicking it takes you to the setup page. The first option is image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HuXMeV1IFo_xBg1vs5XlA.png" /></figure><p>You won’t have a Snapshots option (more on this later), but the default choice (Ubuntu) is what we want, so you don’t have to do anything here.</p><p>The second choice is pricing plans:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xmj5-JTbazo5D8hgV5Nvgg.png" /></figure><p>Here you can see what you’re getting, and how much it costs. You’re charged per hour that the droplet exists, so unless you’re not deleting it when you’re done, your cost will be a lot lower than the per-month costs quoted.</p><p>Which one you pick depends on a few things:</p><ul><li>How big are the files you’ll be loading into memory? (pandas dataframes for instance). The first line under the price is how much memory / how many CPUs the droplet has.</li><li>Can your process be distributed? (think sklearn njobs= -1 ). If it can, multiple CPUs will speed up processing. Likewise, if you have a lot of data, splitting in half and running the jobs at the same time will save time, but is only possible on droplets with more than 1 CPU.</li><li>How big are the data files you’ll be uploading? This is the second line, the amount of storage available.</li><li>The last line represents the amount of data transfer (upload + download) that is allowed. Unless you’re doing something really crazy, 1TB is more than enough.</li></ul><p>I recommend the $5/month option to start. It’s pretty easy to upgrade if you’re hitting a wall.</p><p>The third step is Add Block Storage. You don’t need this initially.</p><p>The forth is choosing a data centre:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ER2JeaciX77wW8PMVb8tAw.png" /></figure><p>I’m in Ireland, so I chose London. Choose whichever is closest to you.</p><p>The final step is to enable monitoring (more on this later) and give your droplet a really useful name!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQJTpuUFEngcoh3z1T2rew.png" /></figure><p>Then hit create droplet, and after a minute or so, you’ll be all set!</p><h3>3. Initial Setup and Snapshots</h3><p>When you’re done, you’ll get an email from Digital Ocean with an IP address, username and password. Copy the IP address, fire up your command line and enter:</p><pre>ssh root@[IP Address]</pre><p>If this hangs and nothing happens, you can try:</p><pre>ping [IP Address]</pre><p>and see if you have a connection. If not, you’re probably being blocked by an external firewall (your work or university). This happened to me, and there’s not a lot you can do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*zyHVDv89dziBoV4o0LDpGQ.png" /><figcaption>Hit CTRL-C to stop it after 10 or so packets</figcaption></figure><p>If you do get a response from ssh root@[IP Address] , there will be a bunch of text asking you if you want to proceed. Write yes and press enter.</p><p>You’ll then be asked to enter the password. Copy and paste that in from the email and hit enter. You’ll then need to change the root password. Make this pretty secure as you won’t be logging into root that often, but if someone else does they can totally wreck your droplet.</p><p>Next, you want to create a user:</p><pre>adduser [username]</pre><p>where [username] is anything you want.</p><p>You’ll have to create a password for this user, and it’ll ask for a bunch of personal information. Enter this if you like, or skip it (press enter), it doesn’t matter.</p><p>Next, give your new account permissions to do stuff on the server</p><pre>usermod -aG sudo [username]<br>gpasswd -a [username] sudo</pre><p>This gives yourself the ability to make changes without having to be logged into root.</p><p>Finally, change the time zone:</p><pre>sudo dpkg-reconfigure tzdata</pre><p>and select your current city.</p><p>Nice! We’re all set up on root. Now we can exit and check out your user account.</p><pre>exit</pre><pre>ssh [username]@[IP Address]</pre><p>Once you’ve logged in, the first step is to configure your bash profile to make your life easier.</p><pre>nano .profile</pre><p>If you haven’t used Nano before, it’s a simple text editor. Use arrow keys to move, Ctrl+k to cut a line, Ctrl+u to paste a line, Ctrl+o to save, Ctrl-x to exit.</p><p>You can add aliases here (shortcuts) to make life easier. I use Python 3 and Pip 3, so I generally avoid confusion by setting:</p><pre>alias python=&quot;python3&quot;<br>alias pip=&quot;pip3&quot;</pre><p>I also hate typing nano ~/.profile when I want to change or check my bash profile, so I alias that too:</p><pre>alias obp=&quot;nano ~/.profile&quot;<br>alias sbp=&quot;source ~/.profile&quot;</pre><p>You can also add any other aliases here. Save it with Ctrl+o and exit with Ctrl-x .</p><p>To implement these changes, you need to source the profile:</p><pre>source .profile</pre><p>(As a side note, you can’t use new alias shortcuts before you’ve sourced them, so simply entering sbp won’t work yet, but will after you’ve sourced it the long way once).</p><p>apt-get is a bit like Pip for the command line, and should be updated before we go any further.</p><pre>sudo apt-get update</pre><p>Python 3 is already installed, but Pip isn’t, so let’s go ahead and get and update that:</p><pre>sudo apt-get install python3-pip<br>pip install -upgrade pip</pre><p>Now you can pip install all your regular Python packages! Well, you can in a second. For some reason, Matplotlib and a few other packages have issues with Ubuntu, but you can solve these by running:</p><pre>sudo apt-get install libfreetype6-dev libxft-dev<br>sudo apt-get install python-setuptools</pre><p>Sweet, now you can go nuts with pip3 install . If you have a requirements.txt file which you use for all your installations, you can run that now.</p><p>Finally, <a href="https://geoff.greer.fm/ag/">AG</a> is a great search tool for the command line which doesn’t come as standard, so you can install that too if you’d like:</p><pre>sudo apt install silversearcher-ag</pre><p>Perfect, you’re all set up! Now, this was quite a lot of work, and it would suck to have to do this each time. That’s where Digital Ocean snapshots come in!</p><p>This is a way to ‘save-as’ your current droplet, so that when you create a new droplet next time, you can just load that image and you’ll start exactly where you left off! Perfect.</p><p>Powerdown your droplet using sudo poweroff and head over to the Snapshots menu-item on your Digital Ocean droplet page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Ar-0WyAEDj0XkJOUMuofeA.png" /></figure><p>Snapshots aren’t free, they cost $0.05/Gb/month. My snapshot taken with Pandas, Numpy, Matplotlib and a few other packages install was 1.85Gb, so that’s about $1.11 per year. Not bad considering it’ll save you 10 minutes each time you set up a droplet!</p><p>As your droplet is already powered down, hit the ‘Take Live Snapshot’ button and Digital Ocean will do the rest.</p><p>A side note here, it doesn’t appear you can read a snapshot into a cheaper droplet pricing scheme. Just something to keep in mind.</p><p>If you ever want to upgrade your pricing scheme, head to the Resize menu item. Again, you can’t downgrade here and if you want to, you’ll need to create a droplet from scratch and repeat the above steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*-sN_9bYB6MgANDW7HvtmSw.png" /></figure><p>To turn your droplet back on, head to Digital Ocean and in the top-right hand corner of the droplet page there’s an on/off toggle. Turn it back on and you’re ready to upload data.</p><h3>4. Uploading Data via SFTP</h3><p>Now, if you have the data on your personal computer and want to send it up to the cloud, you’ll need to do so via SFTP (Secure File Transfer Protocol). This is fairly easy, albeit it not lightening fast.</p><p>To start, make an SFTP connection:</p><pre>sftp [username]@[IP Address]</pre><p>Now, you can use the normal command line functions like cd ,ls and pwd to move around the file system on the server. However, for some reason, autocomplete (tab) doesn’t work on SFTP. For that reason, I suggest uploading all your files and code into the home directory, and the logging back in with ssh and moving stuff around using mv and autocomplete. Trust me, it’s much easier.</p><p>That’s on the server side, but how about moving around on your personal computer? The same commands work, but you need to prefix them with an additional l , that is lcd , lls and lpwd . Manoeuvre your way to the directory where the files are held on your local, and then upload them to the server using:</p><pre>put [localFile]</pre><p>or for a whole directory:</p><pre>put -r [localDirectory]</pre><p>This isn’t fast, for my 1.5Gb data files it took about 20 minutes each. Annoying, but there’s not much you can do. You can upload in parallel, but this means opening up a new command line tab and logging in with SFTP again, plus both connections slow down by half, so the total time is the same :(</p><p>You can see how much of you storage you’ve used by running:</p><pre>df -h</pre><p>For future reference, downloading files from the server is as simple as:</p><pre>get [remoteFile]</pre><p>or</p><pre>get -r [remoteDirectory]</pre><p>Now, once your data files are up on the server, you can upload your python scripts too. Make sure that if your local directory configuration is different to the remote, to change any file locations in the code.</p><p>Deleting files from the server is also slightly different to locally, as rm -rf directory doesn’t work. You need to rm filename to delete a file, or empty a directory then rmdir directory to delete a folder.</p><p>This is enough to get you started, but if you’re interested in more advanced options, there’s a good tutorial <a href="https://www.digitalocean.com/community/tutorials/how-to-use-sftp-to-securely-transfer-files-with-a-remote-server">here</a>.</p><p>I thoroughly recommend testing all your code locally (I use PyCharm, which is great and has a <a href="https://www.jetbrains.com/student/">free student license</a> too) on small subsets of the data, then when it’s working, SFTP’ing the code to the server and running it once. Troubleshooting over remote connection can be annoying.</p><h3>5. Running Computations</h3><p>Now, you’re all set up to run some computations. Log back in with ssh , organise all your files, and run any code with python filename.py as you would on your local computer.</p><p>If you get a Killed response when you try and run some code, it means you don’t have enough memory to complete the job. You have two options. Either powerdown and upgrade your pricing plan, or create a Swapfile (more below).</p><p>Printing error logs will give you some more information on what has gone wrong:</p><pre>sudo cat /var/log/kern.log</pre><p>You can monitor job progress on the Digital Ocean dashboard that shows you some nice graphs of usage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9RerFXLXfI9Iwt6x1y6sA.png" /></figure><p>You can even set up alerts to get an email when a metric drops below a certain level, like CPU, which can be used to let you know when a job is done! Click on ‘Create Alert Policy’ at the top of the Graphs page to set something like this up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*F8YV_1pi4BG2LUQCM7F-0A.png" /></figure><p>Once you’re done with your processing, you can use SFTP to get your files from the cloud, and then destroy the droplet so you don’t continue to be charged for it!</p><p>Now for a word of warning; <strong>be careful when writing to file</strong>.</p><p>I wasted a lot of time running a pandas apply function, then using df.to_csv(&#39;filename&#39;) to save the results. If there are any issues with the server (which there may well be, more below), you’ll lose everything before it’s written to file.</p><p>My workaround was to loop over the entire data frame and print the result line by line:</p><pre><em>for </em>row <em>in </em>range(len(df.index)):<br>    col_value = df.ix[row,:].values[2]<br>    ind = df.index[row]<br>    with open(&quot;./data_file.csv&quot;, &quot;a&quot;) as file:<br>        file.write(ind + &#39;,&#39; + function(col_value) + &#39;\n&#39;)</pre><p>This actually wrote my data to csv , then I could just merge the data frames on their index values to line things up.</p><pre>result = pd.concat([df, new_data], axis=1, join_axes=[df.index])</pre><p>Not as pretty as apply , but sometimes when dealing with data of this size, it’s better to trade-off some performance to ensure you’re actually getting the data you want!</p><h3>6. Improving Performance</h3><p>One of the best things about DO is that you can have up to 20 CPUs in your droplet, which can all run processing in parallel. This is much faster than just processing all your data on 1 CPU.</p><p>You should know how many CPUs your plan has, but if not, you can use the following code to check:</p><pre>cat /proc/cpuinfo | grep processor | wc -l</pre><p>I have 2, so this means I can run two processes simultaneously. From what I can see, this doesn’t slow either process, so you can effectively work twice as fast if you split your task in half. The best way to do this is to split whatever data you have in half, then run the same script on each. In Python, I’d add the following code after importing your data with pandas.</p><pre>import sys</pre><pre>number_of_cores = 2<br>length_of_df = len(df.index)<br>stream = sys.argv[1]</pre><pre>if stream == 1:<br>    start = 0<br>    end = length_of_df // number_of_cores<br>else:<br>    start = length_of_df // number_of_cores<br>    end = -1</pre><pre>data_to_process = df.iloc[start:end,:]</pre><pre>output_filename = &quot;output_data_&quot; + str(sys.argv[1]) + &quot;.csv</pre><p>Then from the command line you can run</p><pre>python script.py 1</pre><p>which will process the first half of the data, and</p><pre>python script.py 2</pre><p>which will process the second. Combine the two data files at the end using</p><pre>cat output_data_2.csv &gt;&gt; output_data_1.csv</pre><h3>7. Troubleshooting</h3><p>My biggest headache was getting my scripts to run to completion. For some reason (that I never figured out), the server would just stop running my processing, and then I’d have to restart it manually. My usage graph looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*M-Nbkb5qTIM17AL1EEWhpw.png" /></figure><p>Really not ideal, especially as my college firewall blocked my connection, so I had to wait until I got home to restart things.</p><p>The first part of my solution was to figure out the re-start point in the for loop, so I wouldn’t be re-doing computation. I used the subprocess module so I could run command line functions from within a python script:</p><pre>import subprocess</pre><pre>stream = int(sys.argv[1])</pre><pre>if stream == 1:<br>    stop = 3387532<br>    data = &quot;./data.csv&quot;</pre><pre>    a = subprocess.Popen([&#39;wc&#39;, &#39;-l&#39;, data], stdout=subprocess.PIPE)<br>    wc = int(a.communicate()[0].rstrip().decode().split(&#39; &#39;)[0])</pre><pre>    start = 0 + wc</pre><p>My total number of rows in my file was 6,775,065, and I had 2 CPUs, so like above, I set my stop index to half of the file size. The subprocess.Popen returns the results of a command line function, in this case, wc -l ./data.csv , or checking the number of rows in the output data. stout=subprocess.PIPE makes the output easier to work with. The next line retrieves the actual line count of the output data, then start is set to accordingly.</p><p>This meant whenever things crashed I could simply run:</p><pre>python script.py 1; <br>python script.py 2;</pre><p>on different terminal screens and both halves of my data would restart when the appropriate place. A good result!</p><p>However, this didn’t do anything to stop my server crashing, nor restart processing automatically after it did. Some research led me to crontabs, which allow functions to be evaluated at specific time periods. You can see current crontabs with:</p><pre>crontab -l</pre><p>There shouldn’t be anything there, so you can go ahead and create one using:</p><pre>crontab -e</pre><p>The first time, you’ll be asked to select a text editor, Nano is the easiest, but this can be changed later by running&#39;select-editor&#39;</p><p>I won’t go into too much detail, but the last line of the file looks like this:</p><pre># m h  dom mon dow   command</pre><p>This stands for minute, hour, day-of-month, month, day-of-week and command. This allows you to set a command to be run at a specific interval. A few examples:</p><pre>*/10 * * * * eval &quot;python3 script.py&quot;</pre><p>Runs a script every 10 minutes.</p><pre>10 * * * * eval &quot;python3 script.py&quot;</pre><p>Runs a script at 10 minutes past the hour every hour.</p><pre>10 5 * * 3 eval &quot;python3 script.py&quot;</pre><p>Runs a script at 10 past 5 every Wednesday.</p><p>You get the idea. For me, I wanted to check every 10 minutes if my server had crashed, and if so, restart it. So my crontabs were:</p><pre>*/10 * * * * eval &quot;python3 sys_test_1.py&quot;<br>*/10 * * * * eval &quot;python3 sys_test_2.py&quot;</pre><p>(I had to have two because of the difficulties of running python scripts on separate CPUs from the same file, this was just easier). There’s more of a detailed explanation of crontabs <a href="https://www.digitalocean.com/community/tutorials/how-to-schedule-routine-tasks-with-cron-and-anacron-on-a-vps">here</a> if you’re interested.</p><p>Then my file sys_test_1.py looked something like this:</p><pre>data = &quot;./data.csv&quot;</pre><pre>a = subprocess.Popen([&#39;wc&#39;, &#39;-l&#39;, data], stdout=subprocess.PIPE)<br>wc_1 = int(a.communicate()[0].rstrip().decode().split(&#39; &#39;)[0])</pre><pre>if wc_1 &gt; 3387530:<br>    exit()<br>else:<br>    time.sleep(15)</pre><pre>    b = subprocess.Popen([&#39;wc&#39;, &#39;-l&#39;, data], stdout=subprocess.PIPE)<br>    wc_2 = int(b.communicate()[0].rstrip().decode().split(&#39; &#39;)[0])</pre><pre>    if wc_1 == wc_2:<br>        subprocess.call([&quot;python3&quot;, &quot;run_comp.py&quot;, &quot;1&quot;])</pre><p>So I check the number of lines in my file, and if it’s over some threshold (ie close to the end of the required computation), exit. Otherwise, wait 15 seconds and check the file length again. If they’re the same, it implies no computation is ongoing, so it calls the computation script from the command line.</p><p>Notice I’ve specifically called &#39;python3&#39; , even though I have an alias set so alias python=&quot;python3&quot; in my bash profile. Calling python scripts with subprocess appears to ignore aliases, so keep that in mind.</p><p>So with this running every 10 minutes, I had a way to check if anything was wrong, and if it was, restart processing automatically. Since I fixed this, my server has run non-stop, with any crashes caught quickly and processing restarted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*PrCxDPraXLqw9qf46cBIbQ.png" /></figure><p>Perfect!</p><p>And there you have it! You now know how to create, setup, upload data, and run scripts on a cloud server! Big Data, here you come!</p><p>There’s more of an explanation on swapfiles below, but that’s optional reading…</p><p>If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><h3>Swapfiles</h3><p>Swapfiles are a way to give your droplet extra memory by partitioning part of the hard drive. That way, when the system runs out of memory, it can save some data to disc and retrieve it later. This will let you do more with cheaper plans, but is considerably slower. Keep in mind that it’s probably better just to upgrade your plan.</p><p>To create a swapfile, run</p><pre>sudo fallocate -l 4G /swapfile</pre><p>where 4G represents the size of the file, ie 4 gb. This is the size that you want the memory to take. Too big and you won’t have room for your other files, too small and you’ll still run out of memory. 4 gb should be fine.</p><p>You need to then give write permissions to that directory, create the swapfile, and activate it:</p><pre>sudo chmod 600 /swapfile<br>sudo mkswap /swapfile<br>sudo swapon /swapfile</pre><p>Open up the fstab file:</p><pre>sudo nano /etc/fstab</pre><p>and add to bottom of the file:</p><pre>/swapfile none swap sw 0 0</pre><p>There’s a parameter called swappiness (awesome name) that sets how much and how often memory is swapped to disc. The higher the value, the more often it swaps. We don’t want it to swap that much, so we want to change the default value (60%) to 10%.</p><pre>sudo sysctl vm.swappiness=10</pre><p>To set this as default, open:</p><pre>sudo nano /etc/sysctl.conf</pre><p>and add to bottom of the file:</p><pre>vm.swappiness=10</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2442db4246f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/lessons-learned-digital-ocean-for-python-3-e2442db4246f">Lessons Learned: Digital Ocean for Python 3</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[Using Unsupervised Learning to optimise Children’s T-shirt Sizing]]></title>
            <link>https://medium.com/data-science/using-unsupervised-learning-to-optimise-childrens-t-shirt-sizing-d919d3cbc1f6?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d919d3cbc1f6</guid>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Thu, 04 May 2017 14:31:21 GMT</pubDate>
            <atom:updated>2017-05-05T09:58:12.859Z</atom:updated>
            <content:encoded><![CDATA[<p>All the code and data for this post are available on <a href="https://github.com/Padam-0/cluster_t-shirt_sizing">Github</a>. This analysis uses Python 3, Numpy 1.12.0, Pandas 0.19.2, Scikit-Learn 0.18.1, matplotlib 1.4.3 and Seaborn 0.7.1.</p><p>Unsupervised learning and specifically K-Means aren’t overly difficult to understand when dealing with low dimension data. However, as the number of variables scales up, it can be difficult to understand what you’re looking at, let alone trying to figure out if it’s of any use.</p><p>Using a large dataset of body measurements of children, the aim of this exploration was to use unsupervised learning to come up with three distinct T-shirt sizes that would fit the majority of children in either Small, Medium, or Large.</p><p>The dataset used in this exploration contained anthropometric data for children, and some demographic-related attributes. There were 3,900 observations for 122 variables.</p><h3>Data Cleaning</h3><p>The first step was to examine the data, and it was seen that many objects contained empty values. As such, any variables which contained more than 2,000 Null values (zero in this case) were removed.</p><pre>import pandas as pd</pre><pre>df = pd.read_csv(&#39;data.csv&#39;, index_col=0)<br><br>remove_cols = []<br><br><em>for </em>i <em>in </em>df.columns:<br>    <em>if </em>3900 - df.loc[:,i].astype(bool).sum() &gt; 2000:<br>        remove_cols.append(i)<br><br>df = df.drop(remove_cols, axis = &#39;columns&#39;)</pre><p>76 variables were removed using this criteria.</p><p>As stated above, the dataset contains both anthropometric and demographic data. Demographic data was deemed to not be useful in this situation, as the aim was to design T-shirt shirts, so 22 demographic variables were also removed.</p><pre>demographic_attributes = [&#39;AGE IN YEARS&#39;, &#39;LOCATION&#39;,<br>       &#39;BIRTH DATE&#39;, &#39;MEASUREMENT DATE&#39;, &#39;MEASUREMENT SET TP&#39;,<br>       &#39;MEASURER NUMBER&#39;, &#39;COMPUTER NUMBER&#39;, &#39;RACE&#39;, &#39;GRADE LEVEL&#39;,<br>       &#39;HANDEDNESS&#39;, &#39;NUMBER OF BROTHERS&#39;, &#39;NUMBER OF SISTERS&#39;, &#39;TWIN&#39;,&#39;BIRTH ORDER&#39;, &#39;MOTHERS OCCUPATION&#39;, &#39;FATHERS OCCUPATION&#39;,<br>       &#39;MOTHERS EDUCATION&#39;, &#39;FATHERS EDUCATION&#39;, &#39;YEARS IN COMMUNITY&#39;,&#39;ANTHROPOMETER NO&#39;, &#39;CALIPER NO&#39;, &#39;GIRTH NO&#39;]<br><br>df = df.drop(demographic_attributes, axis = &#39;columns&#39;)</pre><h3>Exploratory Data Analysis</h3><p>2 important variables that would have a large impact on clustering were Age (in months) and Sex (1 or 2). It was unclear whether 1 or 2 was Male or Female, but not necessary information for this analysis. An exploration of the Age range showed that there was a range from 0 to 240 months (20 years), with a median of about 128 months (10 years, 8 months).</p><pre>print(df.loc[:,&#39;AGE IN MONTHS&#39;].describe())</pre><p>It was obviously not appropriate to design a single T-Shirt sizing for all ages, so using Erect Sitting Height as a proxy for size, a plot was made to see how this measurement changed as children aged (Age 0, 1, 19 and 20 were removed as there were not enough observations for accuracy).</p><pre>shoulder_data = df[[&#39;ERECT SITTING HEIGHT&#39;, &#39;AGE IN MONTHS&#39;]]<br>shoulder_data[&#39;YEAR&#39;] = shoulder_data[&#39;AGE IN MONTHS&#39;].apply(<em>lambda </em>x: x//12)</pre><pre>x = list(shoulder_data.groupby(&#39;YEAR&#39;).mean().index[1:-2])</pre><pre>y = list(shoulder_data.groupby(&#39;YEAR&#39;).mean()[&#39;ERECT SITTING HEIGHT&#39;][1:-2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFKR2zB9wP_ma878s5BheA.png" /></figure><p>This shows a roughly linear growth rate, with two ages where there is a dramatic increase in height. 6–7 years old and 12–13 are these two age jumps where there is a visible increase growth rates. As such, there are three age intervals where shirt sizes need to be determined; 0 to 6, 7 to 12, 13 to 20. There is also scope for overlap of Small, Medium and Large across these boundaries, that is, the Large Shirt for 7–12 year olds might be a similar size to the small for 13 to 20 year olds.</p><p>Also of interest is the relationship between Sex and size. A plot of the average sitting heights per age for both Sex 1 and Sex 2 suggests that there isn’t much difference between Males and Females until around age 15, when it would be assumed that Males grow slightly taller. With this information, it is estimated that Sex 1 is Male, and Sex 2 is Female.</p><pre>shoulder_data = df[[&#39;ERECT SITTING HEIGHT&#39;, &#39;AGE IN MONTHS&#39;, &#39;SEX&#39;]]<br>shoulder_data[&#39;YEAR&#39;] = shoulder_data[&#39;AGE IN MONTHS&#39;].apply(<em>lambda </em>x: x//12)</pre><pre>y_1 = shoulder_data[shoulder_data[&#39;SEX&#39;] == 1].groupby(&#39;YEAR&#39;).mean()[&#39;ERECT &#39; \<br>                        &#39;SITTING HEIGHT&#39;][1:-2]</pre><pre>y_2 = shoulder_data[shoulder_data[&#39;SEX&#39;] == 2].groupby(&#39;YEAR&#39;).mean()[&#39;ERECT &#39; \<br>                        &#39;SITTING HEIGHT&#39;][:-1]</pre><pre>x = list(shoulder_data.groupby(&#39;YEAR&#39;).mean().index[1:-2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xN6a4MgYFOE5yfGlsy4xdw.png" /></figure><p>The other useful variable for differentiating Males and Females is Chest Circumference. The plot below shows the average measurement per age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeSgwxVDMJi7ETFDlL0yJQ.png" /></figure><p>This again shows that a major divergence occurs around age 15. As such, I figured there are 12T-Shirt sizes which need to be developed:</p><ul><li>Age 0–6 Small, Medium and Large Unisex</li><li>Age 7–12 Small, Medium and Large Unisex</li><li>Age 13–20 Small, Medium and Large Male and Female</li></ul><p>For the purposes of this exercise, I’m going to focus on Age 7–12.</p><p>A quick note here that these two graphs are somewhat contradictory. From what I can see, Chest Circumference should take into account breast size on females, and as such the divergence suggests that Sex 1 is Female, whereas the height data would suggest that Sex 1 is Male. I couldn’t find the schema for this data, and so couldn’t resolve this. Whatever the result is, just keep in mind that whenever I’ve specified Male vs Female, they may well be interchanged.</p><h3>Unsupervised Learning</h3><p>The first step was to split the data into subsets, remove rows with 0 values (59 of 1584 in this case), then converted to a numpy matrix for clustering:</p><pre>import numpy as np</pre><pre>t_shirt_columns = [&#39;CHEST CIRCUMFERENCE&#39;, &#39;WAIST CIRCUMFERENCE&#39;,<br>                   &#39;SHOULDER-ELBOW LENGTH&#39;, &#39;ERECT SITTING HEIGHT&#39;,<br>                   &#39;SHOULDER BREADTH&#39;]<br><br>young = df[df[&#39;AGE IN MONTHS&#39;] &lt; 84].loc[:,t_shirt_columns]</pre><pre>middle = df[(df[&#39;AGE IN MONTHS&#39;] &lt; 156) &amp; (df[&#39;AGE IN MONTHS&#39;] &gt;= 83)].loc[:,t_shirt_columns]</pre><pre>old_1 = df[(df.SEX == 2) &amp; (df[&#39;AGE IN MONTHS&#39;] &gt;= 156)].loc[:,t_shirt_columns]</pre><pre>old_2 = df[(df.SEX == 2) &amp; (df[&#39;AGE IN MONTHS&#39;] &gt;= 156)].loc[:,t_shirt_columns]<br><br>drop_list = []<br><em>for </em>i <em>in </em>range(len(middle.index)):<br>    <em>if </em>0 <em>in </em>middle.ix[i,:].values:<br>        drop_list.append(i)<br><br>middle = middle.drop(middle.index[drop_list])<br><br>data = middle.as_matrix()</pre><p>The next step is to decide how many clusters are in the data. We want three, but we also want them to contain enough observations that it’s worthwhile creating a specific T-shirt size for them. One way to find the number of clusters in the data is with an inertia plot, and to look for the ‘elbow’.</p><pre>import matplotlib.pyplot as plt</pre><pre>inertias = []<br>ks = range(1,11)<br><em>for </em>k <em>in </em>ks:<br>    inertias.append(KMeans(n_clusters=k).fit(data).inertia_)<br>plt.plot(ks, inertias, &#39;-o&#39;)<br>plt.xticks(ks)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wg7wQJ3r0G4zvHD0H-4GLQ.png" /></figure><p>From this, it looks like there are 2 or 3 clusters. We can also look at a Dendrogram to see what the cluster order is:</p><pre><em>from </em>scipy.cluster.hierarchy <em>import </em>linkage, dendrogram</pre><pre>mergers = linkage(data, method=&#39;complete&#39;)<br>dendrogram(mergers, leaf_rotation=90, leaf_font_size=6)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Yx_nzKHk2WDIOtNMRacrQ.png" /></figure><p>This looks good, there are two easily identifiable clusters, Green and Red. The third isn’t so easy to see, but we can sort this out. This is promising.</p><p>To find out clusters, it’s time to perform K-Means clustering. Our aim is to find three clusters which represent a large proportion of the observations. Starting with n_clusters=2, I ran the following code until I had three large distinct clusters. This worked with 3 clusters.</p><pre><em>from </em>sklearn.cluster <em>import </em>KMeans</pre><pre>kmeans = KMeans(n_clusters=3).fit(data)<br>samples = kmeans.predict(data)<br><br>names = middle.index<br><br>ns = pd.DataFrame({&#39;names&#39;: names, &#39;cluster&#39;: samples})<br>clusters = ns.set_index(names).iloc[:,0]<br><br>print(clusters.value_counts())</pre><p>Printing the number of instances in each cluster shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*Pk5CfKWge3kC65aih0QcGA.png" /></figure><p>Which is fantastic. We have captured all of the observations into three distinct groups! Now, looking at the cluster centres, we can see how different they really are:</p><pre>print(kmeans.cluster_centers_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSF5XpHa6jAy0KECu1S5XA.png" /></figure><p>Which is fantastic! We can see that across all categories, Cluster 0 contains the smallest values, Cluster 1 contains the biggest values, and cluster 2 contains values in the middle. This means that these centroid values represent the middle values for three distinct clusters of body types, and should be the measurements used when making T-Shirts for kids between the ages of 7 and 12.</p><h3>Extensions</h3><p>Now, manufacturing T-Shirts in different sizes is annoying, so manufacturers would want to use the same templates across as many body types as possible. As such, I hypothesised before that there may be Small / Large overlaps across age group boundaries. Let’s test that theory.</p><p>Doing the same process above for the youngest age bracket, we produce the following dendrogram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHz5Jy411FSoT26GE4nrNg.png" /></figure><p>This isn’t as clean as the one above, as we have a cluster on the left which is highly similar, but only contains a small number of values. This isn’t great, but doesn’t really matter. We will see where these belong when we cluster with KMeans. Again, starting with n_clusters=2 and gradually increasing this value, we see that with 4 clusters that the majority (95.5%) of the data is clustered into 3 good clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*FZwsQ_xFdVKDgKOo1lyoow.png" /></figure><p>Looking at the cluster centres (ignoring Cluster 2 as it contains too few observations):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u95hXbEPAPgyCIsTVcF-sA.png" /></figure><p>Again, we see that there are 3 distinct Small (Cluster 0), Medium (Cluster 3) and Large sizes (Cluster 1). Unfortunately, there doesn’t seem to be much similarity between the large size in this age group and the small size in the middle age group.</p><p>A similar process can be carried out for the older age groups, and the sizes of the Small sized cluster for Males and Females are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcnZ_nhd5qFCvGmBmTNg2A.png" /><figcaption>Small Sizing for Males</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qk1ZDwTiua4nG4m1ZbHBw.png" /><figcaption>Small Sizing for Females</figcaption></figure><p>As expected, the small size for Males and Females differs quite a lot for some variables, most notably Shoulder Breadth. So the initial hypothesis that separate genders would need different sizes in the 13–20 age group appears correct.</p><p>The other point of note is that the small size for Males in the 13–20 age group isn’t that close to the large size in the 6–12 age group, as there is a large discrepancy in waist size. This too is probably to be expected</p><h3>Conclusions</h3><p>This analysis shows the results that even a simple clustering analysis can produce from a large, dirty data set. As always, dealing with erroneous and irrelevant data is critical as always, garbage in = garbage out. Through some simple trial and error clustering, we’ve identified key measurements for T-Shirt design across 3 age groups, and ruled out the possibility of using one size for multiple age groups! Not bad for 145 lines of code!</p><p>Again, all the code and data for this analysis are available at <a href="https://github.com/Padam-0/cluster_t-shirt_sizing">https://github.com/Padam-0/cluster_t-shirt_sizing</a></p><p>If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d919d3cbc1f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-unsupervised-learning-to-optimise-childrens-t-shirt-sizing-d919d3cbc1f6">Using Unsupervised Learning to optimise Children’s T-shirt Sizing</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[Utilising epidemic modelling to improve advertising click rates on Facebook]]></title>
            <link>https://medium.com/data-science/utilising-epidemic-modelling-to-improve-advertising-click-rates-on-facebook-6f294205a43f?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f294205a43f</guid>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[social-media-marketing]]></category>
            <category><![CDATA[social-network-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Mon, 24 Apr 2017 13:53:40 GMT</pubDate>
            <atom:updated>2017-04-24T19:14:56.207Z</atom:updated>
            <content:encoded><![CDATA[<p>This article was co-written with <a href="https://twitter.com/Mcsweena">Andy McSweeney</a></p><p>Social media yearly advertising budgets have seen massive growth in the last few years, and are projected to reach <a href="https://blog.hootsuite.com/social-media-advertising-stats/">$17.34 billion by 2019</a> in the US alone. The ability to target huge markets directly, demonstrated by social media companies such as Facebook, Twitter and Snapchat, has given marketing agencies a completely new, and more powerful way to reach their customers.</p><p>To keep advertisers happy, the methods social media companies use to effectively distribute ads through their network need to be efficient in targeting those users most likely to respond to an advertisement. As a fee for their services, Facebook charges <a href="http://fitsmallbusiness.com/how-much-does-facebook-advertising-cost/">‘per view’ and ‘per click’</a>, so advertisers must balance their costs against the number of users they expose.</p><p>It is clear that Facebook calculates a likelihood of responding to an ad per user, and only targets those with high likelihoods. This is efficient for marketers, as their ‘per view’ cost is fixed, and ‘per click’ costs are theoretically offset by sales. What is unclear, is if Facebook utilises friendship information, more specifically, the assumption that:</p><blockquote>If a user clicks on an ad, the probability their connections will also click on the ad increases.</blockquote><p>Based on this assumption, can the user network be explored to ‘spread’ the ad in a viral manner to achieve a similar (or superior) numbers of clicks, while showing the ad to fewer people?</p><p>To explore this idea, we took a small sub-graph, the <a href="https://snap.stanford.edu/data/egonets-Facebook.html">Facebook ‘Social Circles’ </a>dataset which consists of 4,039 nodes and 88,234 edges. To aid understanding, it’s better if you think of this network as users who like a page on Facebook. There are approximately 4,000 of them, and they’re all friends with at least one other person who likes the page. Some of them are very popular, one has 1,045 friends who also like the page, whereas 75 of them only know 1 other person who likes the page. Overall, the degree distribution looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxodaTooJPYI25RvSs_hWw.png" /><figcaption>Lots of nodes have low degree, a few have a high degree. Turns out that’s pretty normal for Facebook</figcaption></figure><p>Now, based on a number of features (how often they like the pages posts, how often the view the page, similar pages they like etc), Facebook has a decent idea of how much each person really likes the subject.</p><p>Our second assumption is that the probability distribution of a user interacting with the page is pretty similar to the degree distribution of the page’s users. A few are really likely to interact with it, and a lot are fairly ambivalent. That’s why you see pages with thousands of likes, only generating a few hundred likes on their posts.</p><p>This is an exponential distribution, and if we replace ‘probability of interacting with the page’ with ‘probability of clicking on an ad that relates to the topic of the page’, and we have a crude measure for the underlying probability of users clicking on ads. We can’t measure this exactly, as we don’t have the data Facebook does, but we have a starting point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn2gccqysJeG5gHlcqb33g.png" /><figcaption>Per user likelihood of clicking on an ad that relates to the group. Most users have a small chance, and a few have a decent chance.</figcaption></figure><p>To come up with a ‘base-case’ to compare our epidemic models on, we took the path of least resistance. Show the ad to every member of the group, and using independent Bernoulli trials, see how many responded based on their underlying probability.</p><p>We ran 1,000 trials, and saw an average of 88.54 clicks, on 4039 views, or a clicks per view ratio of 0.0198. Clicks per view (CPV) and total number of clicks are the two metrics important to advertisers here.</p><p>Knowing the number we had to beat, we devised a way to utilise information about how users are connected to spread the ad more slowly, but with hopefully better results</p><p>To start with, the underlying probability of each user was determined using an exponential distribution with mean 0.03, as in the base-case. Each connection between users was given a ‘strength’ between 0 and 1, based on how many connections the users shared. If two users both had 12 friends, but 8 of those were common to both, their strength was 66%.</p><p>From this, a line was drawn in the sand. A users connections who shared more than 50% of friends were deemed ‘strong’ connections, and those less than 50% ‘weak’ connections. This is fairly easy to visualise, just think about a relationship with a close friendship group, where everyone knows everyone, against that with a colleague or relative who you know, but isn’t really friends with your friends.</p><p>With this in mind, 3 factors remained to be determined.</p><ul><li>What was the actual effect on a users probability of clicking the ad, given a connection of theirs had previously clicked the ad?</li><li>How ‘contagious’ the ad was, or how would it spread from user to user?</li><li>How should the ad get started, or how many ‘Patient Zeros’ were required?</li></ul><p>All these factors had to be set between two limits. Too low, and the ad would die out quickly, maybe generating a high Click per View ratio, but a low number of total clicks. Bad for advertisers. Too high, the assumptions were unrealistic and wouldn’t be applicable.</p><p>The first factor was set at a maximum increase of 10%, scaled linearly by the strength of the friendship. That is, if a user clicked the ad, all of their connections would see their underlying probability of clicking the ad rise by an amount. If the strength of friendship between those two people was 60%, the amount would then be 6%. If the strength between the people was 25%, the amount would be 2.5%. This was recalculated after every iteration, and users could see multiple probability increases if more and more of their friends clicked on the ad.</p><p>Next, the virality of the ad was determined by an ‘Ad-Serve’ composition. That is, when a user clicked an ad, how many, and which of their connections would be shown the ad in the next iteration? Ad-Serve compositions ranged from 10 Strong Connections &amp; 0 Weak Connections, to 16 Strong Connections &amp; 24 Weak Connections. 28 compositions were tested all together, with some combination of Strong and Weak friends with 10, 20, 30 or 40 people being shown the ad.</p><p>The aim behind varying these numbers was simple. While Strong Connections saw the highest increase in probability after their friend clicked the ad, showing it only to strong connections could get the ad stuck in small communities, or sub-graphs of the network, and limit its propagation. On the other hand, only showing it to Weak Connections risked the ad dying out as there was a lower probability adjustment. We wanted to test how this balancing act influenced results.</p><p>The final factor, the ‘seed’ group, or the number of ‘Patient Zeros’ was varied between 10 and 40. As the assumption was that these people were the first to click on the ad, they were selected as those with the overall highest original probability. This assumption was a bit of a stretch, especially for the 40 person seed group, but more on this later.</p><p>With all factors set, the simulation was set up to run for each Ad-Serve composition, for each seed group size, on 20 random graphs (as the original distribution of probabilities was stochastic, we replicated the simulation for more generalised results). Each simulation concluded when 4, 000 users had seen the ad, or when no new clicks were generated in an iteration.</p><p>From the first simulation, we took the ‘best’ Click per View ratio (for all the seed group sizes) and mapped the results against Ad-Serve composition and Total Additional Clicks Generated (TACG, or total clicks minus the size of the seed group). The results are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQCrIfxDQJfJcaiTWIGAng.png" /></figure><p>What we saw first was that our original fears were confirmed. Small Ad-Serve compositions were generating high Clicks per View (red dot), but a low overall number of clicks (black line). To avoid this, we filtered the dots based on total number of views. Blue dots reached the 4000 view threshold, red ones didn’t (on average).</p><p>With this data removed, the results were inspiring. The best performing Ad-Serve ratio was 20 Strong / 20 Weak, seeded with only the 12 initial highest probability users.</p><blockquote>This produced on average 122.45 additional ad clicks from 4025 views, at a CPV ratio of 0.0304, an increase over the base case of 53%!</blockquote><p>Interestingly, there didn’t appear to be a whole lot of difference between the different Ad-Serve compositions. Even though those with a high number of Strong Connections had a probabilistic advantage, it appears that the <a href="https://www.jstor.org/stable/2776392">strength of weak ties</a> evened this out!</p><p>This was very interesting, as we showed that by simply slowing down the movement of ads across a network, Clicks per View could be dramatically increased.</p><p>However, as mentioned above, we weren’t in love with some of our assumptions. The underlying probability distribution, and the selection of the seed users was essentially random, and we wondered if there was a better way to model this.</p><p>We then attempted to model the real-world trend of social media ‘influencers’. Over the past few years, the rise of the ‘influencer’ on social media has seen massive growth. An influencer can be defined as a someone who has a large social media following and is paid by companies to promote products to their network.</p><p>Based on the degree of a user (number of connections), we could use this as a proxy for their influence in the network. We then let the underlying probability of a user clicking the ad be equal to their number of friends, divided by the largest number of friends of anyone in the network (1045). This produced a probability distribution that was very close to an exponential! And with a small tweak (multiplying all probabilities by 0.7), we produced a distribution very close to our original assumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04ewUZwmIZ8CrgFHg7zm8Q.png" /></figure><p>The big difference now was that underlying probabilities were no longer stochastic! This meant we had a lot more confidence in the results of our simulation.</p><p>Like the original simulation, the seed users were still the users with the top probabilities in the group, but now these users were the actual influencers in the group. Instead of thinking of these people as ‘most likely’ to click on the ad, they could actually be those users paid to promote the ad. This was a much more organic and realistic assumption as to how ads were introduced to the ecosystem.</p><p>The second change we made was how users probabilities were adjusted after a connection of theirs clicked the ad. Before, it was the strength of connection times 10%. Now it was strength of connection times 5%, plus 15% times influence. This represents the fact that users are more likely to be influenced by someone famous within a network, as opposed to ‘just some guy’.</p><p>The 5 + 15 coefficients are purely assumptions, but the beauty of the model is that the actual numbers are somewhat irrelevant. If they were 0% and 0%, we would be back at the base case. If the model shows any improvement at all with any non-zero coefficients, it’s proof that the viral advertising method works!</p><p>With that being said, let’s look at the results. Simulations were run in a similar manner as the original case, except without the 20 random graphs (as the graphs are now deterministic).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5Psta_4rpQ9kynJ6titaQ.png" /></figure><p>This graph shows more or less the same results as the original case, but with higher Click per View and Total Additional Clicks Generated! In fact, the best case generated a 0.0341 CPV using an Ad-Serve composition of 36 strong and 4 weak, seeded with 24 influencers. This generated an additional 137 clicks.</p><p>24 influencers was kind-of a lot, they’re not cheap those influencers, so we looked to see if there was a slightly worse result that used less influencers. And there was:</p><blockquote>The Ad-Serve composition of 16 strong and 24 weak generated a CPV ratio of 0.0335 and 135 additional clicks, using only 14 influencers! 70% better than the base-case!</blockquote><p>So we had seen that our Ad-Serve viral marketing model was producing fantastic results on a small-graph, we wanted to see how it would fare against a bigger model. Using the Albert-Barabási preferential model, we generated larger graphs which closely mimicked the degree distribution seen in the original Facebook graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXmTpowxm00e1TjCjF513g.png" /><figcaption>The tails of each distribution are a little different, but they’re close enough for what we’re trying to do</figcaption></figure><p>We generated graphs with 4,039 (to compare directly), 10,000 and 20,000 nodes, in each case attaching 20 additional edges to each new node (the average degree in the original Facebook graph was ~21).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSADmemLB0ohhDWgatfGYw.png" /></figure><p>Reassuringly, these networks produced very similar results and gave confidence the model could be scaled to far larger, real world graphs developed by Facebook or Twitter.</p><p>The final insight from this modelling exercise is that regardless of what the actual adjustment values, any increase in probability of clicking an ad a user sees by virtue of having a friend click the ad, a viral marketing model will generate CPV and TACG increases, and hence revenue increases for Social Networks and advertisers.</p><p>All the code and a slightly more technical report are available at <a href="https://github.com/Padam-0/facebook_viral_advertising">https://github.com/Padam-0/facebook_viral_advertising</a></p><p>If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter <a href="http://twitter.com/padams02">@padams02</a>.</p><p>Once again, a huge thanks to <a href="http://github.com/mcsweena">Andy McSweeney</a> for his contribution on this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f294205a43f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/utilising-epidemic-modelling-to-improve-advertising-click-rates-on-facebook-6f294205a43f">Utilising epidemic modelling to improve advertising click rates on Facebook</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[Did Pokemon GO Try Too Hard to be Agile?]]></title>
            <link>https://medium.com/@padam0/did-pokemon-go-try-too-hard-to-be-agile-d226456cf7a4?source=rss-e4afb73432fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d226456cf7a4</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[pokémon-go]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <dc:creator><![CDATA[Peter Adam]]></dc:creator>
            <pubDate>Sat, 15 Apr 2017 10:11:28 GMT</pubDate>
            <atom:updated>2017-04-15T10:18:26.557Z</atom:updated>
            <content:encoded><![CDATA[<p>When Pokemon GO hit the App Store in July of 2016, it quickly became a global phenomenon. What was also quickly apparent, was that the game had flaws that undermined the user experience, and that users were leaving the game in large numbers.</p><p>While the game issues have received the lions share of blame for the loss of users, Niantics apparent lack of preparation in dealing with these issues has also (rightly) been criticised.</p><p>However, blaming Niantic for not correctly anticipating the response to Pokemon GO is somewhat shortsighted. Operating under the assumption that Hanke and employees are smart, talented and driven to produce the best possible product, what specific part of their decision making process was responsible for Niantic being unable to deal with the success of the game?</p><p><strong>Is the </strong><a href="https://en.wikipedia.org/wiki/Agile_management"><strong>project management framework</strong></a><strong> utilised (Agile) responsible?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqYochTXn9Rbm42_XDRWHQ.jpeg" /></figure><h3>Niantic and Pokemon GO</h3><p>To attempt to understand how Niantic found itself in this position, some context is required.</p><p>The first iteration of <a href="https://www.nianticlabs.com/">Niantic</a> began with <a href="https://en.wikipedia.org/wiki/John_hanke">John Hanke</a> developing an overlay for Google Maps in 2010. This led to the creation of the company within Google, and the development of 2 apps, Field Trip and Ingress, based on Augmented Reality technology. When Google announced the creation of Alphabet in August of 2015, Niantic Labs, already a somewhat standalone company within Google, was <a href="http://www.androidheadlines.com/2016/07/google-niantic-labs-parted-ways-pokemon-go.html">spun</a> <a href="http://www.androidheadlines.com/2015/08/niantic-labs-maker-of-ingress-spins-off-from-google.html">off</a>.</p><p>The rationale for this decision was partly based on the perception that Niantic ‘<a href="https://www.androidheadlines.com/2016/07/google-niantic-labs-parted-ways-pokemon-go.html">wasn’t as agile</a>’ as other startups it was competing against. Running the company outside the Alphabet umbrella allowed Niantic to truly adopt Agile philosophies. In a techcrunch.com interview, Hanke said of the spinoff from Google,</p><blockquote><a href="https://techcrunch.com/2015/10/15/gotta-raise-them-all/"><em>Being independent allows us to be more nimble across the board</em></a></blockquote><p>In September of 2015, Niantic announced that it was developing Pokemon GO, and a month later announced it had raised $20m of funding from Google, The Pokemon Company, and Nintendo.</p><p>Pokemon GO launched on <a href="http://www.forbes.com/sites/ryanmac/2016/07/26/monster-game/#69ee170622c0">July 6th, 2016</a> to a huge response from fans. It had the biggest opening week of any app according to Apple. Estimates suggested that 1 in 10 Americans played the game, and that it was generating $6m USD in daily revenue from US players alone. Despite only being available in 3 countries at launch, players all around the world spoofed their GPS locations or created fake app store accounts to play. Hillary Clinton referenced the game on the campaign trail, and multiple <a href="http://www.politico.eu/article/norways-prime-minister-caught-playing-pokemon-go-in-parliament/">Norwegian members of parliament</a> were caught playing the game while in chambers.</p><p>All metrics were smashed, with Daily Active Users reaching <a href="http://www.bloomberg.com/news/articles/2016-08-22/these-charts-show-that-pokemon-go-is-already-in-decline">45 million</a> by the 3rd week of July (2 weeks after launch), and Time Spent In App beating even <a href="https://techcrunch.com/2016/07/13/pokemon-go-tops-twitters-daily-users-sees-more-engagement-than-facebook/">Facebook’s numbers</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*SZ66CKMAt9q7HFrO4uNifg.png" /><figcaption>I think we know where this is going…</figcaption></figure><h3>Niantic and Agile</h3><p>While Hanke and Niantic have not publicly commented on Project Management methodologies utilised during the development of Pokemon GO, we can infer from the speed of development and the incremental rollout of Pokemon GO that an <a href="http://www.droid-life.com/2016/07/25/pokemon-go-sdcc/">agile framework</a> was used.</p><p>The initial release of Pokemon GO has been considered a <a href="https://www.itx.com/ITX-Blog/Article/408/Pokemon-GO-is-a-Minimal-Viable-Product">Minimum Viable Product</a>, or</p><blockquote><a href="http://www.startuplessonslearned.com/2009/08/minimum-viable-product-guide.html">“… that version of a new product which allows a team to collect the maximum amount of validated learning about customers with the least effort.”</a></blockquote><p>Niantic utilised this popular Agile technique of maximising capital efficiency, which also quickly creates a <a href="https://www.itx.com/ITX-Blog/Article/408/Pokemon-GO-is-a-Minimal-Viable-Product">healthy backlog to feed Scrum teams</a>. The MVP method is the quickest way to develop a ‘<a href="http://scrumandkanban.co.uk/what-is-an-mvp/">Build-Measure-Learn</a>’ feedback loop upon which Scrum thrives.</p><h3>Pokemon GO and Users</h3><p>With the release of Pokemon GO, the Scrum Backlog filled up quickly. Despite the apps popularity, it was plagued by <a href="https://support.pokemongo.nianticlabs.com/hc/en-us/articles/221958208-Known-Issues">issues</a>. Server overloads prevented millions from playing each day. Buggy GPS tracking means players were engaging with the game but the game was giving nothing back. Constant app crashes meant restarting progress constantly. Crippling battery usage resulted in a boom for portable power banks, but constant frustration from players.</p><p>Teams worked quickly to resolve these issues, but more kept appearing. As more servers were bought online, the infamous ‘Three Step Bug’ appeared. At San Diego ComicCon, Hanke plead with players to stick by the app, promising many more features, and that only <a href="http://www.droid-life.com/2016/07/25/pokemon-go-sdcc/">10%</a> of the envisaged final product had been released to players. He also addressed the ‘Three Step Bug’, promising that Niantics engineers were <a href="http://www.businessinsider.com/pokemon-go-niantic-san-diego-comic-con-2016-2016-7">working hard to fix it</a>. Despite this, within a week the ‘Pokemon distance indicator’ that was affected by the bug was simply <a href="http://kotaku.com/thats-one-way-to-fix-pokemon-gos-three-step-glitch-1784589719">removed from the game</a>.</p><p>These promises and what work Scrum teams were making on the backlog did little to appease annoyed users. By mid-August, 6 weeks after launch, Bloomberg <a href="http://www.bloomberg.com/news/articles/2016-08-22/these-charts-show-that-pokemon-go-is-already-in-decline">estimated</a> that Daily Average Users had dropped to 30 million, and further to <a href="http://expandedramblings.com/index.php/pokemon-go-statistics/">20 million</a> by October. Daily Time Spent in App was down to <a href="http://expandedramblings.com/index.php/pokemon-go-statistics/">26 minutes</a>, half that of <a href="http://www.businessinsider.com/how-much-time-do-people-spend-on-facebook-per-day-2016-4">Facebooks</a> which they had previously topped. Daily revenue was <a href="https://thinkgaming.com/app-sales-data/130634/pokemon-go/">down 75%</a> from the peak to USD 1.5 million per day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjQ0GK-euc8uSnu8jTNQWw.png" /><figcaption>Estimates become sparse after August, but the overall trend is obvious</figcaption></figure><p>While these numbers are still very strong, and the estimated <a href="http://expandedramblings.com/index.php/pokemon-go-statistics/">USD 500</a> million of revenue generated by the app represents a huge return on investment for Niantic and its investors, one has to wonder about the amount of money left on the table.</p><h3>Agile and Results</h3><p>The Minimum Viable Product approach to building a Scrum backlog works well when a company can control the level of reach their product has. Software firms creating products for clients are able to limit distribution, and hence the impact of flaws in the MVP. Companies creating products that already have a huge viral following should be careful when following in Niantics footsteps, as even the most loyal fans only have so much patience.</p><p>The <a href="https://en.wikipedia.org/wiki/Scrum_(software_development)#Values">Scrum philosophies</a> may have been to blame for some of Niantics shortcomings in developing Pokemon Go. Prioritising ‘Individuals and Interactions over Processes and Tools’ may have lead to oversights in rigorous testing of the weakest links of <a href="http://blog.smartbear.com/performance-monitoring/pokemon-go-software-quality-lessons/">system architecture</a>. ‘Responding to Change over Following a Plan’ may have lead to overconfidence in the MVP and Niantics ability to fix problems as they arose, not before they arose.</p><p>Finally, Niantic appears to have suffered from Confirmation Bias when planning release scenarios for the app. Not only did they massively underestimate user demand, but the sometimes strange locations of <a href="http://www.rollingstone.com/culture/pictures/pokemon-go-10-worst-pokestop-locations-20160713/the-white-house-20160713">poke-stops</a>, <a href="https://www.theguardian.com/technology/2016/jul/10/pokemon-go-armed-robbers-dead-body">robberies</a>, and ‘<a href="http://www.latimes.com/local/lanow/la-me-ln-san-diego-dead-body-pokemon-go-20160715-snap-story.html">unexpected discoveries</a>’ show that not enough effort was put into truly understanding what effect the game would have on people’s lives.</p><p>While Niantics Agile development of Pokemon GO cannot be considered a failure (it was a huge financial success and continues to generate substantial revenue), it provides valuable insights to the shortcomings of Scrum and Agile.</p><p>Note: This article was written in October 2016, some figures / links may be out-of-date, but the overall argument isn’t affected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d226456cf7a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>