<?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 Xander Lewis on Medium]]></title>
        <description><![CDATA[Stories by Xander Lewis on Medium]]></description>
        <link>https://medium.com/@xanderlewis?source=rss-7889d15ac6ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Qzo1gUDYjrwA9ejsn0w3FA.jpeg</url>
            <title>Stories by Xander Lewis on Medium</title>
            <link>https://medium.com/@xanderlewis?source=rss-7889d15ac6ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:22:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xanderlewis/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[Learning this way feels wrong, but it turns out it’s often far more effective]]></title>
            <link>https://medium.com/@xanderlewis/learning-this-way-feels-wrong-but-it-turns-out-its-often-far-more-effective-9a0de5d043f6?source=rss-7889d15ac6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0de5d043f6</guid>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[knowledge]]></category>
            <dc:creator><![CDATA[Xander Lewis]]></dc:creator>
            <pubDate>Mon, 25 Jun 2018 16:27:33 GMT</pubDate>
            <atom:updated>2018-06-25T16:27:33.636Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tolerate unresolved references. Resist the temptation to traverse the knowledge tree depth-first, and take a breadth-first approach instead.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Don6Zyqz0cq-WQzrY0abAA@2x.jpeg" /></figure><p>When learning something, especially if it is a topic within a very large subject, sometimes, although it may seem counter-intuitive and uncomfortable at first, it is beneficial to resist the temptation to start with the basics. When reading an article on, say, Wikipedia, upon coming across a <strong>theorem</strong> or an <strong>equation</strong> or a <strong>quote</strong> that you don’t immediately recognise, don’t be tempted to jump straight into the exponentially branching rabbit-hole that is the world of hyperlinks. If you’re anything like me, you’ll start clicking through onto every page of information possible, including things you hitherto thought you understood, eventually beginning to doubt that you can even comprehend what it means to <em>think</em> anymore.</p><p>Not understanding every bit of terminology to the highest degree and not understanding every single reference to another piece of knowledge is not an indication of a lack of real understanding, but is simply an indication of a lack of contextual grounding. These ‘lower level’ gaps can be filled in later easily, and sometimes, despite how wrong it may feel, it is, in my experience, far more painful to try to build up from these low level blocks than it is to start high and simply fill in the gaps later.</p><p>Don’t worry about the possibility of someone coming up to you one day and saying, ‘Yeah, but do you actually understand how it works underneath? You may be able to program in C, but do you really understand what the machine code underneath is doing?’. You can achieve great things and have a solid, genuine understanding of a problem without ever needing to understand the lower levels. Sure, often it helps, and I will <em>always</em> believe that eventually you should go back and fill these things in, but when you’re learning something for the first time, perhaps getting a grip of the layers from the top down is the best and most rewarding way in. I have always been a strong believer in ‘building it up from first principles’, but I realise now that actually, <em>pragmatically</em>, you’re often better off just getting on with it and learning about the higher levels first.</p><p>Don’t be afraid to let others handle the lower levels, and to build your understanding on top of theirs.</p><p>This whole idea may be obvious to you—I don’t know. But it wasn’t to me, and so I am writing it down in the hope that I can remember it next time I feel like I’m about to stumble into <strong>hyperlink hell</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0de5d043f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting colours from an image using k-means clustering]]></title>
            <link>https://medium.com/data-science/extracting-colours-from-an-image-using-k-means-clustering-9616348712be?source=rss-7889d15ac6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/9616348712be</guid>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Xander Lewis]]></dc:creator>
            <pubDate>Sat, 09 Jun 2018 13:58:56 GMT</pubDate>
            <atom:updated>2021-05-29T00:25:54.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kdo6nq2JG7xbXZkA" /><figcaption>Photo by <a href="https://unsplash.com/@shawnanggg?utm_source=medium&amp;utm_medium=referral">@shawnanggg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The problem</h4><p>I wanted to write some software that would allow me to extract a set of colours from an image, and do it in a way that seems natural and takes human perception into consideration. A colour scheme can often sum up the ‘vibe’ of an entire image, and so I thought it would be a useful thing to be able to do.</p><p>So… I spent some time thinking of some ways that I could do this. I devised some fairly simple algorithms that would, for example, chop the image regularly into chunks and output the mean colour of each of these parts. Maybe extra layers could be added where the chunks are compared to each other and joined into groups, and maybe each colour could be recursively combined with another until the desired number of colours is reached. I quickly realised, though, that this problem had already been solved in the general case, and in a way that will work quite nicely.</p><h4>The solution</h4><p><a href="https://en.wikipedia.org/wiki/K-means_clustering">K-means clustering</a> is a method through which a set of data points can be partitioned into several disjoint subsets where the points in each subset are deemed to be ‘close’ to each other (according to some metric). A common metric, at least when the points can be geometrically represented, is your bog standard euclidean distance function. The ‘k’ just refers to the number of subsets desired in the final output. It turns out that this approach is exactly what we need to divide our image into a set of colours.</p><h4>Our case</h4><p>In our case, the ‘data points’ are colours, and the distance function is some measure of ‘how different’ two colours are. Our task is to group these colours into a given number of sets, and then calculate the mean colour of each set. Using the mean seems like a fairly sensible choice because you can imagine blurring your eyes whilst looking at the different colour clusters, and seeing a mean colour for each. However, we could instead use any other statistical measure (mode, median, or anything else!) and possibly get a better result.</p><p>Let’s write this in <strong>JavaScript!</strong> ✨</p><h4>The data points</h4><p>Each data point is a colour and can be represented as a point in an <a href="https://en.wikipedia.org/wiki/RGB_color_space">RGB colour space</a>.</p><p>In JavaScript, a single data point could look something like this:</p><pre><em>// An array if we want to be general<br></em>let colour = [100,168,92];</pre><pre><em>// Or an object if we want to be more explicit<br></em>let colour = {red: 100, green: 168, blue: 92};</pre><h4>The distance function</h4><p>Since we want to be able to calculate how similar two colours are, we need a function. This is another point where we have many choices, but a straightforward one is just to calculate the euclidean distance using the component values of each colour.</p><p>Our distance function could look like this:</p><pre><em>// Distance function<br></em>function euclideanDistance(a, b) {<br>    let sum = 0;<br>    for (let i = 0; i &lt; a.length; i++) {<br>        sum += Math.pow(b[i] — a[i], 2);<br>    }<br>    return Math.sqrt(sum);<br>}</pre><p>Since we haven’t specified a fixed number of components in our function, it will work for <em>n-dimensional</em> data points (with n components). This is useful in case we want to represent colour in a different way later on.</p><h4>The algorithm</h4><p>The most common algorithm used for k-means clustering is called <em>Lloyd’s algorithm</em> (although it is often known simply as <em>the</em> k-means algorithm). We’re going to use that algorithm here.</p><p>We’re going to create a set of objects called ‘centroids’, each of which defines a single, unique cluster.</p><p>A centroid has two things associated with it:</p><ul><li>a point within the range of the data set (the centroid’s position)</li><li>a set of data points from the data set (the points in the centroid’s cluster)</li></ul><p>There are three main steps to the algorithm:</p><p>1. <strong>Initialisation</strong>. Choose initial values for the centroids. In this case, we’ll just choose a random point for each one.</p><p>2. <strong>Assignment</strong>. Assign each data point to the cluster whose mean (the centroid) is the least distance away.</p><p>3. <strong>Update</strong>. Set the new mean of each centroid to be the mean of all of data points associated with it (in the centroid’s cluster).</p><p>The algorithm will perform <strong>initialisation</strong> once, and then perform <strong>assignment</strong> and <strong>update</strong> in order, repeatedly, until the algorithm converges.</p><p>The algorithm is said to have ‘converged’ when nothing changes between assignments. Basically, when the points make their mind up about which cluster they’re a part of, we can stop looping.</p><h4>Helper functions</h4><p>Let’s get some helper functions defined: one for calculating the range of a given dataset, and one for generating a random integer within a given range. The ‘range’ of an n-dimensional data set is just a set of ranges — one for each dimension.</p><pre><em>// Calculate range of a one-dimensional data set</em></pre><pre>function rangeOf(data) {<br>    return {min: Math.min(data), max: Math.max(data)};<br>}</pre><pre><em>// Calculate range of an n-dimensional data set<br></em>function rangesOf(data) {<br>    let ranges = [];</pre><pre>    for (let i = 0; i &lt; data[0].length; i++) {<br>        ranges.push(rangeOf(data.map(x =&gt; x[i])));<br>    }</pre><pre>    return ranges;<br>}</pre><pre><em>// Generate random integer in a given closed interval<br></em>function randomIntBetween(a, b) {<br>    return Math.floor(Math.random() * (b - a + 1)) + a;<br>}</pre><p>Assuming we’ve got those two, we can now write the code for the three steps of the algorithm.</p><h4>Step One — Initialisation</h4><p>For the number of centroids desired (k), we generate a random integer-valued point in the range of the data set provided and append it to an array. Each point in the array represents the position of a centroid. The centroids, of course, have the same number of dimensions as the data.</p><pre>function initialiseCentroidsRandomly(data, k) {<br>    let ranges = rangesOf(data);<br>    let centroids = [];<br>    for (let i = 0; i &lt; k; i++) {<br>        let centroid = [];<br>        for (let r in ranges) {<br>            centroid.push(<br>            randomIntBetween(ranges[r].min, ranges[r].max));<br>        }</pre><pre>        centroids.push(centroid);<br>    }</pre><pre>    return centroids;<br>}</pre><h4>Step Two — Assignment</h4><p>This is where we assign data points to clusters. For each point, we choose the centroid that is the minimum distance away and we append the point to the associated cluster.</p><p>I’m using the Array’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> function along with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a> here, so have a quick look at those if you’re not quite sure what’s going on.</p><pre>function clusterDataPoints(data, centroids) {<br>    let clusters = [];</pre><pre>    centroids.forEach(function() {<br>        clusters.push([]);<br>    });</pre><pre>    data.forEach(function(point) {</pre><pre>    let nearestCentroid = Math.min(<br>    centroids.map(x =&gt; euclideanDistance(point, x)));</pre><pre>    clusters[centroids.indexOf(nearestCentroid)].push(point);<br>    });</pre><pre>    return clusters;<br>}</pre><h4>Step Three — Update</h4><p>For each cluster, we calculate the mean of its enclosing data points and set it as the associated centroid’s position. We then return the new set of centroids.</p><p>There’s actually another function being used here called <em>meanPoint</em>. I won’t go into to detail because it’s fairly obvious to implement yourself. It returns a point whose components are the means of the corresponding component values in each of the passed points.</p><pre>function getNewCentroids(clusters) {<br>    let centroids = [];</pre><pre>    clusters.forEach(function(cluster) {<br>        centroids.push(meanPoint(cluster));<br>    });</pre><pre>return centroids;<br>}</pre><h4>Oh, one more thing!</h4><p>There is one issue with this algorithm, and it’s that sometimes the clusters become empty. There isn’t much of a consensus on what to do when this happens, but some possible approaches are to:</p><ul><li>Remove the cluster (a bit silly)</li><li>Assign a random data point to the cluster</li><li>Assign the closest data point to the cluster</li><li>Restart the algorithm and hope it doesn’t happen again</li></ul><p>Although the last option seems like a bit of a bodge, the algorithm (with the random initialisation) is non-deterministic and so simply restarting does work quite well. After all, this method is pretty much a heuristic and heuristics by definition are ‘a bit of a bodge’ … at least compared to a solid <em>algorithm</em>.</p><h4>Pulling it all together</h4><p>Now that we’ve got the basic functionality defined, all that’s left is to write some code to call each function when required as defined by the algorithm.</p><p>I’ll leave that to you as an exercise, but, if you really want to, you can see my implementation of it as a web app <a href="https://github.com/xanderlewis/colour-palettes">here</a>. 🌈</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22yc7P_ZZUjgxlff3oTU9g.png" /><figcaption>Here’s what it looks like after being fed the cover of a <a href="http://ryanhemsworth.com/">Ryan Hemsworth</a> song.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9616348712be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/extracting-colours-from-an-image-using-k-means-clustering-9616348712be">Extracting colours from an image using k-means clustering</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>
    </channel>
</rss>