<?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 Hussain Safwan on Medium]]></title>
        <description><![CDATA[Stories by Hussain Safwan on Medium]]></description>
        <link>https://medium.com/@safwan-du16?source=rss-ccfbeb4e8d4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*20vyPUfR8a3xBMBSK7lDVQ.jpeg</url>
            <title>Stories by Hussain Safwan on Medium</title>
            <link>https://medium.com/@safwan-du16?source=rss-ccfbeb4e8d4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:30:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@safwan-du16/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[Self Attention]]></title>
            <link>https://safwan-du16.medium.com/self-attention-163153f5bb6c?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/163153f5bb6c</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 12:23:33 GMT</pubDate>
            <atom:updated>2021-07-19T12:23:33.115Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explained with Q, K, V notions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r64w1rtQRK0ySxDB" /><figcaption>Photo by <a href="https://unsplash.com/@chiklad?utm_source=medium&amp;utm_medium=referral">Ochir-Erdene Oyunmedeg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let&#39;s kick off with a little scenario. <strong><em>The earth is like an orange</em></strong>, <strong><em>Orange is a bright color</em></strong>. Now, put a little focus on the words orange in either sentence. It should be pretty obvious that the very same word is conveying meanings that are wildly different from each other. In the first sentence, it denotes orange, the fruit while the second one is telling about orange, the color. But how are we able to tell these apart? After all, they are essentially the same words. That’s where context comes into play.</p><h3>What is attention?</h3><p>Context plays a major role in our natural conversations. Same words or phrases may assume multiple meanings depending on the context they’re being used. Context is the set of other words around a word that provide the circumstances for the event described to occur. To grasp the complete and intended meaning of a word, or better a token as referred to in NLP, we need to look at the other words that surround it.</p><blockquote>Attention is the cognitive mechanism focusing on one or a bunch of tokens that are believed to be of more significance to assist express the intended meaning for the token in question.</blockquote><p>Like for the example cited above, <strong><em>The earth is like an orange — </em></strong>to determine whether orange here refers to the color or the fruit, we speculate the word earth and would very much want our algorithm to do so.</p><p>In the context of NLP, attention is the process of attaching a bit of context to each of the tokens under procession. Though used in several forms time series, the use of attention mechanism has been greatly popularized by the 2016 paper on the Transformer model, by Google, entitled <strong><em>Attention is all you need</em></strong>. The transformer model uses the mechanism on a couple of varied settiings, but what we’de be looking at is <strong><em>Self attention</em></strong>.</p><h3>Self Attention</h3><blockquote><strong>Technically speaking, self attention is the relative degree of attendance each token should ensure to the fellow tokens of the sentence.</strong></blockquote><p>It can be thought of as a table that enlists each token both on row and column and <em>(i, j) th</em> cell accounts for the relative degree of attendance ith row should ensure to the jth column. Now the question is how?</p><p>Let’s take the previous,<strong><em> Earth is like an orange,</em></strong> sentence as a working example.</p><ol><li>We tokenize the sequence and translate each token into a word embedding. Let sequence now be denoted as,</li></ol><blockquote>V = [ V1, V2, … Vn]; Vi denoting word vector for ith word</blockquote><p>2. Okay, all set to make the first operation. We take each word embedding and assign others with a relative priority with respect to how similar they are. Now how exactly do we measure the similrity between words. Thats why we need the embeddings. This idea of measuring similarity very much deserves it’s own article, but anyway it’d put it in as little words yet as elaborate as possible.</p><p>You see, word embeddings are vectors usually of elements in the rage <em>-1</em> to <em>1 </em>(negetive meaning “is not”) and of a fixed length depending on which implementation you’re up against. The rows denote a feature. For example, the embedding for the word earth may have a large value for the slot of <em>round </em>(like <em>0.95 </em>or something, since it’s almost a sphere) and large negetive value for features like <em>rectangle </em>or <em>toxic environment</em>(since earth is neither <em>rectangular</em>, nor <em>toxic </em>to life). On the otherhand orange might also have a large positive number for the feature of <em>round</em>, since it’s roundish too. Now see what happens when we dot-product the embeddings. Since they have large values on similar slots and possibly zero or negligible (either positive or negetive) numbes on others, the dot product generates a rather large result. On the contrary, had they been not similar, they would have had larger values on dissimilar slots that would minimize each other on the event of a dot product and produce a tiny value. So that’s pretty how dot products are used to find similairties between word embeddings.</p><p>Say wo begin with the token earth. We dot-product the vector for earth with each of the vector in the sequence, yes with itself too, and recieve a pure number, a score denoting how similar/related they are.</p><p>4. Once the similarity scores are retrieved they’re <strong>normalized </strong>to push then within the range. Now they can formally be termed <strong>weights</strong>.</p><p>5. In this step the <strong>weights </strong>scalar multiplied with each of the vector embeddings within the sequence, this produces a vector, specific to the word we began with, in this case the word earth. Each entry in the resultant vector tells us how related the word earth is to that particular word. We repeat the same procedure for every token in the sequence and essentially get a matrix (like the table mentioned above).</p><p>Here’s a pictorial view of the schematic,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*NVRyEYe3WivX4iETJjn-xg.jpeg" /></figure><p>This depicts the iteration for the word orange.</p><p>All good so far. But there’s a catch in all of these. We’re passing on a word and finding the weighted matrix for relative attendance, that’s fine. But where’s the learning in all these? Being an ML model, it should strive to learn something every passing iteration, right? Let’s deal with that with a database analogy. We input the algorithm with a word and ask it for the relative attention and the algorithm returns that. It’s like the algorithm acts as a database that when queried with a word (orange in the diagram) and provided with a set of keys (original sequence in the diagram) maps it against a value (also the original sequence, but one shown above) and returns the results. That’s where the notion of Query, Keys and Values drop in.</p><p>Again we’ve to perform the same operation for each word, so why not put up a matrix representation of the Queries, Keys and Values. Hence we multiply each of the component with appropriate Q, K and V matrices. Note that this also solves the problem of learning.</p><p>How? Well during the backpropagation the back flowing signals update the matrix entries in a way that minimizes the overall errors. The new schematic is shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMSa5eAm4AcpT1G6d4TKJw.jpeg" /><figcaption>X, like in X K denotes being dot product’ed with matrix K</figcaption></figure><p>Now lets put the entire iterative flow within a package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eudwZGMMTjwZ4a_ZV1eNJw.jpeg" /></figure><p>The X vector on the left denotes the input word embeddings. Note that X1, X2 are vectors. This matrix is passed to Value, Query and Key layers via matrix multiplication. The outputs of Query and Key, generated via multiplication, is passed through the normalization layer. The normalized outputs, termed as weights, are then mapped to the value parameters to generate the final attention scores. One more thing to note here is the color convention used. The arrows in green denote a forward pass, red denotes backward pass — where the parameters are update that is learning occurs and those that do not identify with either are in blue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163153f5bb6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Trees. Implementaion.]]></title>
            <link>https://safwan-du16.medium.com/decision-trees-implementaion-e3c4d24f0c70?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c4d24f0c70</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 05:14:29 GMT</pubDate>
            <atom:updated>2021-06-12T06:12:32.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decision Trees. Implemented</h3><h4>Simple, module wise implementation of Decision Trees using Gini index</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vjVYdlYScEt3l-13" /><figcaption>Photo by <a href="https://unsplash.com/@theheartdept?utm_source=medium&amp;utm_medium=referral">Tanalee Youngblood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve talked quite a bit about decision trees. This is the article that we actually implement one. For the very basics, decision trees are a class of supervised learning algorithms in ML that relies on repeatedly splitting the dataset with respect to the <strong><em>“most plausible feature”</em></strong> to construct a graphical structure that has decisions at the level of roots. Since this is implementation-focused writing, there won’t be much of theoretical discussions.</p><h3>Inner mechanisms</h3><p>For this article, I’ll refer to the target column of the dataset as Y and the rest as X. At the very core of the system, we’ve got a third level nested loop that one each iteration performs the following,</p><ol><li>The innermost loops through each pair of data points within each column of X to determine the best split point.</li><li>The middle one loops through each column of X to find one with the best split point, dubbed as the best attribute. At this level, we’re gonna make the split. With the split made, we’ve got two new datasets, shrunk in size and a little bit more homogenous. We apply the same rules to the new datasets alike until we either stumble upon a case where there are no more features to split on — an absolutely pure state of the dataset, or each label of Y is the same.</li><li>This brings us to the outermost loop that iterates through each of the child datasets to execute the inner loops.</li></ol><h3>Codification</h3><p>Let&#39;s kick off with the imports,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30950f221b7b7a7f7a193502e6f63e43/href">https://medium.com/media/30950f221b7b7a7f7a193502e6f63e43/href</a></iframe><p>Next, we’re gonna create a Node class. You start with the root node, with each split you end up with two more nodes, that store the information such as best split point, attribute, gini and so on about the split until you reach the terminal nodes (also called the leaves) that store decision.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a040c620d5d9a6246d5a88d91d9917c/href">https://medium.com/media/3a040c620d5d9a6246d5a88d91d9917c/href</a></iframe><p>Let’s move on to the DecisionTree class. The constructor takes in a dataset (X and Y fused) and an optional parameter <strong><em>rows</em></strong> to specify what portion of the dataset is intended for the training phase. The class also features a built-in label-encoding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0062fd2901db99211090b2471806fc3/href">https://medium.com/media/f0062fd2901db99211090b2471806fc3/href</a></iframe><p>The model calls the fit function on the encoded dataset. The fit function in turn calls for a recursive function <strong><em>recur_fit()</em></strong>. Now, this is the function where the splits and stuff occur. So every time it’s invoked, it creates a Node variable, gets the best split attribute and splits the dataset into two, and stores each as left and right, respectively, of the fresh node variable. Note that the contents of each of the snippets from here on are within the scope of the DecisionTree class and are pasted separately only due to better elucidation purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec28db2c5b1cd638c97c91b19eb934ad/href">https://medium.com/media/ec28db2c5b1cd638c97c91b19eb934ad/href</a></iframe><p><strong><em>find_best_attribute()</em></strong> is a function that takes in a table (a subset of the entire dataset) and spits out the attribute w.r.t the split is to be made, where within the column the split is to be made and the gain should the split be made. <strong><em>find_best_split()</em></strong> attribute is employed for the best point to split.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88d0da999af76ef7b7baab2df8afa489/href">https://medium.com/media/88d0da999af76ef7b7baab2df8afa489/href</a></iframe><p>Here are some auxiliary methods needed for the training phase,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b966a992e0677781d61e5375678b5d14/href">https://medium.com/media/b966a992e0677781d61e5375678b5d14/href</a></iframe><p>Next, talking about the prediction module, the system takes in a row, label-encodes it and passes it down the tree to reach the corresponding leaf and returns the associated decision.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3da1eecd1be616ada89351e57d7a371a/href">https://medium.com/media/3da1eecd1be616ada89351e57d7a371a/href</a></iframe><p>For testing, with say the iris.csv dataset, run the following snippet,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94d523ad3eea6636cea3157bf6e70bc7/href">https://medium.com/media/94d523ad3eea6636cea3157bf6e70bc7/href</a></iframe><p>Visit <a href="https://colab.research.google.com/drive/1pFwKcmgP-VU5YtBsyPsJdPAGvMHz47Ag?usp=sharing">this link</a> for the entire code base on my Colab.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c4d24f0c70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mary’s Room]]></title>
            <link>https://medium.com/curious/marys-room-e943bd00b2b7?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e943bd00b2b7</guid>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 07:03:57 GMT</pubDate>
            <atom:updated>2020-12-17T12:27:53.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>The door to Epiphenomenalism</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xdQEXo3ErvzkAb1z" /><figcaption>Photo by <a href="https://unsplash.com/@justusmenke?utm_source=medium&amp;utm_medium=referral">Justus Menke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Think of a brilliant scientist called Mary made to live in a dark room unable to connect to the external world except via a screen through which she monitors the world and unfortunately the screen is only capable of displaying grayscale images. Mary, a neurophysiologist by profession, excels in the field of human vision, visual perception, and the science of colors. One fine sunny morning, she is released into the wide world that so far existed beyond her physical knowledge. Now the question that arises is whether Mary will learn anything new after being released into the wilderness.</p><p>This is a famous thought experiment, devised by philosopher Frank Jackson and published in his article Epiphenomenal Qualia in 1982. The author intends to argue against the philosophy of Physicalism that states that whatever exists in nature along with all its mental aspects are purely physical and can accurately be simulated via physical means. In his article, Jackson places the fictional character Mary in the shoes of an observer who gains all the knowledge there is to gain about a physical phenomenon but does experience the phenomenon itself and asks if it does make a difference. According to the author himself, yes it does make a difference. Mary will learn something new once she steps out of the room and experiences color vision for the first time, even though she attained all the knowledge about color and it’s perception while being inside the room.</p><h3>Qualias</h3><p>The term qualia stems from the Latin word of qualias that in a literary sense means ‘of what kind’, which signifies an idea of being a part of a class.</p><blockquote>Qualias are defined as an individual instance of experience, perceivable purely through the appropriate senses.</blockquote><p>To illustrate the idea of qualia, scientist Feigl draws the example of an alien with perceptive abilities different from humans and unsurprisingly can not feel pain. Now, with so many resources available on pain and it’s the process of perception, the alien can easily learn about the pain, that it feels bad to humans, and even pass a biology test on the topic, without ever being able to be inflicted by pain. If that is the case, then the pain is a qualia, feeble to humans, in this case.</p><p>Try explaining what color is to a blind person. One common pattern in qualias is the only reliable explanation of qualia involves a reference to that qualia itself, a vicious cycle. For example, you may explain the color pink to a person who never saw the color as a lighter shade of red or the sound of gunfire to one who never heard one as being similar to that of a cracker only much louder. Notice that each of these explanations assumes the observer to have observed a different version of the qualia beforehand. You might try associating the red color with fire and hotness, blue with peace and cool, and so on. But these won’t make much of a sense to a person who never witnessed a color.</p><p>It seems there is something inherently different about studying a color or any other qualias like taste or hearing and actually perceiving them through the appropriate senses. More on this later.</p><h3>Back to Mary</h3><p>Though Frank Jackson, the author of hte article, concludes that Mary will definitely learn something upon expsoure to the color-world and that qualias exist, a number of alternate explanations exist.</p><p>Paul Churchland argues that all Mary learned while being in that hypothetical room are the brain states and their functionalities and nothing actually about colors. So it is natural for her to learn something new when exposed to the color vision.</p><p>VC Ramchandan and Edward Hubbard propose a total of three mutually exclusive paths the events might follow when she is released.</p><ol><li>She continues to experience the world in black and white, a situation indicating her retina hasn’t evolved to that stage of receiving color data or that the optic lobe hasn’t developed on processing that.</li><li>She does actually experience color for the first time.</li><li>She experiences blindsight where colors can not explicitly be differentiated but can be perceived via a vague inner sense.</li></ol><p>Whichever the case, this proposition does seem to go in favor of Frank Jackson and indicates a new thing is learned.</p><h3>The Senses</h3><blockquote>We experience the world as far as out senses allow us to</blockquote><p>The doctrine of naturalism states that the natural exists with or without conscious observers. We observe the world through our senses. The senses offer an abstraction of reality and not the reality itself. Sometimes this process of abstraction involves creating the entirely new perception that resides purely within the brains of the observer and is totally irrelevant to the actual physical world. For example, the color that we see is an interpretation of the wavelength of the incident light, the sound that we hear is the frequency at which the air column next to the eardrum vibrates. These are all irrelevant outside the head of the observer, unlike gravity or the earth, which exist irrespective of any conscious observer.</p><p>Human senses however have limitations, like we perceive a minute portion of the entire electromagnetic spectrum, which we call the visible spectrum, can hear a small range of frequencies from 20 Hz to 20 kHz. There are animals and living beings that can perceive Xrays, hear beyond 20 kHz, sense geo-waves, rotation of the earth, and so on.</p><p>In conclusion, it is worthy to note the fact that everyone is helplessly alone inside the head. No one can perceive the world in exactly same manner as you do. I claim the strawberry in the cover of the article to be red and you might to agree on ‘calling’ it red even though you see it as what might seem green to me and call it ‘red’ only because you learned that is what red means — and we might go home happily never knowing how different our visions are. I don’t have any means of verifying that my red is the same as yours. Do I?</p><p>Well, that could give you a profound feeling of uniqueness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e943bd00b2b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/curious/marys-room-e943bd00b2b7">Mary’s Room</a> was originally published in <a href="https://medium.com/curious">Curious</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Activation Functions?]]></title>
            <link>https://medium.com/curious/what-are-activation-functions-d40a5f552c77?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d40a5f552c77</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 10:19:22 GMT</pubDate>
            <atom:updated>2020-12-17T12:28:11.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>The data itself is redundant, all that is needed to know is if it was greater than a threshold.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MmvtsIJJb7034Ovm" /><figcaption>Photo by <a href="https://unsplash.com/@timothymeinberg?utm_source=medium&amp;utm_medium=referral">Timothy Meinberg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Activation functions are the driving forces of artificial neural networks, as they sit on top of any neuron and administer its behavior such as if it should fire upon a certain input, if it does, to what degree, and so on. Technically speaking, the activation function of a certain node takes as input the data from its predecessors in the network and spits out a certain value that in turn indicates to its successor nodes how “turned on” it was in response to the particular input signal. In this article, we discuss the anatomy of a neural network that makes activation functions a part and parcel of itself, its biological analogue, and a superficial view of a couple of famously used activation functions.</p><h3>Structure of a neural network</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81OriEJxA2yA2B5XxW8SzA.png" /></figure><p>Being a data science enthusiast, it’s hardly possible for you to have never encountered the above image or a similar one. A classic depiction of the workflow of a two-layered neural network.Say, the network classifies images for a cat or a dog, has two hidden layers, each containing a line of 16 neurons.Let’s focus to the level of a single neuron, the first one of the second layer,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt4cWK9vb0Co8fvC1SCB-g.png" /></figure><p>A closer shot might look quite like this. Note that the neuron is fed as input the signals from each of 16 predecessors. The neuron calculates the resultant by multiplying the connection weight to the signal and adding a bias term to the product, which is designated as <strong><em>v</em>. </strong>This term, <strong><em>v</em></strong>, might be thought of as the perception of the input image for this particular neuron. After perceiving the input signal, the neuron is expected to generate an appropriate reaction, which is where the activation function makes its way in. The activation function, designated as <strong><em>f()</em>, </strong>acts as a mapping from perception to reaction, that produces as value <strong><em>a</em></strong>, that is passed on to the next layer neurons as a signature of how a specific neuron from the the previous layer reacted to the signal.</p><h3>Biological analogue</h3><p>Think of placing your palm over a gradually heating steel pot. As soon as the temperature surpasses a threshold, you feel the urge to take your hands off the surface. Note the fact that you never needed to know the exact temperature of the surfacer to pull your hands out, rather a binary result based on the actual parameter. This is called the firing of a neuron, when it does, a command is passed on to the periphery (hands in this case). This is where activation functions stem from or are at least analogous to. The actual data here is redundant, all that a neuron needs to know is if it was greater than a threshold.</p><p>One significant difference between a biological neuron and its artificial counterpart is that the former, as we understand today, may either be activated or not activated, a binary value, whereas the latter operates in a range depicting the degree of activation.</p><h3>Different types of activation functions</h3><p>There are all the different kinds of activation functions. Let&#39;s explore a few of them, on the surface, in the order of the problems they address.</p><p><strong>Problem 1: Learning</strong></p><p>In the earlier days of neural networks, when learning itself was the goal, linear functions did pretty well. They’re called linear functions because, the approximation <strong><em>v = wa + b</em></strong> quite closely resembles the <strong><em>y = mx + c</em></strong>, which is the equation of a straight line.</p><p><strong>Problem 2: Nonlinearity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5CbuHhz6VDui8aQYw4qxg.png" /></figure><p>While linear functions approximate the right-hand dataset quite well, the perform miserably for the one at the left. Since non-linearly distributed datasets dominate the realm of machine learning, and activation functions are the only suitable spot to inject nonlinearity into the network, there is no scope for the function to be linear. Some of the renowned functions to address this problem are,</p><p><strong>Sigmoid function: </strong>This is a function that takes in a number and outputs a number in the range of (0, 1). The smaller the input, closer is the output to zero, greater it is, closer it approaches to 1, without ever touching either of the extremities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*d0nTuKFld0xrVdILts_aLg.png" /></figure><p><strong>tanh function: </strong>Also known as the hyperbolic tangent function is pretty similar to the sigmoid except the output ranges from -1 to 1, without ever touching the either.</p><p>The one at right is the plot for sigmoid and the other for tanh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*GjSQAdUaMIBo9lYXcgdpnw.jpeg" /></figure><p><strong>Problem 3: Vanishing Gradient</strong></p><p>Notice the graphs once again, for the sigmoid, the curve almost flattens while approaching either extremities. That is for inputs of very large absolute values, the output doesn’t reflect a significant change. This drastically retards the learning rate. This is known as the vanishing gradient problem, where the gradient (ie. learning) diminishes as the process progresses.</p><p>This limitation is addressed by the ReLU activation function, the de facto default activation for modern neural networks.</p><p><strong>ReLU function</strong>: Standing short for Rectified Linear Unit, this is probably the most interesting and counter-intuitive function of all. It is an almost linear function with a single knee at the origin. It is defined as a piece-wise function,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*AU_sFbzQXVYAAi6uPUkGUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkZ5OYHJvCnYPigMJ2SIyg.png" /></figure><p>The question often asked is how can a near-linear function save the day. From the graph, it&#39;s obvious that it can almost completely avoid the gradient decent problem. Single ReLUs are flat and boring, but an army of them can be unbeatable. Have a look at how it approaches the Annulus Ring problem,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*dn7N3AkC3F7FqyMnfzuYTQ.jpeg" /></figure><p>Linear utterly fails to approximate, tanh attempts and draws a smooth circle-like curve and finally, ReLU — comes in with a hexagon. You might think of this like this —having two pieces of straight line joined at one end, like the hands of the clock. Now imagine having a million of such lines. You can replicate almost any nonlinear shape with that arrangement. The beauty of ReLU is that it is near-linear and a bunch of them can be molded to almost any shape by twisting the knee angle to perfection.</p><p>That brings us to the last problem to be addressed.</p><p><strong>Problem 4: Probabilistic Sum</strong></p><p>Whatever is done within the hidden layers, the ultimate goal at the end of the day is to generate some sort of prediction and the style here is to output a likelihood vector containing the list of probability of the input object being one of the labeled ones. For example, the result of the neural network in the first picture may like,</p><blockquote>[dog, cow, cat, goat, lamb] = [0. 2, 0.05, 0.7, 0.03, 0.01]</blockquote><p>The result will most likely be cat since it’s got the highest score of 0.7.</p><p>To convert the final output of a fully connected layer into a normalized vector of probability, a function is required that takes in a vector and spits out a vector too, only that the sum of each element of the output vector be equal to 1. After all, that’s what makes it a probability vector.</p><p>Sigmoid function closely resembles a probability function since its outputs range from 0 to 1, however, fails to satisfy the condition of the sum being equal to one.</p><p>The special function that achieves this feature is the Softmax function.</p><p><strong>Softmax function: </strong>This function takes in a vector and for each element calculates the corresponding entry in the output vector using the following function,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*j3KGB-jmMtb88Bs-frH-aQ.png" /></figure><p>The denominator being the sum of all possible numerators prevents the outputs to exceed the value of 1.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d40a5f552c77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/curious/what-are-activation-functions-d40a5f552c77">What Are Activation Functions?</a> was originally published in <a href="https://medium.com/curious">Curious</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of ConvNets]]></title>
            <link>https://medium.com/swlh/fundamentals-of-convnets-4c386df9ff33?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c386df9ff33</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Sat, 05 Dec 2020 07:34:59 GMT</pubDate>
            <atom:updated>2020-12-06T12:38:57.828Z</atom:updated>
            <content:encoded><![CDATA[<h4>“Computer vision is the science of programming a computer to gain a high-level understanding of digital imagery.”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e9tOW4eTV7XJ0NT0" /><figcaption>Photo by <a href="https://unsplash.com/@senjuti?utm_source=medium&amp;utm_medium=referral">Senjuti Kundu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ConvNets are at the heart of image recognition and computer vision. One of the most fascinating things about this is how a sequence of raw mathematical operations like multiplication and addition goes all the way to process and recognize complex visuals. In this episode, we talk about a few fundamental concepts of computer vision, define and illustrate the working procedure of ConvNets and jot down some technical terms associated with that. First, let&#39;s talk of the idea since they are bulletproof(!)</p><h3>The idea</h3><p>The idea is simple, detect what’s inside an image, playback video, or a live recording (since all videos are at the most rudimentary level a sequence of fast-changing images). Technically speaking, computer vision is the science of programming a computer to gain a high-level understanding of digital imagery by replicating the working strategy of the human visual system. We use a variation of artificial neural networks called Convoluted Neural Network to achieve this. From here on, I’ll be referring to the technology as CNN. The core task of a CNN is to detect the valuable features in an image so that the image can itself be represented mathematically in the form of a vector of numerical figures which can, in turn, be compared against that of a labelled image to confirm to which class the subject belongs or what&#39;s in it depending on the initial requirements.</p><p>Now, CNN may have numerous layers, each of a different type — which I’ll not be discussing in this episode. The layer we’ll be focusing here today is the convolution layer.</p><h3>The Convolution Layer</h3><p>The convolution layer as the name suggests performs the convolution operation. To begin with, let point out the fact that digital images arrays of numbers (typically ranging between 0 to 256) denoting the colour combination of each pixel. For instance, an1 KB grayscale square image is in binary an array of size 1024 x 1024. Please note that coloured images use a third dimension called the colour channel and that for simplicity, we’ll be dealing with grayscale images in this lecture.</p><p>The primary job of a convolution layer is to detect significant features in an image. We begin with edge detection. An edge (no, not the WWE one!) in an image is a line, straight or curved, both sides which have a sharp change colour contrast. To detect one, a filter window is slid over the original image that attempts to look for an edge within its scope. Here’s how the convolution is done,</p><ul><li>Take an image of dimensions <em>nh x nw</em></li><li>A filter of <em>fh x fw</em></li><li>Slide the filter over the image, one step at a time, and on each step, perform an element-wise multiplication of each element of the image with that of the filter, within the scope of the window and finally add the products and store the sum in a 2d resultant array, we’ll talk about the dimensions of the resultant array in a short while.</li></ul><p>Here’s a pictorial view,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwdE05sFWDAB_YGzwBL18A.png" /></figure><p>The shaded image on the bottom is the subject, there are two edges marked with a red ellipse, the 2d array on the upper left is the numerical form of the image. The conventions used is that lower the value of an individual pixel (an index in the 2d array), lighter is the shade in the image. Finally, the 2d array on the upper right is the filter. Note that in this example, we use an image of dimensions 5 x 5 and a filter of 3 x 3.</p><p>Let’s capture the convolution in action,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFaKcC2DPtsqVysNA8K5kw.png" /></figure><p>For the first value in the resultant matrix,</p><blockquote>resultant[0][0] = 10x1 + 10x0 + 0x(-1) + 10x1 + 10x0 + 0x(-1) + 10x1 + 10x0 + 0x(-1) = 30</blockquote><p>As a matter of fact, each <em>fh x fw</em> (3 x 3, in this case) subset of the original matrix (the image) goes into a single cell of the resultant matrix. The resultant has a dimension of 3 x 3, which is just one dimension greater than the difference of dimensions of the image and the filter.</p><blockquote>Hence, output dimension = input dimension — filter dimensino+1</blockquote><p>Take a closer look at the resultant matrix, there is a column of higher values (60) sandwiched between two columns of lower values(30), that is there are two changes in contrast, that corresponds to the two edges in the original image. You might be tempted to say that that’s no edge, that’s a whole shaded region, but lemme remind that we’re dealing with a 5 x 5 image, whereas real images are of much higher resolution.</p><h3>The Accessories</h3><p>There are a few factors to consider while convolving,</p><p><strong>Padding: </strong>Note that the size of the image shrinks upon convolution, from 5 to 3, meaning we’re missing out potential features at level of convolution and finally may end up with a single-dimensional image at the end. Here’s where the concept of padding comes in. We might pad the image with a line of 0s at each step to preserve the dimension. This is called <strong>same padding , </strong>where the dimensions of resultant remain the same as original after convolution.</p><p>Stride: Stride is the skip of columns at each iteration of the convolution. A stride of 2 means filter is to be placed on every 2nd columns.</p><p>Here’s a visual representation of padding and stride,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_j0VUFVstWTOGPZJH0fCw.png" /></figure><p>The illustration depicts a padding of 2 (same padding for 5 x 5 image) and a stride of 2.</p><p>Incorporating padding and stride into the equation of output dimension,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Hg8jHwcY7XoE4GLAWJg1lg.png" /></figure><h3>The Algorithm</h3><p>Finally, as usual, let’s end the discussion with a pseudocode for the algorithm,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnsEa8MqmwxTXi_2j7VygA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c386df9ff33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/fundamentals-of-convnets-4c386df9ff33">Fundamentals of ConvNets</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adversarial Search and α-β pruning]]></title>
            <link>https://safwan-du16.medium.com/adversarial-search-and-%CE%B1-%CE%B2-pruning-e908f9cedd53?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e908f9cedd53</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 06:37:43 GMT</pubDate>
            <atom:updated>2020-10-28T06:37:43.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can you beat what you just created?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vI78aOld7DWQQx9Z" /><figcaption>Photo by <a href="https://unsplash.com/@imandrewpons?utm_source=medium&amp;utm_medium=referral">Andrew Pons</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Wonder why it is virtually impossible for an average person to beat a computer in strategic board games like chess, go, or tic tac toe? That’s because computers can literally see into the future (or <strong>futures</strong>, to be precise) of the game and decide the upcoming move accordingly. The class of algorithms exploited in this context is known as <strong>Adversarial Search</strong>. The core motive of such algorithms is to play defensively and resist the opponent from winning at any cost. So until you sit with a piece of paper and try to simulate the outcome up to a certain depth before finalizing any moves, odds are pretty high you lose.</p><h3>The Minimax Algorithm</h3><p>As stated earlier, AIs which employ the adversarial search, play in a defensive manner, with a prime target not to win, but to minimize the loss as much as the situation allows. This is known as loss aversion. Note that in case such decisive games mentioned above, the entire game can be represented by a decision tree, where each initial decision leads to a specific, unique leaf.</p><p>In the Minimax algorithm, the terminal nodes (called leaves) are each assigned a value (more on this value assignment later). Two players, called Mini(traditionally the AI player) and Max(the human opponent), are playing. Initial move is always made by Max. The incitement of each player is to maximize the utility upon their turn and to minimize on the turn of the opponent. Here’s a typical game tree,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVDNjTEfT1yPr0OJaP-pVg.jpeg" /></figure><p>Notice that the first move is made by Max and the game continues with alternating players. The algorithm as written in plain English is,</p><ol><li>Find all the possible moves from the current stage of the game</li><li>For each possible moves, recur down the hierarchy until a leaf is found</li><li>If the current node is a leaf, do the following,</li></ol><p>3a. If the player is Max, return the maximum of scores of the current leaf node and its siblings</p><p>3b. Else, return the minimum</p><p>4. After the recursion completes and algorithm returns to the site of initial call, decide based on the computed score and current player (whether Min or Max) which path to take.</p><p>The algorithm is a back-tracking one.</p><h3>How long does it take</h3><p>Say, the time it takes to expand a node happens to be a constant and is of the value <em>c </em>and we’ve got a tree with a branching factor of 3, i.e. each time any node is expanded, it expands into 3 more nodes (usually the branching factor decreases with depth, as in tic-tac-toe, as you’ll see later in this episode)<em>. </em>Observe, initially there is one node, the root, nodes at level 0 is 3⁰ (=1), it expands into 3 nodes as the branching factor is 3, so at level 1 there are 3¹ nodes, in the next level each of 3 node expands into 3 more nodes, so at level 2 there are 3x3 = 9 =3² nodes. Noticed the pattern? At level d, there are 3^d nodes. If branching factor is b then at level d, there are b^d nodes.</p><p>Now the total effort required to expand all the nodes is the sum of the nodes expanded at each level. Like at level 0, its <em>c.3⁰ = c, </em>at level 1 its <em>c.3¹ = 3c </em>and so on. The total effort for branching factor b and depth d is,</p><blockquote><em>total effort = c.b⁰ + c.b² + c.b³ + … + c.b^d</em></blockquote><p>Considering the largest term and omitting the constant part, the time complexity becomes O(b^d).</p><p>For games like chess, the average number of possible moves at any given instance is 35 and the average depth is about 100, which states that to simulate a chess game from any given point would require about 35¹⁰⁰ or 2.55x10¹⁵⁴ nodes be expanded, and that’s only the average, not the worst case possible!</p><h3>Can we do better?</h3><p>Minimax is a great leap forward for AIs competing with human counterparts but is way too naive for most of the strategic games. The fact that it expands each and every node up to the leaves makes it stumble on the ground. The AI can be taught to cut off some branches if they do not seem promising enough. This is called <strong>α-β </strong>pruning. This is not an algorithm by itself, rather like Minimax 2.0.</p><p>The fundamental idea is to maintain two variables called alpha and beta that keep track of how useful it is to expand the next node. Alpha is maximized while beta minimizes. The algorithmic pseudocode for a tic tac toe with <strong>α-β </strong>pruning is given in the next section.</p><p><strong>The algorithm</strong></p><p>The algorithm can almost readily be reproduced into a running python implementation with a few syntactic changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_-pdx_ozm4BFK1gpOKPTg.png" /></figure><p>A couple of functions need to be implemented to get the flavor of how the algorithm runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pySTdmFb35xtecJUpjM13g.png" /></figure><ul><li>+/- inf denote positive and negative infinities. winning() is a utility function that checks the board configuration to tell if a player is winning. findEmptySlots() runs through every cell to find an empty one. The logic here is to return -10 upon losing, +10 upon winning and 0 on a tie — from the perspective of Min (AI player) with the added compensation, hence subtracting the depth.</li></ul><h3>The Simulation</h3><p>Let’s actually employ the algorithm in an actual near end tic tac toe gam and see it in action. Consider the following stage of the game, O for AI, X for human.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*l9nx7oO71NxsKTQ4UVGYxA.jpeg" /></figure><p>Its got 3 empty slots. From here on, 11 new nodes can be expanded as follows, obviously there’s no single move at this stage that can lead to the victory of AI,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oumdtJbzs99zO-v2IEinpg.jpeg" /></figure><p>Here’s the convention,</p><ul><li>the tuple inside each is unique by at least one value</li><li>the first value denotes the number of the node as per order of traversal, like node (3, 1, 2) is the 3rd node to be visited</li><li>second value denotes the depth and thrid denotes number of empty slots at this stage</li><li>numbers on the edge also denote the depth, red numbers below each leaf denotes the final score, +/- (10-depth)</li><li>finally, the red circled nodes are the ones pruned</li></ul><p>Give it a go yourself, the algorithm should prune off 4 nodes.</p><p>About how much better is alpha-beta pruning as compared to Minimax, this depends mostly on the ordering of the nodes, if the left-most node contains the best path, the algorithm prunes the other branches, if not — the same time is required as Minimax if not worse, in order to handle the alpha and beta variables. The average complexity may be summed off to O(sqrt(b^d)).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e908f9cedd53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing the Density Based Clustering Algorithms]]></title>
            <link>https://medium.com/swlh/visualizing-the-density-based-clustering-algorithms-1ea63c36725?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ea63c36725</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 08:43:54 GMT</pubDate>
            <atom:updated>2020-10-20T13:48:08.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MlLUB6UQF_wseo3d" /><figcaption>Photo by <a href="https://unsplash.com/@erdaest?utm_source=medium&amp;utm_medium=referral">Erda Estremera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous episodes, we’ve discussed a few clustering strategies like centroid based and hierarchy based (<a href="https://medium.com/@safwan.du16">you can find them here</a>, if interested); in this episode, we talk of yet another family of clustering algorithms. Density based clustering algorithms are ones that proceed by finding the areas with a higher concentration of data points and merge those with similar concentration into a single cluster. Now, I know this might seem a little vague, like what’s concentration? How can it be similar? And so on. So without further adieu, let’s dive into the matter.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZZrAQ3MBVMOxJ6rIDC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZZrAQ3MBVMOxJ6rIDC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZZrAQ3MBVMOxJ6rIDC%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/47290ef16e7004cc985377fe817836f0/href">https://medium.com/media/47290ef16e7004cc985377fe817836f0/href</a></iframe><h3>The intuition</h3><p>One of the best ways to tackle a theoretical formulation is to ignite the flames of intuition. To get the train on the tracks, we need to grasp a few concepts like,</p><p><strong>Radius based neighborhood:</strong> Say you live in a locality and consider every house less than four doors away to be your neighbors. Now looking closely, you find your neighborhood forms a circle of three houses. Likewise for a data point in space, if a draw a circle with the point in the center and a radius of ɛ, it forms an ɛ-neighborhood. For 3d space, a sphere forms, and in higher dimensions, N-spheres form.</p><p><strong>Density: </strong>Back in the grad school days, we’ve density to be the measure of compactness, mathematically expressed as mass over volume. The notion hasn’t been altered that much. Say you got a point in 2d space and have drawn a circle of radius = 3 units. The volume would be (3.1415x3²)=28.27, (I know that’s the area, but this can also be seen as the projection of volume, like when you squash a 3d sphere to a heightless circle). The mass here would be the number of data points that fall within this volume, say for this point, a total of 35 points fall within the radius, the density would then be 35/28.27 or 1.24. The number 1.24 or the density all by itself is meaningless, but if we assign a density value to each point of the dataset, we can then arrange them in different clusters by the virtue of similar density measures.</p><p>While none of the algorithms work the exact same way as stated above, this should at least give a rough overview of the framework. <a href="https://blog.dominodatalab.com/topology-and-density-based-clustering/">Here’s a good read about that.</a></p><h3>Terms and Terminology</h3><p>In this tutorial, we mostly speak about a specific density based clustering algorithm known as DBSCAN (Density Based Spatial Clustering of Applications with Noise). Here are a few terminologies to help get along with the jargon.</p><p><strong>Categories of data points: </strong>There are three different kinds of points in the discussion. Core points are the ones that have at least a given number of data points within the given radius. Boundary points denote the points which do not have the required number of points at the given proximity but are within the circle of one (or more) core points. And finally, the points that do not meet any of the above criteria are labeled as noise, and can safely be ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zyl0F0TTW7v0HwQD4go4SA.jpeg" /></figure><p><strong>Minimum number of points: </strong>This is the minimum count of points the data point in question needs to qualify as a core point, this will be denoted as <strong>minPts</strong>. There are a few clues on how to determine this count though it depends exclusively on the given dataset. Note that a minPts=1 denotes that the results will essentially be that of hierarchical clustering. In fact any minPts&lt; 3 is not useful. It is recommended for the minPts to be at least minPts≤dim+1, where dim = dimensions of the input set. As a rule of thumb, the minPts may be taken to be the double of the dimension.</p><p><strong>The ɛ-radius: </strong>As stated earlier, to form the neighborhood, the expanse of the neighborhood is needed to be known. This will be denoted as ɛ. Like minPts, ɛ depends on the dataset. One effective way to determine ɛ is to plot the KNN graph. If you’re not familiar with that, then KNN(stands for k nearest neighbors) is the measure of the average distance from a given point to k(given as input) of it’s nearest neighbors and the plot is about (index, distance). Wherever the graph sees an elbow, can be taken as the measure of ɛ, if no elbow found, then trial and error might be the only way around. Note that ɛ and minPts are coupled, doubling the ɛ also requires the minPts to be raised by nearly 2^ɛ. More on how to choose the radius? <a href="https://datasciencebeginners.com/2018/11/18/dbscan-quick-tip-identifying-optimal-eps-value/">Visit here.</a></p><p><strong>Distance function:</strong> This is the function used to determine the spatial distance between two points. There are a couple of popular ones such as Euclidean or Manhattan and you’re at the full freedom of devising a custom function based on your dataset.</p><p><strong>Reachability:</strong> There roughly 3 classes of reachability.</p><p>Direct Density Reachable are the points of which one is a core point and the other is within the ɛ-radius.</p><p>Density Reachable are the points of which one being a core point and the other is reachable via intermediate points.</p><p>Density Connected are ones where none is core but are connected via intermediate points.</p><h3>The algorithm</h3><p>In words, we declare an empty set of clusters. We then loop through the set of data points if for every point which qualifies as a core, form a cluster of its own and for every other data points which are not included in any clusters, include in the current cluster. Finally, we merge the clusters which have their core points at most given radius distance away from the others.</p><p>Here’s the algorithmic pseudocode. The inputs are respectively the dataset(D), distance function (dist), radius (ɛ), and the minimum number of points (minPts). For a good implementation article, <a href="https://www.geeksforgeeks.org/dbscan-clustering-in-ml-density-based-clustering/">head over here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVgB1wXKaXvdU3tYvaHaFA.png" /></figure><p>The isCore( ) function, which inherits the necessary parameters from the parent function may be implemented as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rsb4ChfvMMAO-KjuUSQhOw.png" /></figure><h3><strong>Visualization</strong></h3><p>It’s way too tedious to perform even a single iteration of DBSCAN on bare hands. So instead of simulation, I’ve included this section to help visualize how the algorithm runs.</p><p>Observe the following points,</p><p>{ (4, 5), (11, 10), (14, 8), (4, 2), (5, 5), (4, 6), (10, 11), (12, 11), (11, 9), (15, 8), (14, 7), (15, 7) }</p><p>This is our data set. Here’s a plot of the points,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0BMQ2LcF4xcrrNKPPL3a1A.jpeg" /></figure><p>Now, consider the first three points, { (4, 5), (11, 10), (14, 8) } and note that I’ve marked them with C1, C2, and C3. These are the points we consider in this visualization. Say we take ɛ = 4 and minPts = 3. Let’s draw a 4 units radius circle around the points in consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__iXGdw_Z4JC2YvSOkOWHg.jpeg" /></figure><p>Observe with care, the C1 point forms a circle(purple) and traps two other points in it. C1 is obviously not a core point since it traps only 2 (&lt; 3) points. C2 and C3, on the other hand, each trap 3 points in the circle and thus qualify as core points. Again, using the Euclidean distance function, the distance between the core points can be determined, which is 3.61 (&lt;4) and thus they are neighbors, so the clusters formed by C2 and C3 can be merged into a single one. C1 wouldn’t even fall into the neighborhood of any core points and thus would be treated as noise. Points like (12, 11) might not be able to fit 3 points into the circle (hence not core) but lies in close proximity to C2 (core) and thus would be labeled boundary points. Here’ the circle of (12, 11),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeMBVTrDXSqoj47N-7yHOQ.jpeg" /></figure><p>About why and when DBSCAN is to be chosen, the main motive of the algorithm lies in its robustness, i.e. it can deal with outliers quite well. So it&#39;s a good choice for a relatively large dataset with a considerable amount of noise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea63c36725" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/visualizing-the-density-based-clustering-algorithms-1ea63c36725">Visualizing the Density Based Clustering Algorithms</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Hash-Based Message Authentication?]]></title>
            <link>https://medium.com/swlh/what-is-hash-based-message-authentication-685e4caa1083?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/685e4caa1083</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[message-authentication]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 05:01:57 GMT</pubDate>
            <atom:updated>2020-10-09T14:24:46.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ySaD0vkzyC5v3V_7" /><figcaption>Photo by <a href="https://unsplash.com/@sebasgoen?utm_source=medium&amp;utm_medium=referral">Sebastian Gómez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you’re reading this, but how confident are you that this is the same text from the author stated above and hasn’t been compromised to something else on the way (like I was writing on Data Science and the adversary altered it to a text on cryptography)? Well, networks are quite precarious in nature and such an incidence shouldn’t be surprising at all. In network communications, the integrity of the message to be delivered is just as important as secrecy and other privacy requirements are.</p><p>By integrity, we mean that a message (like this article is a message from me to my audience) should arrive at the receiver’s end just as it left the sender’s, i.e. without any alterations or at the least the fact that it has been altered should be confirmable. The central concept here is to tag the message with an authenticator so that the receiver has a clue of what the original message might have been. Now, there are quite a few algorithms to produce and attach the authenticator, the one we are particularly interested in this episode is the hMAC algorithm that stands for hash-based message authentication code. To go for hMAC, we need to understand the rudimentary one, the MAC algorithm. This should serve as a nice gateway into the realm of message authentication.</p><h3>Message Authentication Codes</h3><p>The MAC is a string of fixed size generated by an algorithm that takes the message and a secret key as input. The string, also known as the tag or the digest, is then concatenated to the message itself, and the compound is passed through the unsafe network. On the receiver’s end, the message is extracted and input into the same algorithm provided the receiver has access to the secret key, the same digest should be reproduced which is then compared to the incoming one — if matched the message is authentic else fraudulent. Some of the characteristics of MAC are,</p><ol><li>The same message with the same key produces the same MAC</li><li>MAC is a many-to-one mapping, denoting multiple messages may result in non-unique MACs</li><li>MACs are evenly distributed and ideally depend on every bit of the input.</li></ol><h3>Cipher MACs</h3><p>MACs are a way to secure the integrity of the message and obviously can’t provide the secrecy alone. So the use if MAC with an encryption scheme is the best way to provide privacy and authenticity of the communication at the same time. Below is a diagram to illustrate the procedure, press on the image to zoom in,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNs7ha_aSY5-qa-Ghk6Sug.jpeg" /></figure><p>The procedure is known as cipher tied MAC as the MAC is produced from the cipher. There is another procedure called plaintext tied MAC where the encryption is done after the message-MAC concatenation.</p><p>With that said, I guess we’re ready to take the big bite and discuss about hMACs.</p><h3>Hash-based MACs</h3><p>This class of MAC tags is produced via algorithms that have an underlying hash function. Any well-known hash function may be used for example SHA, MD, Whirlpool, etc. The mathematical definition of hMAC is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*-R6iHnEqtkdSmMRj2fYFUw.gif" /></figure><p>The algorithm takes in the secret key and the message (plain or encrypted) as input, pretty usual. The size of the key is to be adjusted to the block size of the underlying hash function, denoted by <em>H</em>. Like, for instance, the block size of <em>SHA-256</em> is <em>256B</em>. The adjustment is done by hashing the key down to the required size if exceeded. <em>K’</em> here is the length-adjusted key. The <em>opad</em> and <em>ipad</em> are the outer and inner padding constants. The values are strings of hex <em>0x36</em> and <em>0x5c</em> repeated to match the block size, i.e. for a block size of <em>4</em>, the value of <em>opad</em> is <em>0x360x360x360x36</em>. The algorithmic pseudocode would be like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*q0Y7p8aNHB623NSv2dLujA.png" /></figure><p>Since the hash function is anything like SHA or MD, it’s quite arduous to actually work an example out — sorry for that.</p><h3>Attacks and Robustness</h3><p>Brute force attack on the MAC algorithm can be carried out on two lines, one is to linearly search the keyspace, which for a k-length key should be <em>2^k</em>. The other is to search the entire tag space to generate a valid tag for the message <em>m</em>, the effort for which is <em>2^n</em>. So the overall effort is the minimum of the two, i.e. <em>min(2^k, 2^n)</em>.</p><p>Similar goes for hMAC. For an algorithm employing <em>n-bit</em> key, it takes <em>2^n</em> keyspace to be searched, which makes brute force infeasible even for a short lengthed key.</p><p>Before I end this episode, I’d like to share a brute-force scenario that I found at the crypto exchange site. Say we’re trynna break an hMAC-MD5 that employs a <em>128-bit</em> key, which raises the keyspace to <em>2¹²⁷</em>. Now to brute-force this algorithm we use the current fastest GPU, actually an amalgam of 25 internal GPUs, that breaks <em>400 billion (4 x 10¹¹)</em> <em>keys per second</em>. Say due to a super boosted budget we manage 1 million of these servers which raises the computation power to a staggering <em>4 x 10¹⁷ keys/second</em>. Impressive, no?</p><p>Well, not exactly, even at this rate it would take <em>1.35 x 10¹³ years</em>! Fun fact: The sun turns into a red giant in about <em>5 x 10⁹ years</em>!</p><p>ENJOY THE FIREWORKS!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZGwxerWzsgXhm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZGwxerWzsgXhm%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZGwxerWzsgXhm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b634a331baedd4ce29e255ea93b1c2b/href">https://medium.com/media/6b634a331baedd4ce29e255ea93b1c2b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685e4caa1083" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/what-is-hash-based-message-authentication-685e4caa1083">What Is Hash-Based Message Authentication?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ElGamal Scheme. From Root to the Leaves]]></title>
            <link>https://medium.com/swlh/elgamal-scheme-from-root-to-the-leaves-39693ceaefa6?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/39693ceaefa6</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[public-key-cryptography]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 09:29:50 GMT</pubDate>
            <atom:updated>2020-09-30T10:07:52.621Z</atom:updated>
            <content:encoded><![CDATA[<h3>The ElGamal Cryptosystem. From Root to the Leaves</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*65movtR1FlnOt3-h" /><figcaption>Photo by <a href="https://unsplash.com/@zhenhu2424?utm_source=medium&amp;utm_medium=referral">Zhen Hu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over the years, we’ve all grown up and so have Alice and Bob. Now they need more sophisticated and reliable cryptographic standards. That’s where the idea of public key encryption pops in. Public key encryption, in the generic sense, is a scheme that employs one globally shareable public key and an individual private key from each side. The message can be decrypted via a proper combination of the keys on each side. A classic instance of such a scheme is the ElGamal cryptosystem, which we <strong>dissect</strong> in this episode.</p><p>Okay, to study the ElGamal algorithm, we need to have a reasonable grasp over a few (notorious, that’s how I would describe) concepts of number theory. Now most of these elementary notions are well scattered around the internet and it’s a pain going to and fro, following every other reference, so I’ve done my best to put them under a single title. Note that it’s root level tutorial, so even if you’re not familiar with any of the following, you should still be good to go. What we’ll cover in this episode are primitive roots, discrete logarithm, cyclic fields, the robustness of ElGamal, the algorithm, and finally a small work-out. And as you’ve guessed gonna be a long journey, just bear with me.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F11sXlQpn53UuyY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F11sXlQpn53UuyY%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F11sXlQpn53UuyY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="272" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4f26b72b444710acd9dbcc0a37dd05c/href">https://medium.com/media/d4f26b72b444710acd9dbcc0a37dd05c/href</a></iframe><h3>Elementary number theory</h3><p><strong>Primitive roots: </strong><em>x </em>is a primitive root of <em>n</em> if, for every <em>y</em> relatively prime to <em>n</em>, there is a <em>z</em> such that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*c47FmuCEWkA_RSYt-XfP8A.png" /></figure><p>For example, <em>2</em> is a primitive root of <em>5</em> while <em>4</em> isn’t. Because there are numbers <em>z</em> to which <em>2</em> can be mod-exponentiated to produce all the number s relatively prime to <em>5</em> (like <em>2⁰ = 1, 1 mod 5 = 1; 2¹ = 2, 2 mod 5 = 2</em> and so on) but in case of <em>4</em> there isn’t enough such exponents to produce all the relatively primes of <em>5</em> (<em>4⁰ = 1, 1mod5 = 1; 4¹ = 4, 4mod5 = 4; 4² = 16, 16mod5 = 1,</em> see the cycle? <em>2, 3</em> can never be produced). Head on to this for more details.</p><p><strong>Discrete Logarithm: </strong>I’ll begin with an example since a formal definition could a bit frightening. Think of a group like <em>Z(23)</em> (z subscript 23, not familiar with groups? Think of it as the set <em>{1, 2, 3 …, 23}</em>). What would be the value of <em>3⁴</em> in this arithmetic? <em>3⁴ mod 23 = 81 mod 23 = 12</em>, simple enough. The problem of discrete log is the very inverse of this problem, where you’re asked to find <em>k</em> given,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*LdMtCvX87G_vNOnN_wBZcA.png" /></figure><p>From the above context, <em>4</em> is an obvious solution, however not the only. <em>26, 48</em> and to be precise any number of the form<em> 4+22n (n = 0, 1, 2, …) </em>satisfies the equation. So informally discrete log is the inverse of modular exponentiation and the term discrete is to denote the one of interest out of infinitely many solutions. For more reading, please navigate to these two links. <a href="https://www.sciencedirect.com/topics/computer-science/discrete-logarithms">Here</a> and <a href="https://en.wikipedia.org/wiki/Discrete_logarithm">here too</a></p><p><strong>Cyclic Groups: </strong>These are the groups where each member may be procured applying the same operation on the generator or its inverse. For example, <em>G</em> is a group closed under multiplication and <em>x</em> is a member of <em>G</em>. Now the smallest subgroup <em>g of G</em>, that contains the member <em>x</em>, is a cyclic group. How? Consider what can g be like to guarantee the existence of x within itself. It must contain <em>x</em>(trivial), its inverse <em>1/x</em> (since closed under multiplication), identity 1(same reason) and all derived from <em>x</em> and <em>1/x</em> such as <em>x², x³, … and 1/x², 1/x³,…</em></p><blockquote>g = { …, 1/x³, 1/x², 1/x, 1, x, x², x³, … }</blockquote><p>Note that each member is procured applying the same operation (multiplication) to either x(generator) or 1/x(inverse of the generator). <a href="https://en.wikipedia.org/wiki/Cyclic_group">Head over here for more.</a></p><p>Okay, how to put all these together? The knowledge gained from above (if any, at all) can be handy in understanding the intuition behind the scheme and how it is resistant to attacks.</p><h3>The algorithm</h3><p>Back to our old Alice and Bob. Bob initiates the process. He chooses a prime <em>m</em> and generates a field <em>F(m)</em>. Then he picks the numbers a and g where a should be,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*0r-7GtuILMVN2qLsVymmsQ.gif" /></figure><p><em>a</em> is the private and he computes the public key <em>h</em> as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*oRQZ3AxbiTPGS0QDrrdq2Q.png" /></figure><p>Now he sends the tuple <em>&lt;F(m), h, m, g&gt;</em> to Alice.</p><p>Alice generates her own private key <em>k</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*U82IFKPJc2-WJhA58yHSGA.png" /></figure><p>and the public key <em>p</em> as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*doN6oGesvIA4umv96mHSTQ.png" /></figure><p>and the <em>multiplier s</em> as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*nZLt-aDWl-dV9S91IZ7qCQ.png" /></figure><p>The final task for Alice is to encrypt the message M by multiplying with s and send the tuple <em>&lt;p, E&gt;</em> to Bob; <em>E = M . s</em>.</p><p>Bob on this side will simply multiply p with <em>g^a </em>to get <em>g^ka = s</em> and dividing the encrypted message <em>E(=Ms)</em> by s produces the plaintext M. Now I know this might seem a little hazy, solving a real-world problem is just what you need. To get a more organized form of the algorithm, <a href="https://www.geeksforgeeks.org/elgamal-encryption-algorithm/">take a sneak peek here</a>.</p><h3>Work-out problem</h3><p>To begin with, Bob needs a prime generator to build a cyclic field. Let that be <em>m=11</em> and the associated field be <em>F(11)</em>. As per algorithm, he selects <em>a=3(gcd(3, 11) = 1) and g=7</em>. Now he calculates the public key to be,</p><blockquote>h = 7³ mod 11 = 2</blockquote><p>and sends the tuple <em>&lt;F(11), 2, 11, 7&gt;</em>. Alice, on the other end, picks her private key <em>k = 5 (gcd(5, 11 = 1)</em> and generates the public key,</p><blockquote>p = 7⁵ mod 11 = 10</blockquote><p>and the multiplier,</p><blockquote>s = 2⁵ mod 11 = 10</blockquote><p>Now, say she happens to start the conversion saying “hello”. All she does is ASCII down the message as <em>[104, 101, 108, 108, 111]</em> and multiplies the factor s to each character and produces the array</p><p><em>E = [1040, 1010, 1080, 1080, 1110]</em> and sends the tuple <em>&lt;10, E&gt;</em></p><p>Note that none of the values can be represented by a character, as they’re way greater than 256, but that doesn’t matter as network cables carry only the binary information in form of electric signals.</p><p>Bob receives the token and quickly computes</p><blockquote>s=p^a mod 11=10³ mod 11=10.</blockquote><p>Note that he receives the exact same multiplier as Alice did (=10) and divides each number of E with that to extract the plaintext.</p><h3>Intuition and Robustness</h3><p>The algorithm is essentially all about finding discrete log k in a cyclic field generated by p. So every attack boils down to this phenomenon. Information of interest here to the attacker is the value of <em>g and g^a(=h)</em>. The problem is to solve <em>b = g^a (mod m) for a</em>. In brute force, the attacker loops through all possible values of <em>a (0 to m)</em> and checks if <em>g^a equals to b</em>. This is linear in <em>m</em>, ie. <em>O(m)</em>. <em>m</em> however contains <em>l=log(m)</em> bits so the actual complexity is <em>O(2^l)</em> plus the exponentiation time which is of exponential order. Hence, a tough job! So the size of the generator is taken to be large enough to resist the brute force attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39693ceaefa6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/elgamal-scheme-from-root-to-the-leaves-39693ceaefa6">ElGamal Scheme. From Root to the Leaves</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hierarchical clustering with a work-out example]]></title>
            <link>https://medium.datadriveninvestor.com/hierarchical-clustering-with-a-work-out-example-b5b0c86f9c53?source=rss-ccfbeb4e8d4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5b0c86f9c53</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[hierarchical-clustering]]></category>
            <dc:creator><![CDATA[Hussain Safwan]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 13:18:28 GMT</pubDate>
            <atom:updated>2020-09-26T15:03:08.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FoZc60lQMsBybnI4" /><figcaption>Photo by <a href="https://unsplash.com/@amandamocci?utm_source=medium&amp;utm_medium=referral">Amanda Mocci</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Say you’ve got a bunch of points (or objects, suppose, with reasonable similarity among each) and now you want to arrange them into nice little buckets, but the problem is you don’t know how many different sets to partition them into. So you can’t use k means or any related ones (obviously because the value of k is not known or cant feasibly be guessed). What can you do now? We go HIERARCHICAL then!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1J3NPQf42bgLV3Bm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1J3NPQf42bgLV3Bm%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl1J3NPQf42bgLV3Bm%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d6971805d9ea6344178de4910bb26e/href">https://medium.com/media/57d6971805d9ea6344178de4910bb26e/href</a></iframe><p>Okay, funs aside😉. The idea of hierarchical clustering is to build clusters that have predominant ordering from top to bottom (<a href="https://www.kdnuggets.com/2019/09/hierarchical-clustering.html">head on to this site</a>, quite awesome explanation). In this episode, we have a look at the ground on which hierarchical clustering is built on, it’s classification, algorithm and as always a worked-out example to build firm the concepts.</p><p><strong>Please note that</strong> this is not introductory writing(if that’s what you’re looking for, then <a href="https://towardsdatascience.com/hierarchical-clustering-explained-e58d2f936323">here’s a master article</a>), so I’ll assume you’ve got a rough understanding of hierarchical clustering. The purpose of this blogpost is to show the internal mechanisms of the algorithm which I aim to achieve by solving an example.</p><p><a href="https://www.datadriveninvestor.com/2020/08/27/what-is-a-data-catalog-and-how-does-it-enable-machine-learning-success/">What Is A Data Catalog and How Does It Enable Machine Learning Success? | DataDrivenInvestor</a></p><h3>Why hierarchical clustering</h3><p>The fact of not having known the value of k isn’t intuitive enough. So I came up with this example. Say, you’re researching the effect of geography on culture and suppose you start with Asia. In Asia, there are countries under the cultural influence of India, which might form a cluster (say the name of the cluster is India), then there are ones under that of China forming another cluster (cluster China), these are level 1 clusters. These two clusters would merge to form a bigger cluster (say Indochina) since there might be similarities between Indian and Chinese cultures, this is a level 2 cluster. Say this level 2 cluster merges with another level 2 cluster (say Persian cluster) to form a level 3 cluster which is Asia itself (oversimplified for mere illustrative purpose). Here at the beginning, each individual country was a cluster by itself, of level 0. What I’m trying to explain is that this technique of clustering is used when along with clustering the relations between the clusters and their components and aggregate are also needed to be known. Hope this insane example makes a point to the readers.</p><h3>Classification.</h3><p>Broadly of two types.</p><p><strong>Agglomerative</strong>: In this class, the individual clusters, in each iterative step, merge into a larger one, until there one big cluster. ONE CLUSTER TO INCLUDE THEM ALL!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FelUGwgiPOdq7e%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FelUGwgiPOdq7e%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FelUGwgiPOdq7e%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="355" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f7f60f31241aaa6f22a5bae689593d3/href">https://medium.com/media/5f7f60f31241aaa6f22a5bae689593d3/href</a></iframe><p><strong>Divisive</strong>: As the name suggests, it works just the opposite of agglomerative and breaks down the larger cluster until each cluster comprises of a single item. We’re mainly gonna focus on agglomerative clustering, since we believe in building and not breaking, just kiddin’😜.</p><h3>The algorithm</h3><p>Described in words, we’re given a distance matrix, to begin with (we’ll see how that looks in a minute) containing the pairwise distance between the points. What we have to do is to pack up the independent points into clusters. We begin with the two points with the minimum distance and include them in a cluster. Then measure reconsider the matrix and pack up the points with current minimum distance, note that each newly formed clusters are treated as ordinary points while determining the distance. Now the big question that arises is how is the distance between a cluster and a point calculated? To put that into perspective, say we’ve got a cluster [A, B] and an independent point C, how’s the distance to be calculated? Well, as it turns out there are quite a few ways to do so.</p><ol><li>Min approach: Distance here is the minimum of the pairwise distances, like in above example,</li></ol><blockquote>d([A, B], C) = min(d(A, C), d(B, C)).</blockquote><p>This is also called single linkage.</p><ol><li>Max approach: Max of the pairwise distances taken.</li><li>Average: Average of the pairwise distances taken. Like</li></ol><blockquote>d([A, B], C) = (d(A, C) + d(B, C)) / 2</blockquote><p>Now, these are by no means the only metrics used, there are quite a few out there like weighted/unweighted average, Ward’s distance, and others. Okay, I can hear you asking which one to use. That depends upon the dataset you’re working with, how scattered the data is, what you wan to make out of this and some other factors. According to data scientists, it might be a wise choice to try them all out and then decide where the best of results come from. As of now, I’d be using the single linkage metric for the rest of the article. Semi-formal pseudocode might look something like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQVw8B-3gPc09IBoFQwPSQ.png" /></figure><h3>Little work-out</h3><p>For this example, I’m gonna use the following distance matrix,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*tEhYgbmKjaa77BE4TL8uZQ.jpeg" /></figure><p>Notice, the diagonal is zeroed out and the matrix is lower triangular because distance from a point to itself is taken to be 0 and the distances need to be printed once.</p><p>First things first, search for the pair with the minimum distance. That is 2, the distance between points 3 and 5. So cluster them up and present them like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*VUn7u6Uua5fWImeK6XbzkQ.jpeg" /></figure><p>There are quite a few observations to be made. First the dimension of the matrix dropped by 1 on each, from 5 x 5 to 4 x 4. Then the distances are rearranged (marked in gray are the distances of interest, rest are just copied down from the previous state).</p><p>Little insight on distance adjustment:</p><blockquote>d([P3, P5], P1) = min (d(P3, P1), d(P5, P1)) = min(3, 11) = 3</blockquote><blockquote>d([P3, P5], P2) = min (7, 10) = 7</blockquote><blockquote>d([P3, P5], [P3, P5]) = 0</blockquote><blockquote>d([P3, P5], P4) = min (8, 9) = 8</blockquote><p>This is the first iteration. Then the same calculations are repeated until one final cluster remains. Here’s how the matrix may look after the second iteration,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*o7mAJi8k9vBctUKISfafQw.jpeg" /></figure><p>I think you got the concept and can pretty well continue from here on. Just choose the least distance and pack the endpoints into a new cluster. That’s all.</p><p>Hope that helps you with handling all the branches. And as always, BE COOL!</p><h4>Gain Access to Expert View — <a href="https://datadriveninvestor.com/ddi-intel">Subscribe to DDI Intel</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5b0c86f9c53" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/hierarchical-clustering-with-a-work-out-example-b5b0c86f9c53">Hierarchical clustering with a work-out example</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>