<?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 Tarlan Ahadli on Medium]]></title>
        <description><![CDATA[Stories by Tarlan Ahadli on Medium]]></description>
        <link>https://medium.com/@tarlanahad?source=rss-49d8eab979a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-SwOIguAATl0XED9a7GWrg.jpeg</url>
            <title>Stories by Tarlan Ahadli on Medium</title>
            <link>https://medium.com/@tarlanahad?source=rss-49d8eab979a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:24:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tarlanahad/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[Linear SVM Classifier: Step-by-step Theoretical Explanation with Python Implementation]]></title>
            <link>https://medium.com/@tarlanahad/linear-svm-classifier-step-by-step-theoretical-explanation-with-python-implementation-d86c4973dc33?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86c4973dc33</guid>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 03:29:33 GMT</pubDate>
            <atom:updated>2021-08-24T03:29:33.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8QW3XlEYylXDDvkDp5XGA.png" /></figure><h4>Understanding Mathematical as well as Algorithmic procedures behind the SVM</h4><h3>Table of Content</h3><ul><li><strong>Introduction</strong></li><li><strong>Support Vector Machines</strong></li><li><strong>Mathematical Definition of Decision Boundary</strong></li><li><strong>Decision Rule</strong></li><li><strong>Parametrizing Margin of SVM model</strong></li><li><strong>Optimization Problem</strong></li><li><strong>Constrained Quadratic Optimization with Lagrange Multipliers</strong></li><li><strong>Implementation of SVM in Python</strong></li><li><strong>Conclusion</strong></li><li><strong>Resources and References</strong></li></ul><h3>Introduction</h3><p>Machine Learning (ML) is a powerful tool that allows humans to make the computers analyze the features of the collected data and make use of it for further predictions. Different algorithms utilize different approaches for learning and decision procedures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOV1RtZvUKL1isE3blZ9jA.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>In <em>Figure 1</em> various linear decision strategies of 3 well-known ML algorithms are shown. As can be seen from the graphs, although they use different rules to classify the samples, the fundamental principle of the decision-making process is same. All the described algorithms draw line(s) (also called <strong>decision boundary) </strong>to separate negative and positive samples.</p><h3>Support Vector Machines</h3><p>Support Vector Machines (SVM) is one of the sophisticated supervised ML algorithms that can be applied for both classification and regression problems. The idea was first introduced by Vladimir Naumovich Vapnik [1] during the early ’90s. The main question that V. Vapnik asked during the development process of the algorithm was:</p><blockquote>How to draw a straight line that best separates 2 classes?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dec0kWJRTLqIbthMFx4akw.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>In <em>Figure 2</em> lines with different positions were drawn to separate negative and positive samples. In the graph (1) and (3) the drawn lines are too close to the negative or positive samples respectively which decrease/increase the allotted gap (margin) for one of the classes. <strong>However, to sustain the objectivity of the decision process, the line must be drawn such that the allowed margin for both classes is equally wide.</strong></p><h3>Mathematical Definition of Decision Boundary</h3><p>In the N-Dimensional (ND) feature space, the dimension of the decision boundary corresponds to N-1. For example:</p><p>— For 2D feature space, the decision boundary will be a line. <br> — For 3D feature space, the decision boundary will be a 2D plane.</p><p>Thus, to generalize the representation of the plane of the decision boundary the vector that is normal (perpendicular) to the medium of the plane can be utilized. That is how any plane (line) can be described using a single equation. [2]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icibpfK8Fsa_6ZNx7LCBgw.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>To represent the decision boundary, a vector (<strong>w</strong>) starting from the origin and normal the plane is drawn. However, there’s no piece of information about the parameters as well as the length of the vector <strong>w</strong>.</p><h3>Decision Rule</h3><p>Now let’s imagine we include an unknown sample (<strong>u</strong>) into the feature space. It is worth noting that any point in the cartesian coordinate system can be represented using a vector starting from the origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pudOUTLinEievaMHrdFMwA.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><p>To determine whether an unknown sample is on the right or left side of the decision boundary the vector <strong>u </strong>can be projected onto the vector<strong> w </strong>by finding their dot product.<strong> </strong>If the value of projection of <strong>u</strong> onto <strong>w</strong> is greater than an unknown <strong>c</strong>, then a sample <strong>u</strong> is on the right side of the boundary or vice-versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MQbDyh2gFXB_MyBBl9v2Q.png" /></figure><p>Without loss of generality the <em>equation 1</em> can be modified by assuming<strong> <em>c = -b.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0JB8KmqfNg9n7P64WdvLw.png" /></figure><p>Above-written <em>equation 2</em> is a <strong><em>decision rule</em></strong> of the SVM containing two unknown variables — <strong>w</strong> and <strong>b </strong>which are obtained during the training process of the SVM model.</p><h3>Parametrizing Margin of SVM model</h3><p>To be able to define the distance from each support-vector to the decision boundary, the decision rule for both classes should be considered separately. Due to mathematical convenience, the margin distance of <strong>1</strong> will be used after which the derived equation can be multiplied by any constant to increase/decrease margin proportionally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TwsWfYP1VorwSxXD_O97w.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>Thus, <em>equation 2</em> for the positive (x+) and negative (x-) samples can be modified as it is described in <em>equation 3.1</em> and <em>3.2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l_LwJf6SKkqmxqN15LtxA.png" /></figure><p><em>Basically, by doing so we force the decision boundary to have a separation of distance from -1 to +1 for all the training samples.</em></p><p>Although there are 2 separate equations for different classes, by multiplying <em>equation 3.1</em> with +1 and <em>3.2</em> with -1 the equations can be merged into one (<em>equation 5</em>) which will be more mathematically convenient. For this, a new variable <strong>yᵢ</strong> (<em>equation 4</em>) will be included in the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXg0NvR14G9-Dd9jLhFctg.png" /></figure><p>By considering <em>equation 5 </em>the result of the decision rule for the samples on the support vectors can be derived which is also described in <em>Figure 6</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiO5lBb4-ICWpZVPCFLrVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBh0-KGRwWp2pL_88Afukg.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><h3>Optimization Problem</h3><p>In the previous sections, the constraints for determining the decision boundary of SVM were discussed. However, the main objective of SVM is to find a decision boundary with the widest distance of margin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQy8MOaYygux-dWT9Y-syw.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><p>To find the distance between the support vectors, any of the positive (+) and negative (-) samples that are located on the support vectors can be used. The distance will be equal to the projection of the difference of the vectors onto the unit vector in the direction of normal vector <strong>w</strong>. The unit vector can be calculated by dividing the components of the vector <strong>w</strong> by its length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2u-4U5J7HQneM0m22buIg.png" /></figure><p><em>Equation 6</em> can be further simplified by using equation 3.1 and 3.2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asD9hTQomH-K5AiDLo8ylQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-Xb2fzbIAndWf3N3mIU7g.png" /></figure><p>Last, a simple equation (8) was derived that describes the distance between the support vectors. The objective is to maximize it as well as considering the constraints discussed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5nH-O3w1X_2nrOux6bUiQ.png" /></figure><p>Equation 9 describes the conversion steps of optimization problem into quadratic optimization which is more mathematically convenient during the obtaining process of gradients with respect to <strong>w</strong>.</p><h3>Constrained Quadratic Optimization with Lagrange Multipliers</h3><p>The function that has to be minimized in <em>equation 9</em> is constrained by additional functions given in <strong>Figure 6. </strong>For the problem of constrained optimization Lagrange multipliers [3] can be utilized, simply, to convert a constrained optimization problem into unconstrained one [4] which is more computationally convenient. What theory of Lagrange multipliers claims is that:</p><blockquote>For the minimum/maximum solution of the function f(x) constrained by g(x), the level curve of the f(x) is tangent to the level curve of the g(x). Thus, if the level curves are tangent, their gradients must be parallel.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZDV9FB3xAO1X9d0DgPvNQ.png" /></figure><p>By using <em>equation 10</em> the constrained optimization problem of SVM is converted to the unconstrained one. A new equation will be the objective function of SVM with the summation over all constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-p50VaQsLDN6gJD7qnPPg.png" /></figure><p>In <em>equation 11</em> the Lagrange multiplier was not included as an argument to the objective function L(w,b). As the value of the multiplier <strong>𝛼</strong> will be set conditionally during the numerical optimization process such that:</p><ul><li>If the sample is on the support vector: <strong>𝛼 = 1</strong></li><li>else: <strong>𝛼 = 0</strong></li></ul><p>To minimize the objective function the approach of Gradient Descent will be implemented. Here computation of the gradient of L(w,b) with respect to <strong>w</strong> and <strong>b</strong> is required which are described in the equations below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS3V2y2WL7ggW0xfxRv3xQ.png" /></figure><p>As the mathematical foundation of the SVM was completely discussed, it is time for the implementation in Python by utilizing only ‘NumPy’ module.</p><h3>Implementation of SVM in Python</h3><p>Because of its versatility, the implementation of linear SVM will be realized in the class form with an initializer that requires:</p><ul><li>X,y — training set</li><li>num_of_epochs — Number of Epochs</li><li>lr — Learning rate for Gradient Descent</li><li>C — The constant that controls the influence of each individual support vector on the objective function.<strong> </strong>Greater C decreases the effect of <strong>|w|²/2, </strong>and results in the narrower margin. [6]</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aac121d3befb74b99f4cca867056d4fe/href">https://medium.com/media/aac121d3befb74b99f4cca867056d4fe/href</a></iframe><p>In the following code, the function ‘<strong><em>distances’ </em></strong>is for calculating <em>equation 5</em> by considering the Lagrange Multipliers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/202fcd01f512e1be4642adfeb191c446/href">https://medium.com/media/202fcd01f512e1be4642adfeb191c446/href</a></iframe><p>The function<strong><em> ‘get_cost_grads’</em></strong> is for calculating the cost for the given normal vector <strong>w </strong>and finding the gradient of the objective function with respect to<strong> w.</strong></p><p>The function <strong>‘fit’</strong> is for updating the vector <strong>w</strong> at each iteration. Function <strong><em>‘predict’ </em></strong>is for predicting the class of the unknown sample based on the decision rule given in <em>equation 2</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d9080382aa7faad02fd270f353404b/href">https://medium.com/media/a0d9080382aa7faad02fd270f353404b/href</a></iframe><p>Now it’s time to test the performance of SVM class on a <em>linearly separable data [5]</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f194d86c2277d3427344404c2a66dd33/href">https://medium.com/media/f194d86c2277d3427344404c2a66dd33/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/152fdbf3dcd8cdeaf2768dbedda93873/href">https://medium.com/media/152fdbf3dcd8cdeaf2768dbedda93873/href</a></iframe><p>The algorithm works like a charm!</p><h3>Conclusion</h3><p>SVM is a remarkably powerful algorithm as well as one of the paradigms in the field of ML. The philosophy behind the algorithm is highly sophisticated and intuitive. In the following articles, the implementation of the Soft Margin SVM Classifier on non-linearly separable data will be discussed.</p><p>Stay Healthy and Strong!</p><h3>Resources and References</h3><p>[1] <a href="https://www.wikiwand.com/en/Vladimir_Vapnik">Vladimir Naumovich Vapnik — Wikipedia Page</a><br>[2] <a href="https://youtu.be/YBajUR3EFSM">Lec 4 | MIT 18.02 Multivariable Calculus, Fall 2007</a><br>[3] <a href="https://www.youtube.com/watch?v=15HVevXRsBA">Lec 13 | MIT 18.02 Multivariable Calculus, Fall 2007</a><br>[4] <a href="https://qr.ae/pNnEBE">Intuitively, how do Lagrange multipliers work in SVMs?</a><br>[5] <a href="https://bitbucket.org/tarlanahad/myneatcodes/src/master/SVM/Python/files/data.csv">Linearly separable data for testing the algorithm</a><br>[6] <a href="https://stats.stackexchange.com/a/159051/224752">What is the influence of C in SVMs with linear kernel?</a> — Stats.StackExchange.com<br>[7] <a href="https://bitbucket.org/tarlanahad/myneatcodes/src/master/SVM/Python">Full Python Project Codes for Linear SVM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86c4973dc33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naive Bayes Classifier: Bayes Inference, Central Limit Theorem, Python/C++ Implementation]]></title>
            <link>https://medium.com/data-science/naive-bayes-classifier-bayes-inference-central-limit-theorem-python-c-implementation-bdffb3b35de?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdffb3b35de</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 15:01:52 GMT</pubDate>
            <atom:updated>2020-04-12T16:54:14.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>Naive Bayes Classifier: Bayesian Inference, Central Limit Theorem, Python/C++ Implementation</h3><h4>Understanding Mathematical Base of Naive Bayes Classifier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dkvjWfaKOaKShbmr72kWA.png" /></figure><h3>Table of Content</h3><ul><li><strong>Introduction</strong></li><li><strong>1. Conditional Probability</strong></li><li>Definition</li><li>Intuition</li><li>Quick Example</li><li>Chain Rule</li><li><strong>2. Independence</strong></li><li>Definition</li><li>Intuition</li><li>Quick Example</li><li><strong>3. Conditional Independence</strong></li><li>Definition</li><li>Proof</li><li>Quick Example</li><li><strong>4. Bayes’ Theorem and Naive Bayes Classifier</strong></li><li>Definition</li><li>Proof</li><li><strong>5. Central Limit Theorem and Normal Distribution</strong></li><li><strong>6. Implementation of the Theory</strong></li><li><strong>7. Conclusion</strong></li><li><strong>8. Resources and References</strong></li></ul><h3>Introduction</h3><p>In the following article, the details of Bayes’ Theory with respective mathematical proofs will be discussed and then the implementation of the theory will be realized in the context of Naive Bayes Classifier using programming languages Python and C++. The article mostly targets who are eager to gain deeper insight into the astonishing world of Bayesian Inference. It is worth noting that before introducing the concept of Bayes’ Theorem, milestones will be discussed for which minimal knowledge of probability theory is prerequisite. Once, the mathematical base of the algorithm has been understood, implementation will be downhill all the way.</p><h3>1. Conditional Probability</h3><p>Probability is the branch of mathematics that axiomatize and formalize the probability measure of the outcome of the <em>sample space</em>. <em>Sample space</em> is the set of the events such as getting 5 on thrown dice.</p><h4>Definition</h4><p><em>Conditional probability</em> is a probability measure of an event <strong>A</strong> given that another event <strong>B</strong> already occurred. Simply, if 2 events are interrelated, having piece information about any of them will influence the probability measure of another one. In <em>equation 1.1</em> below, conditional probability measure of event A given event B is described.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8byXrLyx4uPf6tm3jMHfvQ.png" /></figure><h4>Intuition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvHh3o78ZpQty-jYn3k1Yg.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p><em>Equation 1.1</em> can be described as a division of the area of the intersection of the events A and B to the whole area of subspace B.</p><h4>Quick Example</h4><p>The portion of the adults who are men and alcoholic is 2.25%. What is the probability of being an alcoholic given being a man?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qblSn7ALMXpUK6Lc3apDJg.png" /></figure><p>To paraphrase the question, the probability of being a man and alcoholic of a randomly selected individual is 2.25%. What is the probability of being alcoholic if you already know that an individual is a man?</p><p>Assuming that 2 genders are distributed evenly, the probability of being a man implies 0.5. By putting all given parameters into <em>equation 1.1</em> we get 4.5%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*006HFO5QMzqZFBbSFMmFEw.png" /></figure><p>Basically, having additional information about the gender of the individual increases our probabilistic certainty from 2.25% to 4.5%.</p><h4>Chain Rule</h4><p>Chain rule is a probabilistic phenomenon that helps us to find the joint distribution of members of a set using the product of conditional probabilities. To derive the chain rule, <em>equation 1.1</em> can be used. First of all, let’s calculate the joint probability for 2 events — A and B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bw5j-SXg6g5_qN-PIez3rA.png" /></figure><p>Using the same principle, we can also find the joint probability of 3 events — A, B, C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Y-P72ymNQTM4J4Q7PHzAg.png" /></figure><p>By comparing patterns between <em>equations 1.2</em> and <em>1.3</em> general equation to calculate the joint probability of N number of events can be determined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQ2zw4ZBw3yFmQdIdMI4bg.png" /></figure><h3>2. Independence</h3><p>Two events are independent if the occurrence of one does not affect the probability of occurrence of the other. [2]</p><h4>Definition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFiQHcTPSxVPiz4xAzTH-Q.png" /></figure><p>From <em>equation 2.1</em> it is clear that having information about event B doesn’t affect the probability measure of event A -&gt; <strong>P(A|B) = P(A)</strong>.</p><h4>Intuition</h4><p>If event A and B are independent, having information about event B should affect the probability measure of event A the same as having any information from universe U (<em>Refer to </em><strong><em>Figure 1</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrbP6YCBDM6xzLpHO6X2PQ.png" /></figure><h4>Quick Example</h4><p>If a dice is thrown twice, what is the probability of getting two 5&#39;s?</p><p>Event A — Getting 5 on a thrown dice for the first time<br>Event B — Getting 5 on a thrown dice for the second time</p><p>As there are six different numbers on a dice, the probability of getting 5 yields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gAybE0-Q5tEGPMKm_TMYg.png" /></figure><p>It is clear that getting 5 for the first time (Event A) doesn’t provide any information about the event B. Thus, as event A and B are independent, the probability of getting 5 for both events <em>A and B</em> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6_0nZ0VUQjhN6YSK5SAMg.png" /></figure><h3>3. Conditional Independence</h3><h4>Definition</h4><p>Events A and B are conditionally independent given C if and only if, given the knowledge that C occurs, knowledge of whether A occurs provides no information on the likelihood of B occurring, and knowledge of whether B occurs provides no information on the likelihood of A occurring. [3]</p><p>Basically, R and B are the events of persons <strong>A</strong> and <strong>B</strong> getting home in time for dinner, and Y is the event of a snowstorm hitting the city. Certainly, the probabilities of RR and BB will depend on whether YY occurs. However, just as it’s plausible to assume that if these two people have nothing to do with each other their probabilities of getting home in time are independent [4]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyCIc8SoqhcS740a0-8lxg.png" /></figure><h4>Proof</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjQIm-HJr06AtAb-iZK_lA.png" /></figure><p>The pattern in equation 3.1 can be applied to N conditionally independent events as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gngF9AxFNYRwKmfdXT3wsQ.png" /></figure><h3>4. Bayes’ Theorem and Naive Bayes Classifier</h3><h4>Definition</h4><p>Bayes’ Theorem is a powerful tool that enables us to calculate <strong>posterior </strong>probability based on given <strong>prior </strong>knowledge and <strong>evidence</strong>. It’s the same principle as doing a training on data and obtaining useful knowledge for further prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfG1PY5-VSILokC66mLtsA.png" /></figure><ul><li>P(y|x) — <strong>posterior </strong>— the probability of the occurrence of event <strong>y</strong> if the occurrence of event <strong>x</strong> is given.</li><li>P(x|y) — <strong>likelihood </strong>— the likelihood of the occurrence of event <strong>x</strong> if the occurrence of event <strong>y</strong> is given.</li><li>P(y) — <strong>prior </strong>— belief about the probability measure of the occurrence of unknown event <strong>y</strong> before obtaining some knowledge/evidence <strong>x</strong></li><li>P(x) — <strong>evidence </strong>— a piece of information that was given as evidence to calculate posterior</li></ul><h4>Proof</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Am-scPr0vgTrM2yhU6En9A.png" /></figure><p>For Machine Learning classification and prediction tasks, we are usually given feature vector X = (x1,…,xn) and corresponding class labels y = (1,…,m). Feature row vector can be assumed as a joint probability of the features. Thus, equation 4.1 becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ACzjCBBix6F8ABvYp9iUw.png" /></figure><p><strong>Now the features of the vector X will be assumed as independent events to simplify the model complexity.</strong> Then 4.2 will be further simplified by appropriating equation 3.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zssWkM_blkQmM7MESfEVOw.png" /></figure><p><em>Indeed, the independence assumption is the main reason why the approach is called ‘</em><strong><em>Naive</em></strong><em>’.</em> Because in the real-world applications, it is highly probable of features being related to or dependent on each other. Despite the ‘naive’ assumption, simplification of the model complexity sometimes results in a surprisingly useful performance.</p><p>The <em>equation 4.3</em> will help us to predict the class of the given feature vector <strong>x</strong> (x1,…xn) by comparing the measure of the posterior probability for different class parameters — y. Then the posterior with the highest value that corresponds to the class will be chosen as the class of unknown feature vector <strong>x</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEWdPFTuUFTHRAyTIIjc8Q.png" /></figure><p>Assuming that the denominator of the equation is staying constant during the comparison process for different classes <strong>y</strong>, it is possible to compare solely numerator part of the equation which will simplify the process further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWbOgdp66SuI0YA5EFAYmA.png" /></figure><p>The equation above (4.5) is more than enough to predict the class of the given feature vector. However, considering the value range of the measure of the probability is between 0 and 1, having the product of several of them can lead to the problem of the arithmetic underflow [5]. Fortunately, the problem can be easily addressed by taking the log (base should be greater than 1) of equation 4.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN6DELnR1seIknIyIP5D5A.png" /></figure><p>In equation 4.6 there are 2 parameters that are needed to predict the class label of feature vector <strong>x</strong>.</p><ol><li>P(y) — <strong>Prior </strong>— Before taking the evidence (feature vector) into consideration, distribution of the probability of class labels <strong>y</strong> is a prior probability<strong> </strong>which is related to its frequency in the training set. Basically, for the exemplary-given label set <strong>&lt;0,0,1,1,1&gt;</strong> prior of class <strong>‘0’</strong> is 2/5.</li></ol><p>2. P(x₁| y)… P(xₙ| y) — For the classification problem, although the values of y — class labels are discrete, values of feature vector <strong>x</strong> is, usually, continuous values as shown in <strong>Table 1</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/854e74141b4df7495d89a37db15356ad/href">https://medium.com/media/854e74141b4df7495d89a37db15356ad/href</a></iframe><p>So we need a special tool, that will help us to get information about the likelihood of the occurrence of some event. For example, If the corresponding feature value for class 1.0 is 1.898, what is the likelihood of having 1.0 if the feature value is 1.897?</p><h3>5. Central Limit Theorem and Normal Distribution</h3><blockquote>The central limit theorem states that if you have a population with mean μ and standard deviation σ and take sufficiently large random samples from the population <strong>with replacement</strong>, then the distribution of the sample means will be approximately normally distributed.[7]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lNaqfRmBw2UZF9zT8Qp4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*5n_gFCojLGfN3W6E" /><figcaption><strong>Normal Distribution: Resources and References [6]</strong></figcaption></figure><p>Simply, in probability theory as well as in nature Normal Distribution approximates the pattern of the deviation of random quantities from the ‘true’ (mean) value. As an example:</p><p>The histograms below describe the age distribution of survived/passed away passengers in the Titanic accident. The above-mentioned pattern of the Normal Distribution can also be seen here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKnnv8IWZPaDnNC-rSwVhg.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p><em>By considering the general distribution pattern of independent random variables, we’ll assume that for each class the values of the feature columns are distributed normally as well. </em>Thus, the mean of the values of the columns for each class will represent ‘true’ feature values for the class. The closeness of the feature vector of an unknown to the mean feature values of some class will represent how they are likely to be the same. To represent the measure of this similarity we’ll use Gaussian Probability Density Function (Gaussian PDF).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JbI9N3ok59FQydZPdNeIg.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>Figure 3 represents the distribution of the features of 2 classes. Each class has its own mean and standard deviation value shown with exact values on the legend of the plot. So:</p><ul><li>P(<strong>x</strong> | μ<strong>⁰</strong>, σ² <strong>⁰</strong>) ≈ 0.125</li><li>P(<strong>x</strong> | μ<strong>¹</strong>, σ² <strong>¹</strong>) ≈ 0.025</li></ul><p>Therefore, the likelihood of x to be class ‘0’ is more than class ‘1’.</p><h3>6. Implementation of the Theory</h3><p>By considering its extensive usage, the implementation will be explained on Python programming language. However, the identical code implementation has been realized in C++ and added to the project codes given link in the Resources and References section. [9]</p><p>Owing to the ease of utilization algorithm will be written in the form of class-structured code. The class will take 2 arguments:</p><ul><li>X — Training Feature Set</li><li>y — Label set</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee50537454c68d57151d5575650799be/href">https://medium.com/media/ee50537454c68d57151d5575650799be/href</a></iframe><p>The next step is to write ‘fit’ function during which the mean and STD values of the feature columns is stored into the defined lists. The process can also be named as Training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77b5bc118f4bc3e7597e82c8e59687b4/href">https://medium.com/media/77b5bc118f4bc3e7597e82c8e59687b4/href</a></iframe><p>Once the corresponding mean and STD values of classes have been calculated, the class of an unknown feature vector can be predicted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e171904c3932c7b4ead1186fd807b7/href">https://medium.com/media/93e171904c3932c7b4ead1186fd807b7/href</a></iframe><p>To test the performance of the algorithm, we can randomly generate data using the ‘sklearn’ python module and then split it as training and test data set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa30984bd6b9f9cfe89e3b5a68878f8/href">https://medium.com/media/9aa30984bd6b9f9cfe89e3b5a68878f8/href</a></iframe><p>As you witness, the ‘Naive’ assumption based algorithm works like a charm and introduces more than 90% of accuracy. The value of the accuracy may increase/decrease regarding randomly generated data set features.</p><h3>7. Conclusion</h3><p>I hope the article dug sufficiently enough into the topic of Naive Bayes Classifier. If you have any comments/suggestion about the article, you can reach me at <a href="https://twitter.com/tarlanahad">my twitter account</a>.</p><h3>8. Resources and References</h3><p>[1] <a href="https://www.wikiwand.com/en/Venn_diagram">Venn Diagram — Wikipedia</a><br>[2] <a href="https://www.wikiwand.com/en/Independence_(probability_theory)">Independence — Wikipedia</a><br>[3] <a href="https://www.wikiwand.com/en/Conditional_independence">Conditional Independence — Wikipedia</a><br>[4] <a href="https://math.stackexchange.com/a/23100/516078">Math StackExchange Answer to the question — Could someone explain conditional independence?</a><br>[5] <a href="https://www.wikiwand.com/en/Arithmetic_underflow">Arithmetic Underflow — Wikipedia</a><br>[6] <a href="https://www.wikiwand.com/en/Normal_distribution">Normal Distribution — Wikipedia</a><br>[7]<a href="http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/BS704_Probability/BS704_Probability12.html"> Central Limit Theorem</a><br>[8] <a href="https://youtu.be/Ws63I3F7Moc">Origin of Markov chains | Journey into information theory | Computer Science | Khan Academy</a><br>[9] <a href="https://bitbucket.org/tarlanahad/myneatcodes/src/master/Naive%20Bayes%20Classifier/">Naive Bayes Classifier ‘Python/C++’ Project codes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdffb3b35de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/naive-bayes-classifier-bayes-inference-central-limit-theorem-python-c-implementation-bdffb3b35de">Naive Bayes Classifier: Bayes Inference, Central Limit Theorem, Python/C++ Implementation</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[Nature-Inspired Optimization Algorithms: Particle Swarm Optimization]]></title>
            <link>https://medium.com/data-science/nature-inspired-optimization-algorithms-particle-swarm-optimization-2cd207d0d37e?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd207d0d37e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[visualisation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Fri, 17 Jan 2020 22:01:33 GMT</pubDate>
            <atom:updated>2020-01-18T08:20:28.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHC46tTrxzQT6sN6SUcgjw.gif" /><figcaption>The murmuration starlings</figcaption></figure><h3>Nature-Inspired Optimization Algorithms: Particle Swarm Optimization Using Python</h3><h4>Taking advantage of the million-year process of Natural Selection to solve the numerical optimization problem</h4><h3>Table of content</h3><ul><li><strong>Introduction</strong></li><li><strong>What is Emergent Complexity?</strong></li><li><strong>Modeling Bird Swarm Intelligence</strong></li><li><strong>Implementing Theory Using Python</strong></li><li><strong>Conclusion</strong></li><li><strong>Resources and References</strong></li></ul><h3>Introduction</h3><p>Particle Swarm Optimization (PSO) is a powerful algorithm based on Stochastic Optimization and inspired by the rules involved in large flocks of birds. In this article, the feasibility of the approach will be backed up, then an accurate model of these principles will be derived. Finally, the implementation of a mathematical model of these principles for the numerical optimization problem will be described and then realized using Python to find the global minima of Rastrigin Function [1]. If you’re coding in C++, you can refer to the link written in the Resources and References section [2] to view the project source codes.</p><h3>What is Emergent Complexity?</h3><p>Emergent Complexity[3] is the phenomenon that describes how individual components of large groups work together with the same but simpler rules to create diverse and intricate systems. There are a few natural complex behaviors that can be an example of emergence. For instance, ants instinctually communicate with each other to build a live bridge which minimizes the commutation distance while searching for a food source[4]. Birds are following each other and create larger groups which increase their likelihood of detecting predators as well as the food source. Unlike the usual concept of complexity which is not necessarily useful, natural complexity is the result of a million-year process of natural selection in which energy usage is the most essential factor to increase the chance of staying alive. Thus, if there are two solutions to the same problem, the way which is simpler and requires less energy will survive because of natural selection. That’s why the solution that nature suggests will be simple but still effective to decrease the energy consumption of the animals as much as possible. Hence, scientists observed each bird in a flock of starlings individually and found out that each of them takes simple actions to form complex structuring.</p><ol><li>Each bird has its own position and velocity</li><li>Each bird has its own vision span in which it can follow the surrounding bird(s). The bird is absolutely unaware of the actions outside of this span.</li><li>If any of the birds spotted food all the birds in the flock will tend to that direction.</li></ol><h3><strong>Modeling Bird Swarm Intelligence</strong></h3><p>As in nature, in a numerical problem, any of the boid’s (bird-like-object) observable vicinity is limited to some range. Therefore, it can converge to some local minima or saddle point in which the gradient (in our case velocity) will be 0. However, having more than one boid allows all the birds in a swarm to be aware of the larger surface of an error function and not getting stuck in local minima if any of them has seen a better position in terms of error. For this, we’ll mathematically model the above-mentioned principles to make the swarm find the global minima of an error function</p><ol><li>Each boid has its own position and velocity. We can consider a velocity as a vector of partial derivatives of an error function.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*p8IYgn8FMhEg8nLw4r1v-Q@2x.png" /><figcaption>The surface plot of f(x)= x²+y² function</figcaption></figure><p>2. Each boid keeps track of the best position that it ever experienced which contributes to the current velocity of boid to some predefined extend.</p><p>3. There’ll the best position that the whole birds of swarm ever saw. Therefore, it will affect the velocity of all the boids at a predefined rate.</p><p>By using the rules above, we can easily derive mathematical equations that will drive each boid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYwixdI1FMpsEwcOZrHBQQ@2x.png" /><figcaption>Vector representation of calculating Delta V</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QopK57QWQl0atyHAl548hA.png" /></figure><p>In the equations above:</p><ul><li>w — is the inertia that determines to what extent the current velocity of boid will effect to ΔV</li><li>c₁, c₂ — defines how boid’s and swarm’s best-recorded position will affect to ΔV respectively</li></ul><p>w, c₁, c₂, learningRate —are the hyperparameters that should be finetuned during the optimization process.</p><h3><strong>Implementing Theory Using Python</strong></h3><p>The mathematical theory behind the swarm intelligence was discussed and modeled and it can be implemented using any modern programming language. However, because of its widespread usage, the implementation will be realized using Python. Still, at the Resources and References section of the article, the C++ project codes can be found as well. To test the algorithm, Rastrigin Function will be utilized as an error function, which is one of the most challenging functions for an optimization problem. Having a lot of cosine oscillations on the plane introduces a myriad of local minimums in which boids can get stuck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*egc5BvvR63j-bsMz-HcxsA.png" /><figcaption>Rastrigin Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG3Q22p3jf4lozGdF-Jikg.png" /><figcaption><a href="https://www.wikiwand.com/en/Rastrigin_function">3D Surface of Rastrigin Function: </a>[1]</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01e55ae52ea7efb1e64620b398a964d3/href">https://medium.com/media/01e55ae52ea7efb1e64620b398a964d3/href</a></iframe><p>As it was mentioned above, each boid will have a position, velocity, error, best position and best-known error. We should also write a setter function to modify parameters when it’s required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90c4082546cf99bfa7800bb3924e54da/href">https://medium.com/media/90c4082546cf99bfa7800bb3924e54da/href</a></iframe><p>The PSO class will consist of a list of moving particles on the surface of the error function. To initialize the function, the dimension of the function, number of boids, as well as the number of epochs is required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cebb42ddb80b9e2065b58a6beff8ea7/href">https://medium.com/media/8cebb42ddb80b9e2065b58a6beff8ea7/href</a></iframe><p>Last, we write code to find a position that best optimizes the error function. Firstly, at each epoch, every particle is picked one-by-one and optimized its position. Once the position of the particle updated, “if” statement written checks if it’s the best location for the swarm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41773f7b737a350732fe4bbf774d1ff/href">https://medium.com/media/a41773f7b737a350732fe4bbf774d1ff/href</a></iframe><p>Now, it’s time to run the PSO and observe the performance of the algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61bc29804d69b3ae43f6e19e358e3b8c/href">https://medium.com/media/61bc29804d69b3ae43f6e19e358e3b8c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d56882545f8508aaf8ca74c14a9a6b35/href">https://medium.com/media/d56882545f8508aaf8ca74c14a9a6b35/href</a></iframe><p>From the contour plot below, it can be easily seen that swarm takes only a few epochs to converge to the global minimum of the Rastrigin function. To obtain the code that creates contour visualization as well as an Error-Epochs plot of the process you can refer to link given the Resources and References section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fV1HNUyYqXotq-whw_gHSw.gif" /></figure><h3><strong>Conclusion</strong></h3><p>To sum up, Particle Swarm Optimization mimics the collective behavior of the swarm of the birds (or fish). It benefits from the way that nature forms to solve its own optimization problem to minimize energy usage. The design of nature and practical application of its principles to Computer Science problems is marvelous. Although there&#39;s a myriad of resources that can help you to gain more insight about Emergence as well as PSO, I’ll put some of the distinguishing ones that you can use to dig more into the topic of swarm intelligence.</p><h3>Resources and References</h3><p>[1] <a href="https://www.wikiwand.com/en/Rastrigin_function">Wikipedia, Rastrigin Function</a></p><p>[2] <a href="https://bitbucket.org/tarlanahad/myneatcodes/src/master/PSO/">T. Ahadli, Particle Swarm Optimization C++/Python Project Codes</a></p><p>[3]<a href="https://theconversation.com/emergence-the-remarkable-simplicity-of-complexity-30973">The Conversation, The remarkable simplicity of complexity</a></p><p>[4] <a href="https://www.youtube.com/watch?v=4BdjxYUdJS8">National Geographic, How Ants Build Bridges in Mid-Air With Just Their Bodies</a></p><p>[5] <a href="http://youtube.com/watch?v=bVDX_UwthZI">James McCaffrey, Swarm Intelligence Optimization using Python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd207d0d37e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/nature-inspired-optimization-algorithms-particle-swarm-optimization-2cd207d0d37e">Nature-Inspired Optimization Algorithms: Particle Swarm Optimization</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[Most Effective Way To Implement Radial Basis Function Neural Network for Classification Problem]]></title>
            <link>https://medium.com/data-science/most-effective-way-to-implement-radial-basis-function-neural-network-for-classification-problem-33c467803319?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/33c467803319</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 22:08:06 GMT</pubDate>
            <atom:updated>2020-01-10T22:08:06.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP4692bnMXIybBxsKONcZQ.png" /><figcaption>3D visualization of Gaussian Radial Basis Function</figcaption></figure><h4>How to use K-Means Clustering along with Linear regression to classify images</h4><h3>Introduction</h3><p>Radial Basis Function Neural Network or RBFNN is one of the unusual but extremely fast, effective and intuitive Machine Learning algorithms. The 3-layered network can be used to solve both classification and regression problems. In this article, the implementation of <a href="https://www.wikiwand.com/en/MNIST_database">MNIST Handwritten Digits dataset</a> classification is described in which about <strong>94%</strong> of accuracy has been obtained. Additionally, both C++ and Python project codes have been added [3] for the convenience of the people from different programming language backgrounds.</p><h3>Prerequisites</h3><ul><li>K-Means Clustering Algorithm</li><li>Linear Regression</li></ul><p>If you are not familiar with any of the above-mentioned topics, you can refer to the links given in the Resources and References [1][2]<strong> </strong>section at the end of the article.</p><h3>Radial Basis Function</h3><p>Firstly, let’s start with a straightforward example. Imagine that 2D plotted data below was given to you. Your task here is to find a pattern that best approximates the location of the clusters. Thus, when an unknown point is introduced, the model can predict whether it belongs to the first or the second data cluster. The problem can be easily solved by using the K-Means clustering algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*m11b0DaWw0DSE7qa-VWxPA.png" /><figcaption><a href="https://haosutopia.github.io/2018/04/K-Means-01/">https://haosutopia.github.io/2018/04/K-Means-01/</a></figcaption></figure><p>However, RBFNN utilizes a different approach. it models the data plane (in 2D) using circular shapes. Consequently, the cluster to which data belongs can be predicted by considering the cluster centroids and their radii.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*VJJQay6N2GK7hqL-k0QAIQ.png" /></figure><p>But according to the theory described above, there is a possibility that point belongs to none of the clusters if it’s enough far away from all the centroid radii. Consequently, this leads to ambiguity about the class of the data points.</p><p>To address this theoretical gap, Radial Basis Function is used which is the most important part of the RBFNN. Implementation of Radial Basis Function (RBF) enables us to be aware of the rate of the closeness between centroids and any data point irrespective of the range of the distance. RBF models the data using smooth transitioning circular shapes instead of sharp cut-off circles. Additionally, RBF gives information about the confidence rate of prediction which the K-means Clustering algorithm can’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LQwkgHXM95_lcYPzxcMxQ.png" /></figure><p>From the plot above, it can be observed that as we go further away from the centroids of the clusters the intensity of the color smoothly decreases. To have such a smooth transition, <em>exponential function</em> with a negative power of distance can be used. By multiplying the distance with a scalar coefficient <strong><em>Beta </em></strong>we can control how fast the function will decay. So higher Beta means a sharper decline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*MIay3aIlpT18yewOfnvTiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el4kUEIr42JeikDf3rrHFA.png" /></figure><p>It is worth noting that <strong>Beta </strong>is a hyperparameter that should be fine-tuned. However, for testing purposes, 2 options can be tried.</p><ol><li>Using the <em>standard deviation</em> of the cluster:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*7CVXm8FYPF8CFudZBs_gJg.png" /></figure><p>2. Using the equation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*YEcI_P6orY917fQrzHQEjQ.png" /></figure><ul><li><strong><em>K</em></strong> — the number of centroids</li><li><strong><em>Dmax — </em></strong>the maximum distance between any 2 centroids</li></ul><p>The Euclidian distance D can be easily found by using a Pythagorean theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SAufkl_Fz7EagVi27KFlA.png" /></figure><h3>Getting output from Radial Basis Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWEGrMH3OhgIKbbLqOlIEw.png" /></figure><p>The graph diagram above shows how the RBFNN layers are comprised. In the graph, the first layer represents the input data. The second layer which is also called the hidden layer is where RBF of all input data is stored. For example, the node <strong>RBF1 </strong>is the vector with the length of <strong>n</strong> where the RBF of <strong>X ([x1,x2,…,xn])</strong> and <strong>C1</strong> (First centroid vector) is described. RBF1 vector is a measure of how the distance between the <em>first centroid</em> and <em>data X</em> is related to each other.</p><p>Now we have cluster circles and the measure of the distance between data points and cluster centroids. If we consider there’s only one cluster for each digit, by finding the highest RBF between clusters and the given point, we can predict its class. But what would happen if there is more than one cluster for any of the classes?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdFb_8GyoHPBj4KGJfAmPQ.png" /></figure><p>From the scenario illustrated below, although the answer is 2, the classifier yields 3. To solve this problem, the effect of different clusters of the same classes as well as the other ones can be linearly combined. Therefore, the produced output will be based on all the RBFs. The difficulty that arises here is to find <strong>W</strong> ([w1,w2,w3]) that best approximates the linear relationship between RBFs and the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Je9o6wwLv6xSWBXNX5B5fw.png" /></figure><h4>Optimization: Finding weights using Least Squares Linear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*JYSaI5czVApLIEHXqK5zqw.png" /></figure><p>One of the main advantages of RBFNN is the utilization of the Least Squares Linear Regression equation in which obtaining a global minimum of the cost function is relatively fast and guaranteed. On the other hand, other optimization algorithms such as Batch Gradient Descent can also be applied to update weights.</p><p>In the digit classification problem:</p><ul><li>X is the 2-dimensional matrix of RBFs</li><li>y is a one-hot-encoded 2-dimensional matrix.</li></ul><p>Finally, by using the theory explained above, the prediction of the class of the unknown point can be obtained as follow:</p><ol><li>Get <strong>RBF </strong>of an unknown data point <strong>x</strong> with respect to all centroids.</li><li>Calculate dot product of <strong>RBF </strong>and <strong>W </strong>and select an index of maximum value</li></ol><h3>Implementation of theory in Python</h3><ol><li>First, we have to define the required functions that will be used in RBFNN. The modified “kmeans” function returns the cluster centers as well as the standard deviation of the clusters.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa093e0a54f4904a32d781d194689896/href">https://medium.com/media/fa093e0a54f4904a32d781d194689896/href</a></iframe><p>2. To make the implementation more conducive, we can code up RBFNN as a class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b8135fa7561a63695bd8d44e3f59767/href">https://medium.com/media/8b8135fa7561a63695bd8d44e3f59767/href</a></iframe><p>3. Fit function: First lines performs k-means to get centroids and the standard deviation of the clusters. Then we can make the algorithm to use the same <strong>Beta </strong>for all the cluster centroids by using the equation mentioned. In the next lines, we get the RBF of the input X and apply Least Squares Optimization to get a proper weight matrix <strong>W</strong>. Additionally, to measure the accuracy of the model, test data is utilized in the last few lines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3af461c66caa7d0f96f2b15a07730d6e/href">https://medium.com/media/3af461c66caa7d0f96f2b15a07730d6e/href</a></iframe><p>4. Split MNIST data set into training and testing and let the RBFNN do its job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/187fe25f69094e1010325f58c023bf7b/href">https://medium.com/media/187fe25f69094e1010325f58c023bf7b/href</a></iframe><h3>Conclusion</h3><p>All in all, RBFNN is one of the powerful models for classification as well as regression tasks. RBF nets can learn to approximate the underlying patterns using many RBF curves. The practice of the statistical equation for the optimization process makes the algorithm more conducive and faster compared to <strong>MLP </strong>structured networks. But, fine-tuning hyperparameters such as <strong>K — </strong>number of clusters<strong> </strong>and <strong>Beta </strong>requires work, time and practice.</p><h3>Resources and References</h3><p>[1] <a href="https://medium.com/@tarlanahad/kickass-introduction-to-regressions-linear-regression-with-python-41d9ac86f267">T. Ahadli, Introduction to Regressions: Linear regression with Python (2018)</a></p><p>[2] <a href="https://medium.com/@tarlanahad/a-friendly-introduction-to-k-means-clustering-algorithm-b31ff7df7ef1">T. Ahadli, A Friendly Introduction to K-Means Clustering algorithm (2020)</a></p><p>[3] <a href="https://bitbucket.org/tarlanahad/myneatcodes/src/master/RBFNN/">T. Ahadli, C++/Python Codes for classification of MNIST Digits Data Set using RBFNN (2020)</a></p><p>[4] <a href="https://www.researchgate.net/publication/295256901_Multistep_Modeling_for_Approximation_and_Classification_by_Use_of_RBF_Network_Models">Prof. G. Vachkov, Multistep Modeling for Approximation and Classification by Use of RBF Network Models (2016), Innovative Issues in Intelligent Systems</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33c467803319" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/most-effective-way-to-implement-radial-basis-function-neural-network-for-classification-problem-33c467803319">Most Effective Way To Implement Radial Basis Function Neural Network for Classification Problem</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Friendly Introduction to K-Means clustering algorithm]]></title>
            <link>https://medium.com/@tarlanahad/a-friendly-introduction-to-k-means-clustering-algorithm-b31ff7df7ef1?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31ff7df7ef1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 15:42:49 GMT</pubDate>
            <atom:updated>2020-01-07T15:42:49.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXGsBrC9FnSHGJVw9lDhQA.png" /></figure><p>K-means clustering is one of the most common unsupervised learning algorithms in Data Science. The method follows straightforward rules to classify unlabeled datasets which will be discussed in the article.</p><p>Before jumping into the main topic, let’s imagine that there’s a town in which the company wants to sell its new T-shirts. However, producing them to fit each individual body size is ineffective and risky. The product should be marketized to meet the requirements of the majority so the likelihood of sales is satisfying.</p><p>This is where data scientists come to play. His role in the company will be to generalize and classify the body sizes into the predetermined number of classes. It’s worth noting that the character ‘K’ in the term ‘k-means’ represents this number.</p><p>As usual, the first part of the problem is to collect as much data as possible. For educational purposes, we can type up a code to generate an artificial data set. But the technique can easily be applied to any real-world datasets that are structured similarly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca0b98d628d6e38bde9aa5743de56c80/href">https://medium.com/media/ca0b98d628d6e38bde9aa5743de56c80/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDfBdQ8LTCZaIpaCIf6ehw.png" /></figure><p>The next step is to initialize ‘K’ number of randomly picked points on the plane. Then we will iterate on each collected data point and find the distance to initialized points. The data point will belong to the initialized point to which the distance is minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*OiB2cSYSO4W0LHR9_I-n7A.png" /></figure><p>Finally, we’ll find the mean of widths and heights respectively, and set it as a new coordinate for the above-initialized points which are also called <strong>centroids</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGWChiGula9HuwrqfJRQ_g.png" /></figure><p>This process will be repeated until the convergence is met which means there’s no change in the position of centroids. Thus, these centroids will represent the width and height of T-shirts that will be produced for the various class body sizes. That’s all!</p><h3>How to choose K?</h3><p>The main drawback of this technique is related to ambiguity about the K number of points that should be initialized. To overcome this issue, the performance of the algorithm is calculated for different numbers of centroids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*vi-h63ohyg-UV106rreu0w.png" /></figure><p>To apply the evaluation, once the convergence occurred, the distance between each cluster centroid and the data point is calculated. Then all the calculated distances summed as a measure of performance.</p><p>As the number of cluster centroids increases, the magnitude of the objective function will be less.</p><p>In the image below, the relationship between the ‘number of clusters K’ and the value of the objective function is depicted. To choose the optimal K, the <strong>elbow method</strong> is usually used. In the plot below, elbow-like shape happens when K equals 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CpyC6NlcydgiawHY.png" /></figure><h3>Putting theory into practice using python</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fdf7b76b80d0bb142a4134647030639/href">https://medium.com/media/6fdf7b76b80d0bb142a4134647030639/href</a></iframe><h3>Conclusion</h3><p>K-means is one of the most common and intuitive clustering algorithms in Machine Learning. The name ‘k-means’ almost explains the theory itself.</p><ol><li>‘K’ number of data points is initialized.</li></ol><p>2. The mean of the corresponding features of the nearest data points is calculated and set as a new coordinate of the pre-initialized centroids.</p><p>3. The process is repeated until there’s no change in the position of centroids.</p><p>If you have any questions about the discussed topic you can easily reach out to me on <a href="https://twitter.com/tarlanahad">Twitter</a>.</p><p><a href="https://github.com/tarlanahad/MyNeatCodes/tree/master/K-means">K-means clustering algorithm codes: Python, C++</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31ff7df7ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kickass Introduction to Regressions: Linear regression with Python]]></title>
            <link>https://medium.com/@tarlanahad/kickass-introduction-to-regressions-linear-regression-with-python-41d9ac86f267?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d9ac86f267</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 14:20:43 GMT</pubDate>
            <atom:updated>2020-01-08T18:21:32.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Regressions: Linear regression with Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0Y73Gqu8shJ-xwd0dLzog.jpeg" /><figcaption><a href="https://bit.ly/2AASDHL">https://bit.ly/2AASDHL</a></figcaption></figure><p>Linear regression is used to find linear relationship between <strong>target (Y) </strong>and <strong>predictor (X)</strong>. Before staring to explanation, the term “relationship” has to be clarified which can be either <strong>Deterministic</strong> or <strong>Statistical</strong>. In this tutorial deterministic<strong> </strong>relationship isn’t being handled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*0mF84kBsZTE5_5CkTfxORQ.png" /></figure><p>It can be easily seen that line perfectly fits to X, Y data points without any error. As the relationship between X and Y is functional so that if someone knows X (Celsius), Y (Fahrenheit) can be calculated by the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1Df-llejN0PHai9iyRNcPw.png" /></figure><p>For any deterministic relationship there is an equation which describes relationship without any error. However in this tutorial, statistical relationship will be discussed in which relationship is not perfect and estimation contains error.</p><h3>Statistical Relationship</h3><p>In the plot below the relationship between <em>death cases owing to skin cancer </em>and the <em>Latitude</em> is depicted. Number of death cases is considered in per 10 millions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*hy2kpU-2VcpQgAQkVhlWYA.png" /></figure><p>It is observed that there is a negative linear relationship between Latitude and the number of death cases which means if someone live higher Latitudes the probability of exposing to Skin cancer is less. To see this relationship the red line regressed on the scattered points which helps us to predict the number of mortality only using Latitude (X). The main objective here is to find best fitting <strong>m</strong> and <strong>b </strong>for the linear equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*1MPZ4hD_sDWNtPQyVg5Q8g.png" /></figure><h3>Algorithm by using python</h3><h4>Hyper parameters</h4><p>In Machine Learning <em>Hyper parameters</em> are the one of the most important phenomenon that controls global workflow of <em>Gradient descent</em> such as l<em>earning rate, number of iterations </em>and<em> initial values</em>. It is zero point where our process is initialized.</p><ul><li>learning_rate — How fast our model is learning</li><li>initial_b, initial_m — random starting points of gradient descent</li><li>num_iters — How many steps will be in gradient descent</li></ul><p>Don’t Worry Gradient descent will be discussed. :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04481cdc0f5e21bbca217ccbbd3475f/href">https://medium.com/media/c04481cdc0f5e21bbca217ccbbd3475f/href</a></iframe><h4>Loss function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*Iq23jd4MAYiRQ8ePmUhaZg.png" /></figure><p>Loss function is a tool that can be seen in all estimation tasks in ML. Simply, Loss function gives an information about how well our estimation is by giving average error rate in every single step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*hC2cIjYaizSNkodN5QmM3Q.png" /></figure><p>Generally, in this procedure all errors are summed for each corresponding Y and found mean of them. However, those who want to get more sophisticated knowledge about Loss functions, they can refer to this <a href="https://www.wikiwand.com/en/Loss_function">link</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d1e12f0f7a6cd1d36c2e3e473ea17f5/href">https://medium.com/media/5d1e12f0f7a6cd1d36c2e3e473ea17f5/href</a></iframe><h4>Gradient descent</h4><p>This part is the most crucial part in which our learning process occurs. To understand this, let’s suppose that we have an Error mountain and our objective is to make man descent as possible as we can. But problem is our man is blind. Now, Let’s think about how can we achieve this?</p><figure><img alt="Related image" src="https://cdn-images-1.medium.com/proxy/1*N5WjbzwsCFse-KPjBWZZ6g.jpeg" /></figure><p>To do this man have to know:<br>1. Number of Steps — Which is defined as Hyper parameter<br>2. Step size — If Step size is wrong he can overshoot the minimum point<br>3. Where to step — The path that leads to the minimum point of mountain</p><p>For the first process we have the function <strong>start_gradient_descent</strong> that determines the number of steps and modifying <strong>m </strong>and <strong>b</strong> before returning them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52e8fac0b6c42916f80e3416ef5cd0f1/href">https://medium.com/media/52e8fac0b6c42916f80e3416ef5cd0f1/href</a></iframe><p>For the second process we have Loss function which gives information about how far we are from the minimum point of the Error mountain. <br>Now let’s discuss the third process which shows our path in the gradient descent.</p><p><strong>step_gradient</strong> function uses <strong>partial derivative</strong> of Loss function to get the direction of minimum point. It is called “partial” as the process gives only direction about where our local minimum point is and then the man stepping to this direction. <br>To get more information about partial derivatives you can refer to this <a href="https://mathinsight.org/partial_derivative_introduction">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*xYUTPautq5ookduGAVYYiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*1819oImcNAd4V09cklhJTw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10a5d8ad5f246a47a24f1d95be785270/href">https://medium.com/media/10a5d8ad5f246a47a24f1d95be785270/href</a></iframe><h4>Sensitivity of Hyper parameters</h4><p>Now we are ready to perform Linear regression on the <a href="https://raw.githubusercontent.com/tarlanahad/Regressions-with-py/master/Linear-Regression/files/CtKeyKEP.csv">data</a> which was previously shown you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7QjJTHHvgOQB-KEkT6R9BQ.png" /></figure><p>It is observed that the regression line doesn’t fit the distributed points on the plot. As you remember previously the term “hyper parameters” was cited and noted that it is one of the most essential part of the gradient descent that determines workflow. Now let’s increase the <em>number of iterations</em> and <em>learning_rate</em> respectively from `1000` to `1000000` and from `0.00001` to `0.0001`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hlguWrq_9eidYGZrSsCQXQ.png" /></figure><p>It is seen from the plot that we got more precisely fitting line which is related to hyper parameters. There’re four methods to find best hyper parameters:</p><ol><li><em>Manual Search:</em> Using knowledge you have about the problem guess parameters and observe the result. Based on that result tweak the parameters. Repeat this process until you find parameters that work well or you run out of time.</li><li><em>Grid Search:</em> Using knowledge you have about the problem identify ranges for the hyper parameters. Then select several points from those ranges, usually uniformly distributed. Train your network using every combination of parameters and select the combination that performs best. Alternatively you can repeat your search on a more narrow domain centered around the parameters that perform the best.</li><li><em>Random Search:</em> Like grid search you use knowledge of the problem to identify ranges for the hyper parameters. However instead of picking values from those ranges in a methodical manner you instead select them at random. Repeat this process until you find parameters that work well or use what you learn to narrow your search. In the paper <a href="http://jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf">Random Search for Hyper-Parameter Optimization</a> Dr. Bengio proposes this be the baseline method against which all other methods should be compared and shows that it tends to work better than the other methods.</li><li><em>Bayesian Optimization:</em> More recent work has been focus on improving upon these other approaches by using the information gained from any given experiment to decide how to adjust the hyper parameters for the next experiment. An example of this work would be <a href="http://dash.harvard.edu/handle/1/11708816">Practical Bayesian Optimization of Machine Learning Algorithms</a> by Adams et al.</li></ol><h3>Resources and References:</h3><p>Although there is a myriad of resources to more dig into the topic, I’ll provide best of them in the links below.</p><ol><li><a href="https://www.youtube.com/watch?v=uwwWVAgJBcM&amp;t=2424s">Siraj Raval — Linear Regression Machine Learning</a></li><li><a href="https://stats.stackexchange.com/questions/95495/guideline-to-select-the-hyperparameters-in-deep-learning">Guideline to select the hyper parameters in Deep Learning</a></li><li><a href="https://www.cs.toronto.edu/~frossard/post/linear_regression/">Linear Regression with NumPy</a></li><li><a href="https://www.youtube.com/watch?v=IHZwWFHWa-w&amp;t=1s">3Blue1Brow — Gradient descent, how neural networks learn | Deep learning, chapter 2</a></li></ol><p>To obtain complete code you can view the <a href="https://github.com/tarlanahad/Regressions-with-py/tree/master/Linear-Regression">github repo</a>. If you have any question, please don’t hesitate to write it in the response section or my <a href="http://tarlanahad@gmail.com/">email</a>.</p><p>If you loved the article, don’t forget to clap :)</p><figure><img alt="Image result for claps in medium" src="https://cdn-images-1.medium.com/proxy/1*6p88Qr70JrweEN90m4U-vg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d9ac86f267" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Is Sin(x) Calculated By Computers?]]></title>
            <link>https://medium.com/kodera/how-is-sin-x-calculated-by-computers-8d386a54cefc?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d386a54cefc</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Sat, 03 Mar 2018 04:05:03 GMT</pubDate>
            <atom:updated>2018-03-03T04:05:03.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PVunTMyRL3F81aoo." /><figcaption>Photo by <a href="https://unsplash.com/@benwhitephotography?utm_source=medium&amp;utm_medium=referral">Ben White</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Computers are incredibly fast, accurate and stupid. Human beings are incredibly slow, inaccurate and brilliant. Together they are powerful beyond imagination. — Albert Einstein, physicist and humanitarian (1879–1955)</blockquote><h3>Introduction</h3><p>One of the most remarkable features of computers is their inevitable speed which allows us to compute most of the arithmetical operations just in milliseconds. Let’s have a look some straightforward examples that can be solved analytically by computers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*kfYOEOtfOlwnVBFOr2ZsRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*99Pl3mc6ROE4QmGRwEKmoA.png" /></figure><p>As you can see from a quadratic equation above, we can easily solve the problem only by using simple operations. If you don’t know the method of solving quadratic equations, you can learn it from <a href="https://www.wikiwand.com/en/Quadratic_equation">Wikipedia</a>.</p><p>Okay, but what about if we tried to find the the roots of <strong>x⁹+2x²+5 </strong>or<strong> Sin(x) </strong>which can’t be solved in an analytical way? The answer is <strong>Taylor’s Theorem</strong>.</p><h3>Old but Gold: Taylor’s Theorem</h3><p>In <a href="https://www.wikiwand.com/en/Mathematics">mathematics</a>, a <strong>Taylor series</strong> is a representation of a <a href="https://www.wikiwand.com/en/Function_(mathematics)">function</a> as an <a href="https://www.wikiwand.com/en/Series_(mathematics)">infinite sum</a> of terms that are calculated from the values of the function’s <a href="https://www.wikiwand.com/en/Derivative">derivatives</a> at a single point. — <a href="https://www.wikiwand.com/en/Taylor_series">Wikipedia</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*KUhJRygjJToqgK4fy2lZ_A.jpeg" /><figcaption>Brook Taylor (1685–1731)</figcaption></figure><p>Taylor theorem is such a magical tool that helps computers to convert non-analytical equations to a programmable form. The definition below is an expansion of Taylor series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRsWN4Z30NaUmDUbXBNIaQ.png" /></figure><p>in a compact way usually it is written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*HhRj4hIQ71-leEUhOuUbAg.png" /></figure><ul><li><em>n ! — factorial of </em><strong><em>n</em></strong></li><li><em>f⁽ ⁿ⁾(a) — nᵗʰ derivative of </em><strong><em>f(x)</em></strong><em> at the point </em><strong><em>a</em></strong></li><li><em>When </em><strong><em>a = 0</em></strong><em>, it becomes a special form of Taylor’s series which is called </em><a href="https://www.wikiwand.com/en/Colin_Maclaurin#Contributions_to_mathematics">Maclaurin series</a>.</li></ul><h3>Maclaurin series: Finding Sin(x)</h3><p>In order to find Sin(x), we’ll use a special form of Taylor series, namely, Maclaurin series in which method we just assume <strong>a </strong>is zero (a=0). Let’s analyze the solving method Sin(x) with Maclaurin series :</p><p>First of all, in order to implement Maclaurin series and to find the power series expansion of sin(x), we have to compute the derivatives of sin(x):</p><ol><li>Sin(x)` = Cos(x)</li><li>Sin(x)`` = -Sin(x)</li><li>Sin(x)``` = -Cos(x)</li><li>Sin(x)```` = Sin(x)</li></ol><p>In the next step, <strong>x</strong> is replaced by <strong>a</strong>, which is 0 in our case, and tried to find correlation between position and items of series.</p><ol><li>Sin(0) = 0</li><li>Sin(0)` = Cos(0) = 1</li><li>Sin(0)`` = -Sin(0) = 0</li><li>Sin(0)``` = -Cos(0) = -1</li><li>Sin(0)```` = Sin(0) = 0</li></ol><p>It is clear that the pattern repeatedly continues and gives a hint about the definition below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRsWN4Z30NaUmDUbXBNIaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTqHW9lSUOfPibX_gRcwxA.png" /></figure><h3>Coding 😍</h3><p>Personally, I would recommend you to rewrite the expansion of Taylor series in a compact way in order to see the sequence clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*DG6fmdKvbtATwi5A1hEj4A.png" /></figure><p>From the definition above, you can easily convert and implement the code to your own used programming language. For the test purpose we’ll use Sin(<em>π/2) </em>which is equal to 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6733c80d030e2a1f72099ac1c7d033ad/href">https://medium.com/media/6733c80d030e2a1f72099ac1c7d033ad/href</a></iframe><p>We get <em>0.9999436490076448 </em>for the value of Sin(<em>π/2) </em>which is extremely close to 1. If I had increased the value of accuracy in the code above, I would have get more precise answer and when accuracy is approaching to infinity, the answer will be exactly 1.</p><h3>Conclusion</h3><p>As it is understood, we can’t get equally exact answer and obtain an approximation of the solution for the equations that can’t be solved analytically . If you still think that this article is not enough for you, please visit the links below which will help you to understand concept entirely.</p><ol><li><a href="http://tutorial.math.lamar.edu/Classes/CalcII/TaylorSeries.aspx"><strong>Calculus II — Taylor Series — Pauls Online Math Notes — Lamar University</strong></a></li><li><a href="https://www.khanacademy.org/math/calculus-home/series-calc/maclaurin-taylor-calc/v/sine-taylor-series-at-0-maclaurin"><strong>Maclaurin series of sin(x) (video) | Series | Khan Academy</strong></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d386a54cefc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kodera/how-is-sin-x-calculated-by-computers-8d386a54cefc">How Is Sin(x) Calculated By Computers?</a> was originally published in <a href="https://medium.com/kodera">Kodera</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Radix Sort — Sorting without comparison]]></title>
            <link>https://medium.com/@tarlanahad/radix-sort-sorting-without-comparison-d204aaba5ed7?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d204aaba5ed7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[radix-sort]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Wed, 14 Feb 2018 12:30:42 GMT</pubDate>
            <atom:updated>2018-02-14T12:30:42.586Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>non-comparative sorting algorithm (the key are not compared)</li><li>sorts the keys by sorting individual digits which share the same position</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycezcvh8ySnjdiQ6kruwwQ.jpeg" /></figure><h3>Table of contents</h3><ul><li>Introduction</li><li>Imagine the code</li><li>Algorithm</li><li>Java</li><li>Conslusion</li><li>Resources and References</li></ul><h4>Introduction</h4><p>Before starting the topic, I would like to give some information about Radix sort. <em>Radix</em> is a Latin word which means“root”. <em>Root</em> can be considered as a synonym for <em>base. </em>This sort technique is not only fast but also old and well-known in Computer Science. The image below is a clear proof in which an <a href="https://www.wikiwand.com/en/IBM_card_sorter">IBM card sorter</a> is performing a radix sort on a large set of <a href="https://www.wikiwand.com/en/Punched_cards">punched cards</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4Ydm3Dx40d0CgxWYb_7ufQ.jpeg" /></figure><h4>Imagine the process</h4><p>Radix sort is working with the unique keys of each node. For example, when you send an email, it is mechanically sorted by zip code of the area and then sent to the proper area. In this article we will work with Integer, however, after understanding the algorithm, you can learn how to sort String by means of radix sort as well.</p><p>Let’s consider that we have an array of integers.</p><pre><br>int arr[] = {329,457,657,839,436,720,355};</pre><p>Now we’ll sort the numbers based on the digits starting from the last one.The numbers in the leftmost column is input. The remaining columns illustrate how radix sort works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6zRY-djlPNRFD6azYF0k8g.jpeg" /></figure><p>As can be seen in the image,firstly, radix sort begins from least to most and as a result we get a beautifully sorted array.</p><pre>329,355,436,457,657,720,839</pre><p>After visualization of this sort technique you will easily understand the concept, so let’s try to learn algorithm before writing in Java.</p><h4>Algorithm</h4><ol><li>Find the max number</li><li>Find the count of each digit for the given position</li><li>Find the range of number with the same digit according to position</li><li>Copy ranged numbers to temporary array</li><li>Copy temp array’s items to the input array</li></ol><h4><em>Java</em></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ada11bcd48e643e673845edd6e3f794c/href">https://medium.com/media/ada11bcd48e643e673845edd6e3f794c/href</a></iframe><h4>Conlusion</h4><p>Complexity of the search is just based on the length of the numbers so in practice it is not efficient way of sorting items. Because during the radix sort we copy from array to another one, and then copy temp array to the input array. That’s why it is not considered as an effective way of sorting. However, still mails are sorted by means of this sort technique.</p><h3>Resources and References</h3><ul><li><a href="http://is.ptithcm.edu.vn/~tdhuy/Programming/Introduction.to.Algorithms.pdf">MIT Press — Introduction to algorithms, Chapter 8.3 (page 170)</a></li><li><a href="https://www.youtube.com/watch?v=Nz1KZXbghj8&amp;list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb&amp;index=7">MIT — Introduction to Algorithms, Lecture </a>7</li><li><a href="https://courses.csail.mit.edu/6.006/fall11/lectures/lecture7.pdf">MIT — Lecture 7,lecture notes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d204aaba5ed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AVL Trees — Get rid of linked lists in the BSTs]]></title>
            <link>https://medium.com/@tarlanahad/avl-trees-get-rid-of-linked-lists-in-the-bsts-ca41b81690ca?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca41b81690ca</guid>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[avl-tree]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Sat, 10 Feb 2018 20:42:02 GMT</pubDate>
            <atom:updated>2018-02-10T20:42:02.600Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read the article that have been posted before this, you may experience some difficulties. That’s why I would recommend you to read them before starting to this article 😊. I’ll list them below…</p><ul><li><a href="https://medium.com/@tarlanahad/super-arrays-linked-lists-c0b6af1f3349">Super Arrays — Linked Lists 💪</a></li><li><a href="https://medium.com/@tarlanahad/binary-trees-and-bsts-oxygen-source-of-data-structures-a6eb0f8e629b">Binary Trees and BSTs — An Oxygen source of the Data Structures</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3tIKsDxWY-TgpecPItTUg.png" /></figure><h3>Table of contents</h3><ul><li>Introduction</li><li>Rotations</li><li>Adding a node</li><li>Rebalancing</li><li>Rotations</li></ul><h3>Introduction</h3><p>Last time, we talked about <a href="https://medium.com/@tarlanahad/binary-trees-and-bsts-oxygen-source-of-data-structures-a6eb0f8e629b"><em>Binary Search Trees</em></a><em> </em>as well as their advantages and disadvantages. As I mentioned before, the problem is that the tree structure changes along with its time complexity of search process and creates <strong>imbalance</strong> between children when adding nodes to the tree. Let’s try to understand what does imbalance actually mean?</p><blockquote>In the AVL trees difference between the heights of the child nodes always have to be equal or less than one otherwise the situation is called violation of AVL tree and have to be solved.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0cjxcvMdrBxohPHn89SOQ.png" /></figure><p>As can be seen from the image, the problem is caused by the node 8, and to fix the issue we’ll rotate its grandparent (4). We also should know that if the problem is in the <em>right child’s right subtree</em>, we’ll do<em> left rotation</em>, else if the problem is in the <em>left child’s left subtree, </em>we’ll do <em>right rotation</em>.Let’s try to understand what does rotation mean?</p><h3>Rotations</h3><p><strong>Left Rotation </strong>— We’ll left rotate problem causing node’s grandparent around its parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bG0M34lgGEe1FFzfJTTQPw.png" /></figure><p><strong>Right Rotation </strong>— We’ll right rotate problem causing node’s grandparent around its parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1D6ZpE1-O4zjUFKyHA1vfw.png" /></figure><p>Apart from the situations that cited above there can be more tricky problems that require more effort to address. If the node that causes the violation of AVL tree is in the <em>left child’s right subtree </em>or<em> right child’s left subtree</em>, we have to implement <em>combination of two rotations</em>.</p><ul><li>If the problematic node is in the left child’s right subtree, we’ll do left rotation of parent and right rotation of grandparent node respectively.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nC1thfRAL99fZ1vVopi9jA.jpeg" /></figure><p>After doing these procedures, we see that there appears violation in the root node which is the grandparent of the node that causes the problem (10). Now we see that the problematic node is in the right child’s right subtree which means that we’ll implement left rotation of its grandparent(4) and get beautifully balanced tree again ❤.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGY0ydjFhMmR8abvqxmdFw.png" /></figure><h3>Adding a node</h3><p>We’ll use Node as an inner class with three pointers,namely, Left, Right and Parent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57b2421419e49e204eb57cf134a560b5/href">https://medium.com/media/57b2421419e49e204eb57cf134a560b5/href</a></iframe><p>In the AVL_Tree class, we’ll have <em>Root</em> which is entry to the tree and CurrentSize which is the number of nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9985fdf6c62904fe52b1f110f09cf41c/href">https://medium.com/media/9985fdf6c62904fe52b1f110f09cf41c/href</a></iframe><p>Pseudo code</p><ol><li>Create a node with the given Key</li><li>Check if we have an empty tree</li><li>If the tree is empty, set new Node to the Root</li><li>else call addHelper method</li></ol><p>Java code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4759440b1e7f1f289e01506d4c170af9/href">https://medium.com/media/4759440b1e7f1f289e01506d4c170af9/href</a></iframe><p><strong><em>addHelper()</em></strong> method is a recursive method that will start from the root and go down until reaching the leaves and then append the new Node to the valid location. Subsequently<strong><em>, CheckBalance()</em></strong> method will be called thanks to which balance between the children will be checked.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c357eac62e71a8cf7556b19b31f3810/href">https://medium.com/media/1c357eac62e71a8cf7556b19b31f3810/href</a></iframe><h3>Rebalancing</h3><p><strong><em>CheckBalance()</em></strong> is a recursive method which will begin from the new added Node ,which is leaf, go up until the root and check balance between every parent’s children. If the difference in the heights of them is more than one, <strong><em>ReBalance()</em></strong> method will be called in order to address the issue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e78f4f3582494dfadf1c8fc6074db7d/href">https://medium.com/media/2e78f4f3582494dfadf1c8fc6074db7d/href</a></iframe><p><strong><em>ReBalance() </em></strong>method will detect where is the problem occurred and take a convenient action such as leftRotation, rightRotation and so on…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f65a1d6752f3fbaea2020632fad01892/href">https://medium.com/media/f65a1d6752f3fbaea2020632fad01892/href</a></iframe><h3>Rotations</h3><p>Let’s try to understand rotations more deeply. First of all, we should know that when doing rotations, we are searching for median value and putting it in the middle of child and grandparent.</p><h4>Left Rotation</h4><p>Pseudo code:</p><ol><li>set temp = grandparent’s right child</li><li>set grandparent’s right child = temp left child</li><li>set temp left child = grandparent</li><li>use temp instead of grandparent</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qOAhOFGA6AYMB0L-65TIg.png" /></figure><p>Java code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f84fa8b4e2dab6210694e79ef4ae2b0/href">https://medium.com/media/2f84fa8b4e2dab6210694e79ef4ae2b0/href</a></iframe><h4>Right Rotation</h4><p>Pseudo code</p><ol><li>set temp = grandparent’s left child</li><li>set grandparent’s left child = temp right child</li><li>set temp right child = grandparent</li><li>use temp instead of grandparent</li></ol><p>Java code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cc0253d6756f606c1adb19a8afe5eb0/href">https://medium.com/media/8cc0253d6756f606c1adb19a8afe5eb0/href</a></iframe><h4>LeftRight and RightLeft Rotations</h4><p>Pseudo codes have been provided separately above, that’s why only Java codes have been written here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fafcd542290f1b8877473c5ba7e6553/href">https://medium.com/media/9fafcd542290f1b8877473c5ba7e6553/href</a></iframe><p>If you experienced difficulties during reading, as I recommended at the beginning, please read the articles that have been posted before and don’t hesitate to write your question below ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca41b81690ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Trees and BSTs —An Oxygen source of the Data Structures]]></title>
            <link>https://medium.com/@tarlanahad/binary-trees-and-bsts-oxygen-source-of-data-structures-a6eb0f8e629b?source=rss-49d8eab979a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6eb0f8e629b</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Tarlan Ahadli]]></dc:creator>
            <pubDate>Thu, 08 Feb 2018 14:16:20 GMT</pubDate>
            <atom:updated>2018-02-09T08:02:23.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8g-hWtLFc5smf3Cyzd0TxQ.png" /></figure><h3>Introduction</h3><p><em>Now we’ll learn a new data structure in which each node has more than one </em><strong><em>self-reference, </em></strong>namely, left reference, right reference, and data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbWdRZS04dgS2C54RhwW5g.jpeg" /></figure><h3>Terminology</h3><ul><li><strong>Root </strong>— <em>The topmost node in the tree.</em></li><li><strong>Parent </strong>— <em>The node which is connected with other node(s) and one level on the top.</em></li><li><strong>Children — </strong><em>The nodes which are linked with Parent and one level bottom.</em></li><li><strong>Leaves </strong>or <strong>External nodes</strong>— <em>The nodes which have no children.</em></li><li><strong>Internal nodes</strong> — <em>Nodes except Leaves.</em></li><li><strong>Siblings </strong>— <em>Nodes which have the same parent.</em></li><li><strong>Depth of the node </strong>— <em>Number of the edges from root to the node.</em></li><li><strong>Height of the node </strong>—<em> Number of the edges from node to the deepest node.</em></li><li><strong>Height of the tree </strong>—<em> Height of the Root node.</em></li><li><strong>A full binary tree</strong> — <em>In which every node has exactly zero or two children.</em></li><li><strong>A complete binary tree</strong> — <em>In which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.</em></li><li><strong><em>Successor of the node</em></strong><em> — The node with the next greater Key in the tree</em></li><li><strong><em>Predecessor of the node</em></strong><em> — The node with the next smaller Key in the tree</em></li></ul><p><em>The complete binary trees are very awesome tree type which has the best ratio between the number of nodes and its height. We can proof it by realizing that there are a maximum number of nodes on the each level.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*NDNK3hxsFKXvLSFCNoFvNA.png" /></figure><p>Solving the equation above we obtain another one, which also gives the time complexity of searching process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*5pe5uzW0TLL2uHVPZWgoYA.png" /></figure><h3>Advantages of Trees</h3><p>Because of their usefulness and serious advantages, trees are one of the most frequently used Data Structures. Because:</p><ul><li><em>Trees ease Insertion and Deletion processes.</em></li><li><em>We can easily move datum in form subtrees</em></li></ul><h3>Binary Search Trees</h3><p>Binary Search Tree is a special type of Tree which helps us to Sort, Search and Retrieving data in only a little time complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWY3PrLUHyCynlUmBaTkuQ.jpeg" /></figure><h4>Nodes’ order regulations</h4><ul><li>Each node has its own Key value which is also known <em>data</em>.</li><li>Parent node’s key has to be <em>greater</em> than that of its <em>left</em> child. P&gt;L</li><li>Parent node’s key has to be <em>smaller</em> than of its <em>right</em> child. P&lt;R</li><li>Duplicate keys <em>cannot</em> be in the same tree.</li></ul><h4>The node</h4><p>In Java Node class will be <em>Inner</em> and <em>Private</em>.</p><pre><strong>public class </strong>BinarySearchTree {<br><br>    <strong>private </strong>Node <strong>Root</strong>;</pre><pre><strong>   public </strong>BinarySearchTree() {<br><br>   }</pre><pre>    <strong><em>private class </em></strong><em>Node {<br><br>        Node </em><strong><em>Left</em></strong><em>;<br>        Node </em><strong><em>Right</em></strong><em>;<br>        Node </em><strong><em>Parent</em></strong><em>;<br>        </em><strong><em>int Key</em></strong><em>;<br><br>        </em><strong><em>public </em></strong><em>Node(</em><strong><em>int </em></strong><em>Key) {<br>            </em><strong><em>this</em></strong><em>.</em><strong><em>Key </em></strong><em>= Key;<br><br>        }<br>    }</em><br>    ...<br>}</pre><h3>Insertion</h3><p><em>Insertion</em> and <em>Searching</em> are quite similar procedures. We just go down from the root until getting a specific location and insert a new Node into the BST. If the node that we want to insert has a duplicate in the tree, we are done. The new node will always replace <em>null</em> reference of Parent node (<em>will be leaf</em>).</p><p><strong><em>Pseudo code</em></strong><em><br>1.Start at root go until the leaves<br>2.If new Node’s Key is Greater than Current Node’s key go Right<br>3.Else go left<br>4.If there is no node in the tree create a root<br>5.Else if new Node’s key is less than Parent Node’s Key,New Node will be left child of its Parent<br>6.Else Parent Node’s right Child will be New Node</em></p><pre><strong>public void </strong>insert(<strong>int </strong>Key) {<br><br>    Node newNode = <strong>new </strong>Node(Key);<em>//Create new Node</em><br><br>    Node current = <strong>Root</strong>;<em>//Start from root</em><br><br>    Node parent = <strong>null</strong>;<em>//Current Parent Node</em><br><br>    <strong>while </strong>(current != <strong>null</strong>) {<em>//Go until leaves</em><br><br>        parent = current;<br><br>        <strong>if </strong>(Key &lt; parent.<strong>Key</strong>)//Go Left<br>            current = current.<strong>Left</strong>;<br>        <strong>else <em> </em></strong><em>//Go right</em><strong><br>            </strong>current = current.<strong>Right</strong>;<br><br>    }<br><br>    newNode.<strong>Parent </strong>= parent;<br><br>    <strong>if </strong>(parent == <strong>null</strong>) <strong>Root </strong>= newNode; //Create Tree<br><br>    <strong>else if </strong>(Key &lt; parent.<strong>Key</strong>) parent.<strong>Left </strong>= newNode;//Insert To                                                           Left<br><br>    <strong>else </strong>parent.<strong>Right </strong>= newNode;//Insert to right<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*voBM5qGBKV02xJ0EQ46ORg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkesbjhBWZQ-ReGr4XPKyw.jpeg" /></figure><p><em>But there is a very serious problem that if we try to insert 7, the tree structure will destroy and will be linear [3,4,5,7] which will change Search operation’s Time Complexity from O(log n) to O(n). However, it can be addressed by means of </em><strong><em>AVL</em></strong><em> </em><strong><em>trees</em></strong><em> which will be written in the Next Article… </em>😄</p><h3>Searching</h3><p>As it is mentioned above search is quite similar to Insertion.</p><p><strong><em>Pseudo code</em></strong><em><br>1.Start from root go down until finding the element or leaves<br>2.If current node’s Key equals to the desired Key, return its index, else continue to search<br>3.If new node’s Key is greater than current node’s key, go Right<br>4.Else go left<br>5.If key couldn’t be found return -1</em></p><pre><strong>public int </strong>search(<strong>int </strong>key) {<br><br>    Node currentNode = <strong>Root</strong>;<br><br>    <strong>int </strong>index = 0;<br>    <br>    <strong>while </strong>(currentNode != <strong>null</strong>) {<br><br>        <strong>if </strong>(currentNode.<strong>Key </strong>== key) <strong>return </strong>index;<br><br>        index++;<br><br>        <strong>if </strong>(key &lt; currentNode.<strong>Key</strong>) {<br>            currentNode = currentNode.<strong>Left</strong>;<br>        } <strong>else </strong>{<br>            currentNode = currentNode.<strong>Right</strong>;<br>        }<br><br>    }<br>    <strong>return </strong>-1;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Rllb7E5ijNHiBgj4bRlhZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xP3GnQssdFyxJvG_tCnKfw.gif" /><figcaption><a href="http://108.61.119.12/wp-content/uploads/2014/10/binary-tree-1-search.gif">http://108.61.119.12/wp-content/uploads/2014/10/binary-tree-1-search.gif</a></figcaption></figure><p>As can be seen from the GIF tree structure is extremely powerful for searching and inserting procedures because each time when we go Right or Left, <strong>2⁽ʰ⁺¹⁾-1</strong> nodes are being eliminated (<em>in an Complete Tree</em>).</p><h3>Deletion</h3><p>Deletion is somehow more complex and tricky process than searching and insertion. Because there are several cases that have to be considered when deleting a Node.</p><ol><li>There is no such Node</li><li>Node is a leaf</li><li>Node has only one child</li><li>Node has two children</li><li>If there is <strong>no node</strong> to delete, nothing should be done.</li><li>If the Node is Leaf, only the leaf will be replaced with <strong><em>null</em></strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*T9GlmFEv3n2r9WIG_n6sqw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgS-MBtV1D3L0_DV4s8BSg.png" /></figure><p>3. If there is only <strong>one child</strong>, the process is very similar to deleting node from the <a href="https://medium.com/@tarlanahad/super-arrays-linked-lists-c0b6af1f3349"><strong><em>Linked List</em></strong></a>. We just bypass the node that has to be deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*lwyH-IQLotmzBzEygCS7tQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3etzR9ZIkqnjcxc1DaLCA.png" /></figure><p>4.When there are two children in the node, it will be less straightforward.We’ll find inorder successor of the node and then copy contents of the inorder successor to the node and delete the inorder successor.<br>PS: Inorder predecessor can also be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*AAuMBPh8F0OKUNB1NkGyzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf-rd8qI0HAuiO0eBiRfxA.jpeg" /></figure><pre><strong>public void </strong>delete(<strong>int </strong>Key) {<br>    <strong>Root </strong>= deleteHelper(<strong>Root</strong>, Key);<br>}<br><br><em>/* A recursive function to insert a new Key in BST */<br></em><strong>private </strong>Node deleteHelper(Node Root, <strong>int </strong>Key) {<br>    <em>/* Base Case: If the tree is empty */<br>    </em><strong>if </strong>(Root == <strong>null</strong>) <strong>return </strong>Root;<br><br>    <em>/* Otherwise, recur down the tree */<br>    </em><strong>if </strong>(Key &lt; Root.<strong>Key</strong>)<br>        Root.<strong>Left </strong>= deleteHelper(Root.<strong>Left</strong>, Key);<br>    <strong>else if </strong>(Key &gt; Root.<strong>Key</strong>)<br>        Root.<strong>Right </strong>= deleteHelper(Root.<strong>Right</strong>, Key);<br><br>        <em>// if Key is same as Root&#39;s Key, then This is the node<br>        // to be deleted<br>    </em><strong>else </strong>{<br>        <em>// node with only one child or no child<br>        </em><strong>if </strong>(Root.<strong>Left </strong>== <strong>null</strong>)<br>            <strong>return </strong>Root.<strong>Right</strong>;<br>        <strong>else if </strong>(Root.<strong>Right </strong>== <strong>null</strong>)<br>            <strong>return </strong>Root.<strong>Left</strong>;<br><br>        <em>// node with two children: Get the inorder successor (smallest<br>        // in the Right subtree)<br>        </em>Root.<strong>Key </strong>= minValue(Root.<strong>Right</strong>);<br><br>        <em>// Delete the inorder successor<br>        </em>Root.<strong>Right </strong>= deleteHelper(Root.<strong>Right</strong>, Root.<strong>Key</strong>);<br>    }<br><br>    <strong>return </strong>Root;<br>}<br><br><strong>private int </strong>minValue(Node Root) {<br>    <strong>int </strong>minv = Root.<strong>Key</strong>;<br>    <strong>while </strong>(Root.<strong>Left </strong>!= <strong>null</strong>) {<br>        minv = Root.<strong>Left</strong>.<strong>Key</strong>;<br>        Root = Root.<strong>Left</strong>;<br>    }<br>    <strong>return </strong>minv;<br>}</pre><p>After understanding this concept you can implement other methods such as Print, Size and so on yourself.</p><h3>References and Resources</h3><p>For this rich article I could write a few resources and references. However, I want to recommend only remarkable ones which would help you understand the concept entirely.</p><ul><li><a href="http://is.ptithcm.edu.vn/~tdhuy/Programming/Introduction.to.Algorithms.pdf">MIT Press — Introduction to algorithms, Chapter 10.4 (page 214)</a></li><li><a href="https://www.youtube.com/watch?v=9Jry5-82I68&amp;t=5s">MIT — Introduction to Algorithms, Lecture 5</a></li><li><a href="https://courses.csail.mit.edu/6.006/fall11/lectures/lecture5.pdf">MIT — Lecture 5,lecture notes</a></li><li><a href="https://www.youtube.com/watch?v=Lta807sEOQY&amp;list=PLpPXw4zFa0uKKhaSz87IowJnOTzh9tiBk&amp;index=49">Dr. Rob Edwards from San Diego State University — Trees</a></li></ul><p><em>Thanks for reading </em>😊<em> . If you have any question, please, don’t hesitate and write…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6eb0f8e629b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>