<?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 Nataniel Ruiz on Medium]]></title>
        <description><![CDATA[Stories by Nataniel Ruiz on Medium]]></description>
        <link>https://medium.com/@nataniel.ruiz777?source=rss-a967b2741c51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*EYIxV_p5F0SWxoA7XXBbDw.jpeg</url>
            <title>Stories by Nataniel Ruiz on Medium</title>
            <link>https://medium.com/@nataniel.ruiz777?source=rss-a967b2741c51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:15:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nataniel.ruiz777/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 to Simulate]]></title>
            <link>https://medium.com/data-science/learning-to-simulate-c53d8b393a56?source=rss-a967b2741c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53d8b393a56</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nataniel Ruiz]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 11:30:48 GMT</pubDate>
            <atom:updated>2019-10-14T17:49:26.145Z</atom:updated>
            <content:encoded><![CDATA[<h4>How learning to simulate better synthetic data can improve deep learning</h4><p><em>The paper presented at </em><strong><em>ICLR 2019 </em></strong><em>can be found </em><a href="https://arxiv.org/abs/1810.02513"><em>here</em></a><em>. I also have </em><a href="https://docs.google.com/presentation/d/1AEqPi-bJ1q-o1bxosBjcqEgCb2Vs2TcJF6cI4nHZKTg/edit?usp=sharing"><em>slides</em></a><em> as well as a </em><a href="https://natanielruiz.github.io/docs/lts_poster.pdf"><em>poster</em></a><em> explaining the work in detail.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-prN8g1R_GBT_xNS3Dx7A.png" /><figcaption>Photo by <a href="https://unsplash.com/@davidclode?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">David Clode</a> on <a href="https://unsplash.com/s/photos/brain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Deep neural networks are an amazing piece of technology. With enough labelled data they can learn to produce very accurate classifiers for high dimensional inputs such as images and sound. In recent years the machine learning community has been able to successfully tackle problems such as classifying objects, detecting objects in images and segmenting images.</p><p>The caveat in the above statement is <strong>with enough labelled data.</strong> Simulations of real phenomena and of the real world can sometimes help. There are cases where synthetic data has improved performance in deep learning systems in <a href="https://www.di.ens.fr/willow/research/surreal/data/">computer vision</a> or <a href="https://openai.com/blog/generalizing-from-simulation/">robotic control applications</a>.</p><p>Simulation can give us accurate scenes with free labels. But let’s take Grand Theft Auto V (GTA) for example. <a href="https://arxiv.org/abs/1608.02192">Researchers have leveraged a dataset</a> collected by free-roaming the GTA V world and have been using this dataset to bootstrap deep learning systems among other things. Many game designers and map creators have worked on creating the intricate world of GTA V. They painstakingly designed it, street by street, and then fine-combed the streets adding pedestrians, cars, objects, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAIv3OP-qjuZMbFB" /><figcaption>An example image from GTA V (Grand Theft Auto V)</figcaption></figure><p>This is expensive. Both in time and in money. Using <strong>random simulated scenes</strong> we might not do much better. This means important edge cases might be severely undersampled and our classifier might not learn how to detect them correctly. Let us imagine we are trying to train a classifier which detects <strong>dangerous scenes</strong>. In the real world we will run into dangerous scenes like the one below with very low frequency, yet they are very important. If we generate a large number of random scenes, we will have very few dangerous scenes like the one below as well. A dataset which undersamples these important cases might yield a classifier which fails on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psa2V3i6YJkBKf3t8HSsVw.png" /><figcaption>Example of a dangerous traffic scene. These important cases can be undersampled when randomly sampling synthetic data. Can we do better?</figcaption></figure><p><strong>Learning to simulate </strong>is the idea that we can potentially learn how to optimally generate scenes such that a deep network can either learn a very good representation or can perform well in a downstream task.</p><p>To test our work, we create a <em>parameterized procedural traffic scene simulator</em> using Unreal Engine 4 and the <a href="http://carla.org/">Carla plugin</a>. Our simulator creates a road of variable length with different types of intersections (X, T, or L). We can populate the road with buildings on the side and cars of 5 different types on the road. The amount of buildings and cars are controlled by tunable parameters, as well as the type of cars. We can also change the weather between 4 different weather types, which control for lighting and rain effects. The main idea will be to learn the optimal parameters which control these scene characteristics for different tasks (for example semantic segmentation, or object detection).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuWWU6LXHgeY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuWWU6LXHgeY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuWWU6LXHgeY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bb8d45706f79acc5be5e646aa14ac43/href">https://medium.com/media/8bb8d45706f79acc5be5e646aa14ac43/href</a></iframe><p>To get sensor data we place a car on the road of our generated scenes which can capture RGB images from the generated scene which automatically have semantic segmentation labels and depth annotations (for free!).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-W_ioqZZydY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-W_ioqZZydY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-W_ioqZZydY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8fc67c9c72479517d8273ec913089be/href">https://medium.com/media/a8fc67c9c72479517d8273ec913089be/href</a></iframe><p>However, the learning to simulate algorithm is more general than this. We don’t have to use it exclusively for traffic scenes, it can apply to <em>any type of parameterized simulator</em>. By this we mean that, for any simulator that takes in parameters as an input, we present a way to search for the best parameters such that the data generated is optimal for a deep network to learn the downstream task. Our work, to the best of our knowledge, is the first to do <strong>simulation optimization to maximize performance on a main task</strong>, as well as <strong>apply it to traffic scenes</strong>.</p><p><strong>Moving on to the crux of our algorithm</strong>. A traditional machine learning setup is the following, where data is sampled from a distribution P(x,y) (x is the data and y is the label). Usually this happens by collecting data in the real world and manually labeling the samples. This dataset is fixed, and we use it to train our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*A80YybeM_cdzZUaAH5gfHw.png" /><figcaption>Traditional machine learning setup</figcaption></figure><p>By using a simulator to train a main task network, we can generate data from a new distribution Q defined by the simulator. This dataset is not fixed and we can generate as much data as our computation and time constraints allow. Still, the data generated in this domain randomization setup is <strong>randomly sampled from Q</strong>. The data needed for obtaining a good model could be large and performance can be suboptimal. <strong>Can we do better?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*3m9r8zCOMBzpU674c12pqg.png" /></figure><p>We introduce learning to simulate which optimizes a metric of our choice on a main task — the pipeline is trained by defining a reward function R which is directly related to this metric (usually is identical to the metric itself). We sample data from a parameterized simulator Q(x,y|Θ), with which we train the main task model at every iteration of the algorithm. The reward R that we defined is then used to inform the update of the Policy which controls the parameter Θ. The reward R is obtained by testing the trained network on a validation set. In our case, we use vanilla policy gradient to optimize our policy.</p><p>Informally, we are trying to find the best parameter Θ which gives us the distribution Q(x,y|Θ) which maximizes accuracy (or whichever metric) for the main task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhiCkg3Dt2E5QyUVJE0RzQ.png" /><figcaption>Learning to simulate setup</figcaption></figure><p>The mathematical formulation of the learning to simulate problem is a bi-level optimization problem. Attempting to solve it with a gradient-based approach poses smoothness and differentiability constraints on the lower-level problem. In this case the simulator should also be differentiable, which is generally not true! This is why a derivative-free optimization approach like vanilla policy gradients makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dhf-AgO8QRxA0uWm" /><figcaption>Mathematical formulation of the bi-level learning to simulate optimization problem</figcaption></figure><p>We demonstrate our approach on <strong>instance counting </strong>and <strong>semantic segmentation</strong>.</p><p>The car-counting task that we explore is simple. We ask the network to count how many individual cars of each specific type are in the scene. Below is an example scene with the correct labels on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_2CMjcCtYZUj0IGmpjABQ.png" /><figcaption>Car counting task example</figcaption></figure><p>We use <strong>learning to simulate</strong> to solve this problem and compare to what happens using only <strong>random simulation</strong>. In the graph below, focus on the <strong>red and grey </strong>curves, which show how learning to simulate (LTS) achieves a much higher reward (lower mean absolute error of cars counted) after 250 epochs. The random sampling case briefly improves, but performance decreases once the sampled random batch is not adequate for the task. The grey curve rises slowly over several iterations but learning to simulate <strong>converges on the best possible accuracy shown by the blue curve</strong> (where we use the ground-truth simulation parameters).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lq2iQrXBaCpXHtA5" /><figcaption>Reward for the car counting task. Note how learning to simulate converges to the best possible reward (on a simulated dataset) shown by the blue curve.</figcaption></figure><p>What is happening? A nice way to look at it is by visualizing the probabilities of different scenarios and objects in our scene. We plot the weather probabilities over time. The ground-truth validation dataset that we generated oversampled certain weathers (clear noon and clear sunset) and undersampled the rest. This means there were more images with clear noon and clear sunset weather than other types of weather. We can see that our algorithm recovers the rough proportions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NXRBncCiGsA8aeFG" /><figcaption>Weather probabilities (logits) over time</figcaption></figure><p>Let’s do the same with car spawning probabilities. Our ground-truth dataset oversampled certain types of cars (silver Nissan and Green Beatle). Learning to simulate reflects these proportions after training as well. In essence, the algorithm pushes the simulator parameters to generate datasets which are similar to the ground-truth dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T0L_CIRMUa82JOd9" /><figcaption>Car probabilities (logits) over time</figcaption></figure><p>Now we show an example of how learning to simulate improves accuracy over random simulation on the <a href="http://www.cvlibs.net/publications/Geiger2013IJRR.pdf">KITTI traffic segmentation dataset</a> which is a dataset <strong>captured in the real world.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dQo3h-zIV8Mj9hTU8DZYA.png" /><figcaption>An example image from the KITTI dataset.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjG1dFTft5yft_-qBqCz_w.png" /><figcaption>An example of ground-truth semantic segmentation labels on our simulator. In a simulator, you can get object labels for free — no need for a human annotator</figcaption></figure><p>As our baseline we train the main task model separately 600 times, with data generated by the simulator using different sets of random parameters for each one. We monitor the validation Car IoU metric for each of these networks and pick the one with highest validation reward. We then test it on the <em>unseen KITTI test set</em>. We train learning to simulate for 600 iterations and obtain a Car IoU (widespread segmentation metric) of <strong>0.579, </strong>much higher than the <strong>0.480 </strong>achieved using the random parameter baseline (random params). We also show our results using another derivative-free optimization technique (random search) which did not achieve good results in this experiment (although it did work pretty well in car counting). Finally, we also show the actual performance of the ResNet-50 network we used for segmentation by training on 982 annotated real KITTI training images (KITTI train set), to show an upper bound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u_OatkvN8Vib80Dm" /><figcaption>Results for semantic segmenation on the unseen KITTI test set for car semantic segmentation</figcaption></figure><p>Learning to simulate can be seen as a meta-learning algorithm that adjusts parameters of a simulator to generate synthetic data such that a machine learning model trained on this data achieves high accuracies on validation and test sets, respectively. We show that it beats domain randomization in real problems and believe it is a very promising research area. It will be exciting to see what can happen with extensions and applications of this in the near-future and I encourage everyone to look into how simulation and learning to simulate can help you in your applications or research.</p><p>All questions are more than welcome! My website is below.</p><p><a href="https://natanielruiz.github.io/">Nataniel Ruiz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53d8b393a56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learning-to-simulate-c53d8b393a56">Learning to Simulate</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[Envy is a Form of Inspiration]]></title>
            <link>https://medium.com/@nataniel.ruiz777/envy-is-a-form-of-inspiration-a89af21ca8f7?source=rss-a967b2741c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/a89af21ca8f7</guid>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[achievement]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[motivation]]></category>
            <dc:creator><![CDATA[Nataniel Ruiz]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 16:25:05 GMT</pubDate>
            <atom:updated>2019-07-10T05:38:29.505Z</atom:updated>
            <content:encoded><![CDATA[<p>But it’s a badly harnessed form of inspiration. How to transmute it into positive actionable inspiration?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOiA_B2GBzvWz4QYWkpFAg.jpeg" /></figure><p>Why are you not running for President? Why did George W. Bush run for President and win? It is because his father was President of the United States. With this, I am not making a political statement or a value judgement on President Bush. I just want to explore the fact that remarkably talented people can become Presidents, Supreme Court justices, CEOs of large companies or just as well lead completely normal and unremarkable lives.</p><p>Lately, I have been trying to understand why some of my peers achieve more than others. More generally, I have been looking at all of my most cherished influences and trying to understand what do they have in common with one another and how they differ from the thousands of other remarkable people that have not achieved what they did. I found that <strong>many of them have successful friends or family.</strong> Now you can question the causation all you want: maybe successful family provides you with opportunities, maybe you become friends with successful people after you become successful yourself. Sure, both of those are probably true! But I believe that there is also an underlying factor that propels them to achieve more than their peers. Inspiration.</p><p>What is inspiration? It’s a pretty expansive word. I found a good practical description through observing my own response to it. It is a certain type of flow of energy in your body which catalyses your mind to start imagining possible futures where you can produce something comparable to what you are observing. For example, ever since I started composing and recording my own songs, <a href="https://www.youtube.com/watch?v=cd0KOtgc88M">Louis Cole</a> has been an incredible inspiration to me. Every time I watch one of his videos or hear one of his new releases I have a strong impulse to go write or record. The big question is why? What about <strong>his </strong>work creates this feeling in me?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96iG_z3kO4Rh1mLjZl7dnQ.png" /><figcaption>Seriously, <a href="https://www.youtube.com/watch?v=cd0KOtgc88M">check this guy</a> out he’s great.</figcaption></figure><p>I want to know if you, the audience, have had that same feeling and I want you to try to remember when it was that you realized that you wanted to do what another person was doing. The times you got inspired. Now I want you to go a little deeper: what were the times you got inspired which changed your life? The times where a simple moment of inspiration made you switch jobs or apply to grad school? I am not talking about abstract inspiration I want to talk about <strong>actionable inspiration</strong>. The times it actually made you move in an unexpected direction.</p><p>I think there is some kind of structure to this process. At least for me. Did you get inspired by someone you knew? Someone similar to you? Someone you related to? I think it is easier if these boxes are checked.</p><p>I think what keeps a lot of people from running for President, to take the extreme case, is not their ability but their imagination. Can they imagine themselves in that position? More to the point, do they know anyone who they think is an <strong>equal</strong> to them, that is in a comparable position. This goes back to the George W. Bush example. Being the President of the United States never seemed out of reach since his father had already achieved it.</p><p>Again, <strong>actionable inspiration</strong> is a very powerful force to achieve what you want. Actionable inspiration happens when you observe the great work or accomplishment of someone you think of as similar to you — someone who seems to be your equal in some imagined way: in skills, upbringing, identity, etc. This means that we can fabricate this actionable inspiration for ourselves. One good way to do this is to rub elbows with successful people. Very soon you will realize that most of them are not superhuman, you are probably as smart as them and they are as flawed as you. If you internalize this, then their work and life accomplishments will seem within reach. Go to your alumni reunions! I never did this but I regret it now.</p><p>And, finally, we get to the title of this piece. Envy is a form of inspiration too. It is, to be clear, a badly harnessed and expressed form of inspiration but it is inspiration nonetheless. The regular person feels envy not for Lionel Messi when he wins the Ballon d’Or, or for Leonardo DiCaprio when he gets his Academy Award. They feel envy when their classmate, who’s presumably as smart as they are, gets the award they wanted. They feel envy for the people they see as <strong>equals</strong>. Now, <strong><em>envy is not good</em></strong>. It is a destructive and uncomfortable feeling. Especially when it takes hold in response to a friend’s success. In my opinion it is probably one of the worst feelings. I propose to convert envy to a positive form of inspiration.</p><p>Envy can not only be transformed into beneficial actionable inspiration, but it can even be transformed simultaneously into <strong>pride</strong> for the person who is achieving. This is especially beautiful if this person is your friend, or family. The idea is to take that bare feeling of anxious envious energy in your body and realize that the feeling is exactly the same as intense inspiration. It is making <strong>you</strong> want to do what <strong>they </strong>are doing. If you truly believe that they are your equal then <strong>you can also learn how to do it</strong>. At that point, envy is superfluous, there can only be happiness that this person has inspired you and if they are your friend then it is not a large step to go from this to feeling proud of having them as a friend.</p><p>Going back to Louis Cole. Why does his music produce that effect? He’s very obviously much better than I am at most of the instruments he plays, at composing, harmony, production, video production — basically everything. I know this is true. Yet, his indie production (which is an artistic choice), his apartment recorded videos, his distorted and saturated sounds, make my brain believe that I could do something similar and it has made me very happy to work on my songs using this inspiration. This transmutation of potential envy to inspiration is something I see in many professional musicians. Somehow they learn how to do this better than any of us — you can also have this superpower.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a89af21ca8f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Medoids Clustering Using ATS: Unleashing the Power of Templates]]></title>
            <link>https://medium.com/data-science/k-medoids-clustering-using-ats-unleashing-the-power-of-templates-56cd7ab944bf?source=rss-a967b2741c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/56cd7ab944bf</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[at]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nataniel Ruiz]]></dc:creator>
            <pubDate>Sat, 04 May 2019 00:40:33 GMT</pubDate>
            <atom:updated>2019-06-13T22:40:39.741Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/natanielruiz/ats-kmedoids">natanielruiz/ats-kmedoids</a></p><p>(you can find all of the associated code above)</p><p>k-medoids clustering is a classical clustering machine learning algorithm. It is a sort of generalization of the k-means algorithm. The only difference is that cluster centers can only be one of the elements of the dataset, this yields an algorithm which can use <strong>any type of distance function</strong> whereas k-means only provably converges using the L2-norm.</p><p>While taking the <em>CS520 Programming Languages </em>course at <em>Boston University</em>, and working with the ATS programming language’s creator Prof. Hongwei Xi, I realized that ATS can be a natural fit for working with this type of algorithm. Indeed, the <strong>templates </strong>allow for an extremely general implementation of k-medoids. After having implemented the template functions, the only thing left to implement to run it on your dataset is the <strong>distance function</strong>. This means that written in this way, the algorithm can work on any dataset the user wishes, given that the user can implement a well defined distance function between points in the dataset.</p><p>Let us show how this works, step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*AxLX7iiuDbolAqYgoq5ILQ.png" /><figcaption>Import all necessary libraries — the mylib function which defines the mylist type is included in the GitHub repo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*pwf4xe0mztrzKoh3jLdKug.png" /><figcaption>The outline of the k-medoids algorithm</figcaption></figure><p>After having parsed and understood the k-medoids algorithm we can see that we will have to implement several template functions. But first let us define some handy data types. Note that these datatypes have an inner datatype <strong>“a” </strong>which will be defined at the moment of implementing the distance function. This means that our code is completely general — allowing for dataset points of any finite length and any type (e.g. integers, doubles, floats, characters).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*2Lyb449ug6YKvigjicW53A.png" /><figcaption>point(a) is a list of type a and pointlst(a) is a dataset of points of type</figcaption></figure><p>Next we define the BIG GUYS. The templates for our k-medoid algorithm. KMedoidsTrain takes in the the dataset p and the number of clusters, does it’s magic and outputs the <strong>medoids, clusters </strong>and<strong> cost </strong>of the final configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JW34wM7iCpw_YAO9mje-yw.png" /><figcaption>We define templates for the k-medoids training function and the k-medoids loop function</figcaption></figure><p>We define some templates to</p><ul><li>initialize the medoids</li><li>associate points in the dataset to the closest medoid</li><li>find medoid for a specific point</li><li>lookup the coordinates for the medoids given the list of the medoid indices</li><li>swap medoid <em>i</em> for point<em> j</em> in the dataset</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*XSe2sF-ZW1TujqLsKFfs0Q.png" /></figure><p>Also some templates to compute the cost and distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*9XP06iDzuvr78L2DAYCZPw.png" /></figure><p>At this point we can ask: which of these functions can be defined completely generally and apply to any clustering problem we want to solve?</p><p>Actually, please <strong>stop scrolling </strong>and let’s play a game. Please answer this question: which functions will we have to define whenever we want to change the distance metric definition? (answer is below)</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>The answer is only the <strong>distance </strong>function. Maybe you thought the cost function would need to be implemented separately for each problem too, but this is not the case. The cost function should basically compute the distance between all the points and their medoids and add these distances up — it depends on the distance function and can be coded independently.</p><p>All of this is great news. One set of function implementations work for ANY problem you would like to tackle. You just need to define a distance function for your dataset.</p><p>Actually let’s look at how this works. Let’s implement the costf function which, given the dataset of points p, the medoids and the clusters gives us the sum of all the distances between the points and their medoids.</p><p>As usual in ATS we use recursion to compute this result, and an auxiliary function costf_aux which uses an accumulator res to compute the result. Remember in this scenario we have medoids which is the list which contains ndices of the medoids (which points in the dataset are medoids) and medoid_pts which we obtain using the lookup_medoids function is a list which contains the coordinates of the medoids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*XL94eHfT-PM7k1OZZPvpCA.png" /></figure><p>In the auxiliary cost function we iterate through the dataset <strong>p </strong>using pattern matching (case+ p of). When the dataset has been iterated through, we output the accumulator res. While we’re still iterating through the dataset we obtain the cluster to which the point p1 belongs to, we get the medoid coordinates m corresponding to that cluster and then simply compute the distance, using the still unspecified distance function.</p><p>Let’s take a quick look at lookup_medoids below. It is just a helper function which takes in the dataset and the medoid indices and gives us the medoid coordinates. You don’t want to be passing around medoid coordinates all over the place when it is not necessary!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*LocFQZDVfC4QxqFHHV5spw.png" /></figure><p>Let’s go back to the algorithm.</p><p>KMedoidsTrain takes in the dataset <em>p </em>and the<em> number of clusters</em>, and using the auxiliary function KMedoidsTrainIter gives us the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*o9pJ7uRUbuAwuASzPB-fvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1/1*6xT3AqKaqlSqPWcP_c-_EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*BYGw_t9PBrCX_xvJ85FBQQ.png" /></figure><p>The code is pretty self-explanatory. But in case you need some help parsing it out the steps are as follows:</p><p>If the clustering is not done:</p><ul><li>Swap medoid j for point i</li><li>Get new clusters for all points</li><li>Get the indices (i, j, step) for the next iteration (I use the helper function below to make the code a little neater)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*ojcYxgY7Hb_qtoZ-DCZmuA.png" /></figure><ul><li>If the new cost is lower than the old cost then use the new medoids! If not keep going with the old ones.</li></ul><p>Pretty simple!</p><p>How to initialize the medoids? Just grab the ‘n_cluster’ first elements of the dataset using a helper function. It would be better to grab random elements but this is still a valid way of initializing the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*TbOO9oDLHhEPpJkUnio97w.png" /><figcaption>for loops are for beginners</figcaption></figure><p>Okay, finally, how do we associate each point in the dataset to it’s corresponding medoid? First we define a function to find the corresponding medoid for one specific point p1. Then we use it to look for all corresponding medoids in the associate_points function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*ma9rUz-sU5yLw6qb-xRJBA.png" /><figcaption>Simple recursion with pattern matching where, at each step, we compare the distance to the old medoid to the distance to the new medoid. If the distance is lesser then the new medoid is carried on!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*a2k8_iKYx2-W5sc-Nb4czA.png" /><figcaption>Here we are basically finding the medoids for all points in the dataset. A simple recurrence.</figcaption></figure><p>One more thing. How do we swap medoid i for point j? Using a function from mylib which you can look up on GitHub :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*5pz2rxGZsqgxn5-SGbt3jQ.png" /></figure><p><strong>We are getting to the fun part!</strong></p><p>Let’s define a new file l2_medoids.dats and call the last file clustering.dats</p><p>Import the previous file containing the template function definitions. Also import the C library to call the square root function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*80fQ8PeotstE5eUI7B5Q5w.png" /><figcaption>ATS can call external C functions to do math</figcaption></figure><p>We have a dataset that looks like this. We want to do clustering using the <strong>k-medoids algorithm</strong> and the <strong>L2 distance function</strong> (with<strong> 2 clusters</strong>). Can you see what the result will be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*E3EqoH-z0Ov0dOm8FAYaHg.png" /></figure><p>Okay, the fun part. Define a distance function between two points. Remember, up to this moment points were lists of unspecified length and of unspecified type a. Extremely general! Now we actually tell the compiler that we are working with points of type <strong>double. We also tell the compiler how to compute the distance for our dataset.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*WKiVdS6Lk_pBZKRX9yyKSw.png" /><figcaption>Recurrence through the point coordinates. d = sqrt((p1 — p2) ** 2)</figcaption></figure><p>It is time to define our k-medoids function for the L2 distance, in the same file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*BfIl81IbRid1vnMeDz-zIQ.png" /></figure><p>And a small example which corresponds to the 2D example drawn above! Let’s see if we got it right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*ENf0YBTuRjmVMF2FJcJCXw.png" /></figure><p>Compile all of this using the ATS compiler ‘patscc’. Whew no errors! ATS is a strongly-typed language and many potential bugs are flushed out at compilation time. While debugging, the compiler caught most of my implementation errors since some functions were not being fed the correct types. Mostly, runtime errors will be out-of-bounds errors, although using advanced ATS programming such as theorem proving even these can be caught at compile time.</p><p>All of these characteristics make ATS an interesting programming language.</p><p><strong>Anyway, let’s run the code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*9Q6mX_z0cAVtPJgSRij_XA.png" /></figure><p>We have our list of associated medoids, the final medoids and also the cost function of the final configuration. Let us draw the final state and see if we got it right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*mrrI09ONlULcqoICVed-Rg.png" /><figcaption>Two clusters in red and blue. The highlighted points are the cluster medoids.</figcaption></figure><p>Perfect! If you want to use this code on your dataset feel free to do so. Remember, you only have to implement the distance function and you’re all set.</p><p>It’s as easy as that. As a goodbye note let’s define the L1 distance which can be used on the same problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*izb_f7XcG5nz4aqMKEPfuA.png" /><figcaption>L1 distance function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*te2v3xsClZ2kp2U2jOhS1Q.png" /><figcaption>Different results. Makes sense!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*WIP7R2fvp_TDE7r3Gvnbfg.png" /><figcaption>Same clusters, different medoids!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56cd7ab944bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/k-medoids-clustering-using-ats-unleashing-the-power-of-templates-56cd7ab944bf">K-Medoids Clustering Using ATS: Unleashing the Power of Templates</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>