<?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 Zijing Gao on Medium]]></title>
        <description><![CDATA[Stories by Zijing Gao on Medium]]></description>
        <link>https://medium.com/@zg104?source=rss-af85ebf340de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g0X5kqjsrKrPP9KPG1e2nw.jpeg</url>
            <title>Stories by Zijing Gao on Medium</title>
            <link>https://medium.com/@zg104?source=rss-af85ebf340de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:27:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zg104/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[Everything You Need to Know about Naïve Bayes]]></title>
            <link>https://medium.com/analytics-vidhya/everything-you-need-to-know-about-na%C3%AFve-bayes-9a97cff1cba3?source=rss-af85ebf340de------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a97cff1cba3</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zijing Gao]]></dc:creator>
            <pubDate>Sat, 19 Sep 2020 00:42:39 GMT</pubDate>
            <atom:updated>2020-09-22T13:53:46.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>Clearly Explained in 30 Minutes</h4><h3>Content</h3><ul><li>Discriminative Model &amp; Generative Model</li><li>Main Idea (1): Bayesian Rule</li><li>Main Idea (2): Conditional independence hypothesis</li><li>Main Idea (3): Construct a classifier from a probability model</li><li>Gaussian Naive Bayes (GNB)</li><li>Naive Bayes in Python &amp; R</li><li>Interview Questions &amp; Other Materials</li><li>Summary</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-zCXMt-dNutfaNwk.png" /><figcaption>Photo by <a href="https://www.flickr.com/photos/mattbuck007/3676624894">Matt Buck</a></figcaption></figure><h3>Discriminative Model &amp; Generative Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*84x5v3YkYPhhZZAp" /></figure><h4>Discriminative Model</h4><p>As is known to us all that machine learning is exactly the technique that predict the target y using features <em>X</em> , which means to compute the conditional probability <em>p</em>(<em>y</em>∣<em>X</em>).</p><p>Then for the discriminative model, we only consider estimating the conditional probability, which is to establish the discriminant function under the condition of a limited sample, without considering the generative model of the sample, directly studying the prediction model, which can also be understood as in the binary classification problem that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*d4eXa0zWpLa-b3ob8LdoMQ.png" /></figure><h4>Generative Model</h4><p>The generative model obtains p(y,X), we need to find the joint distribution probability between X and the target y, and then the big win is to find two joint probability distributions. Take the larger one.</p><h3>What is Naive Bayes?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*A48winOith686bMA.gif" /></figure><p>First of all, Naive Bayes is a generative model. The Naive Bayes classifier is a series of simple probabilistic classifiers based on the use of Bayes’ theorem under the assumption of strong independence between features.</p><p>Naive Bayes has been extensively studied since the 1950s. In the early 1960s, it was introduced into the text information retrieval field under another name. It is still a popular (benchmark) method of text classification. Text classification uses word frequency as a feature to determine the category or Other (such as spam, legality, sports or politics, etc.) issues. With proper preprocessing, it can compete with more advanced methods in this field (including support vector machines). It is also used in automatic medical diagnosis.</p><p>Naive Bayes is a simple way to build a classifier. The classifier model assigns class labels represented by feature values ​​to problem instances, and class labels are taken from a limited set. It is not a single algorithm for training such a classifier, but a series of algorithms based on the same principle: all naive Bayes classifiers assume that each feature of the sample is not related to other features. For example, if a fruit is red, round, and about 3 inches in diameter, the fruit can be judged to be an apple. Although these features are mutually dependent or some features are determined by other features, the Naive Bayes classifier considers these attributes to be independent in the probability distribution of determining whether the fruit is an apple.</p><p>For certain types of probability models, very good classification results can be obtained in the sample set of supervised learning. In many practical applications, Naive Bayesian model parameter estimation uses the maximum likelihood estimation method; in other words, the Naive Bayesian model can also work without Bayesian probability or any Bayesian model.</p><p>Despite these naive ideas and over-simplified assumptions, the naive Bayes classifier can still achieve quite good results in many complex real-world situations. In 2004, an article analyzing the problem of Bayesian classifier revealed several theoretical reasons why the naive Bayesian classifier obtains the seemingly incredible classification effect. Nevertheless, an article in 2006 compared various classification methods in detail, and found that the newer methods (such as decision trees and random forests) performed better than Bayesian classifiers.</p><p>One advantage of the naive Bayes classifier is that it only needs to estimate the necessary parameters (the mean and variance of the variables) based on a small amount of training data. Due to the assumption of variable independence, only the method of estimating each variable is needed, without the need to determine the entire covariance matrix.</p><p>Theoretically, the probability model classifier is a conditional probability model, which is no stranger to us, that is to say: Independent categorical variables have several categories, and the conditions depend on several feature variables, but the problem is that if the number of features is large or the value of each feature is large, the probabilities listed based on the probability model need to be modified to become feasible:</p><h3>Main Idea (1): Bayesian Rule</h3><p>Theoretically, the probability model classifier is a conditional probability model. We are no longer unfamiliar with this, which is to ask for</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*zlPQ9G4ndRFfE2kTXpIGuw.png" /></figure><p>The independent categorical variable y has several categories, and the conditions depend on several characteristic variables. But the problem is that if the number of features n is large or the value of each feature is large, the probabilities listed based on the probability model need to be modified to become feasible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*hRRm9KC--LoT0SbVgv6haA.png" /></figure><p>In simple language, it can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/0*cTzZmrajjugWTSqO.png" /></figure><p>For example, if we have a deck of poker, we want to know the probability that the card we draw is king given that it is a card with a man. So according to the Bayesian formula, we know</p><ul><li>p(King) is equal to 4/52 because there are 4 Kings in a deck of cards</li><li>p(Face|King) is equal to 1 because all kings are Face</li><li>p(Face) is equal to 12/52 because each suit has 3 Face, and there are 12 cards in total</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*u-ScgYuwOYx0hXIP.gif" /></figure><p>The next formula is something we will often encounter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*tSBMq34Pffa8bTrP57Y5iw.png" /></figure><p>In practice, we only care about the numerator of the fraction, because the denominator does not depend on yy and the value of the feature X is given, we can consider the denominator to be a constant, so that the numerator is equivalent to the joint distribution model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*YtiUTtOLJbqawazEiNVt5A.png" /></figure><p>Using the chain rule repeatedly, the formula can be written in the form of conditional probability, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-bMB0kMR1YYjbwe72w-EQ.png" /></figure><h3>Main Idea (2): Conditional independence hypothesis</h3><p>From now on, the “simple” assumption of conditional independence begins to work. What is conditional independence? When two events A and B occur given Y, whether A and B happen or not are independent in terms of the conditional probability distribution, that is, they are conditionally independent given Y.</p><p>So we assume that each feature is conditionally independent, meaning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*emECa9xEE7Gakm39Nx-TgQ.png" /></figure><p>For i is not equal to j, the joint distribution model can be expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*yX2dgUmoYG781DqbsJuZvQ.png" /></figure><p>So this means that the conditional distribution of class variables y can be expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*3Rp3HhLzJg8v4nwAuJeSrQ.png" /></figure><p>Where Z (evidence) is a dependent only on features since the value of the characteristic variable at this time is a constant, which is just an integral. Since it is decomposed into the so-called prior probability p(y) and the independent probability distribution, which evolved into their likelihood. The stability of the probability of the above model has been greatly improved.</p><h3>Main Idea (3): Construct a classifier from a probability model</h3><p>So how to construct a classifier from the naive Bayes probability model requires the establishment of a decision rule. A very common rule is to select the most probable one, which is the maximum posterior probability (<a href="https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation">MAP</a>) decision criterion, and the corresponding classification is a formula defined as follows. Here we assume that y has K categories, so we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*BMX9-ITDWWJws1zcHJpXQA.png" /></figure><p>All the parameters of the model can be estimated by the frequency of each class corresponding to the whole dataset.</p><h3>Extension (1): Gaussian Naive Bayes (GNB)</h3><p>In order to estimate the distribution parameters of the features, we assume tat the training set is following some kind of distribution. Here, we assume that it is normally distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*78Z3MtFXV7rvJI1h.jpeg" /><figcaption>Credited to ChrisAlbon</figcaption></figure><p>If you are dealing with continuous data, a common assumption is that these continuous values ​​are Gaussian. For example, assuming that there is a continuous feature x in the training set, we first classify the data according to categories, and then calculate the mean and variance of x in each category. We have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*6sdu6dyCFbSCiLHU8u1FXw.png" /></figure><p>So, we take x = v as an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*quNGPeFWQrkir6WX4pWnmw.png" /></figure><p>Another commonly used technique for dealing with continuous numerical problems is by discretizing continuous numerical values. Generally, when the number of training samples is small or the precise distribution is known, the method of passing probability distribution is a better choice. In the case of a large number of samples, the discretization method performs better, because a large number of samples can learn the distribution of the data. Since NB is a typical method that uses a large number of samples (the larger the amount of calculation, the higher the accuracy of classification), so the NB uses the discretization method , rather than the method of probability distribution estimation.</p><p>Here is how GNB works. The z-score of each class-mean and every data point can be calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*spRaL4aD_EZVuT3e.png" /></figure><p>If a given class and feature did not appear together in the training set, then the probability will be 0 under frequency-based estimation. This will be a problem. Because when multiplying with other probabilities, all other probabilities will be removed. Therefore, it is often required to modify the probability estimate of each small sample to ensure that there will be no probability of 0.</p><p>Although the independence assumption is often inaccurate in practice, several features of the NB classifier make it possible to obtain surprising results in practice. In particular, the decoupling between various conditional features (<strong>decoupling in mathematics refers to turning a mathematical equation containing multiple variables into a system of equations that can be represented by a single variable, that is, variables no longer directly affect the result of an equation at the same time so as to simplify analysis and calculation</strong>) means that the distribution of each feature can be independently estimated as a one-dimensional distribution.</p><p>This alleviates the obstacles caused by the disaster of dimensionality. When the number of features of the sample increases, the sample size does not need to increase exponentially. However, Naive Bayes cannot make a very accurate estimate of class probability in most cases, but this is not required in many applications.</p><p>For example, in the Naive Bayes classifier, according to the maximum posterior probability (MAP) decision rule, as long as the posterior probability of the correct class is higher than other classes, the correct classification can be obtained. So no matter whether the probability estimate is mild or even severely imprecise, it will not affect the correct classification result. In this way, the classifier can be robust enough to ignore the defects in the Naive Bayes probability model.</p><h3><strong>Naive Bayes in Python &amp; R</strong></h3><ul><li>Python</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/094424787b046c992e02a05245de1ec6/href">https://medium.com/media/094424787b046c992e02a05245de1ec6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6525f660a2df79cc2961b7e0f0dc219/href">https://medium.com/media/e6525f660a2df79cc2961b7e0f0dc219/href</a></iframe><ul><li>R</li></ul><pre>library(datasets)<br>data(iris)</pre><pre>set.seed(100) <br>training_rows &lt;- sort(c(sample(1:50, 40), sample(51:100, 40), sample(101:150, 40)))<br>training_x &lt;- as.data.frame(iris[training_rows, 1:4])<br>training_y &lt;- iris[training_rows, 5]</pre><pre>iris_nb &lt;- function(x, trainx, trainy){<br>  train &lt;- cbind(trainx, trainy)<br>  <br>  class_virginica &lt;- train[which(train$trainy == &#39;virginica&#39;),]<br>  class_setosa &lt;- train[which(train$trainy == &#39;setosa&#39;),]<br>  class_versicolor &lt;- train[which(train$trainy == &#39;versicolor&#39;),]<br>  <br>  posterior &lt;- function(x, classtype){<br>    p_Sepal.Length &lt;- dnorm(x[1], mean(classtype[,1]), sd(classtype[,1]))<br>    p_Sepal.Width  &lt;- dnorm(x[2], mean(classtype[,2]), sd(classtype[,2]))<br>    p_Petal.Length &lt;- dnorm(x[3], mean(classtype[,3]), sd(classtype[,3]))<br>    p_Petal.Width  &lt;- dnorm(x[4], mean(classtype[,4]), sd(classtype[,4]))<br>    <br>    vec &lt;-  0.33* p_Sepal.Length * p_Sepal.Width * p_Petal.Length * p_Petal.Width #for each species<br>    return(vec)<br>  }<br>  <br>  return(list(virginica = sum(posterior(x, class_virginica)), <br>              setosa = sum(posterior(x, class_setosa)),<br>              versicolor = sum(posterior(x, class_versicolor))))<br>}</pre><pre>test_case_1 &lt;- as.matrix(iris[1, 1:4])<br>iris_nb(test_case_1, training_x, training_y)</pre><pre>## $virginica<br>## [1] 9.718005e-25<br><br>## $setosa<br>## [1] 2.866246<br><br>## $versicolor<br>## [1] 4.808048e-19</pre><p><a href="https://uc-r.github.io/naive_bayes">Naïve Bayes Classifier</a></p><h3>Interview Questions &amp; Other Materials</h3><blockquote>Interview Question</blockquote><ul><li><em>What is the difference between Naive Bayes and LR?</em></li></ul><p>Simply put: Naive Bayes is a <strong>generative model</strong>. Bayesian estimation is based on existing samples to learn the prior probability P(Y) and conditional probability P(X|Y), and then the joint distribution probability P(X, Y) , And finally use Bayes&#39; theorem to solve P(Y|X), and LR is a <strong>discriminant</strong> model, according to the maximum log likelihood function to directly obtain the conditional probability P(Y|X); Naive Bayes is based on a strong conditional independence assumption (under the condition that the classification Y is known, the values ​​of each feature variable are independent of each other), while LR does not require this; Naive Bayes is suitable for scenarios with few data points, and LR is suitable for a large scale dataset.</p><ul><li><em>Why is Naive Bayes naive?</em></li></ul><p>When using Bayes’ theorem to solve the joint probability P(X, Y), you need to calculate the conditional probability P(X|Y). When calculating P(X|Y), Naive Bayes made a strong <strong>conditional independence assumption</strong> (when Y is determined, the values ​​of the components of X are independent of each other), which is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*5NKN6OZco2NBX_QG2NZuig.png" /></figure><ul><li><em>What to do if the probability is 0 when estimating the conditional probability P(X|Y)?</em></li></ul><p>Simply put: Introduce λ. When λ=1, it is called Laplace smoothing.</p><p>Laplacian smoothing is a correction method for dealing with zero probability in Naive Bayes. When performing classification, it may happen that a certain attribute does not appear in the training set at the same time as a certain class. If the calculation is directly based on the expression of the naive Bayes classifier, there will be a zero probability phenomenon. In order to prevent the information carried by other attributes from being “erased” by attribute values ​​that have not appeared in the training set, the Laplacian estimator is used for correction. The specific method is: <strong>add 1 to the numerator, and for the prior probability, add the number of possible categories in the training set to the denominator</strong>; <strong>for conditional probability, add the number of possible values ​​of the i-th attribute to the denominator</strong></p><ul><li><em>Pros and cons of Naive Bayes</em></li></ul><p>Pros: Performs well on small-scale data; Suitable for multi-classification tasks; Suitable for incremental training.</p><p>Cons: Very sensitive to the expression form of the input data (discrete, continuous, maximum and minimum values, etc.)</p><ul><li><em>Are there any hyperparameters in Naive Bayes that can be adjusted?</em></li></ul><p>Naive Bayes has no hyperparameters that can be adjusted, so it does not need to adjust parameters. Naive Bayes is classified according to the training set, and the result of the classification is basically determined. The Laplace estimator λ is not a parameter of naive Bayes classifier. The parameters cannot be adjusted to Naive Bayes through the Laplace estimator λ.</p><blockquote>Other Materials</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FO2L2Uv9pdDA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DO2L2Uv9pdDA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FO2L2Uv9pdDA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/73fbca6420fef85706b8e479263aae72/href">https://medium.com/media/73fbca6420fef85706b8e479263aae72/href</a></iframe><ul><li><a href="https://scikit-learn.org/stable/modules/naive_bayes.html">1.9. Naive Bayes</a></li><li><a href="https://www.rdocumentation.org/packages/e1071/versions/1.7-3/topics/naiveBayes">naiveBayes</a></li></ul><h3>Summary</h3><p>Among all machine learning classification algorithms, Naive Bayes is different from most other classification algorithms. For most classification algorithms, such as decision trees, KNN, logistic regression, support vector machines, etc., they are all discriminative methods, that is, directly learn the relationship between feature output Y and feature X, or decision function Y=f (X), or conditional distribution P(Y|X). But Naive Bayes is a generation method, that is, directly find the joint distribution P(X,Y) of feature output Y and feature X, and then use P(Y|X)=P(X,Y)/P(X) inferred. Naive Bayes is very intuitive and does not require a large amount of calculation. It has wide applications in many fields.</p><p><em>Originally published at </em><a href="https://zg104.github.io/Naive_bayes"><em>https://zg104.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a97cff1cba3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/everything-you-need-to-know-about-na%C3%AFve-bayes-9a97cff1cba3">Everything You Need to Know about Naïve Bayes</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Minutes to Understand K-Nearest Neighbours (KNN) in One Article]]></title>
            <link>https://medium.com/analytics-vidhya/%E4%B8%80%E6%96%87%E6%90%9E%E6%87%82k%E8%BF%91%E9%82%BB%E7%AE%97%E6%B3%95-knn-a1c3571562c1?source=rss-af85ebf340de------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c3571562c1</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zijing Gao]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 21:30:18 GMT</pubDate>
            <atom:updated>2020-09-21T16:11:47.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>Starting From KNN to dive into ML</h4><h4>Content</h4><ul><li>What is K-Nearest Neighbours?</li><li>How KNN Works</li><li>How to Deal with k</li><li>KNN in Python: Scikit-Learn &amp; Scratch</li><li>Cons &amp; Pros of KNN</li><li>Improvments</li><li>KNN Interview Questions &amp; Other Materials</li><li>Summary</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IA0Aq2fymtcTXKYuGxSYew.jpeg" /></figure><h3>What is K-Nearest Neighbours</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dNwOcofpryp8R4Og.png" /></figure><p>We are all already familiar with using X to represent <strong>features</strong> and y to represent <strong>targets</strong>. KNN is a <strong>supervised learning algorithm</strong>, that is, we have a dataset (X, y) with target results, and we want to discover their relationship, which means we want to find an equation h(x) so that X can be used to predict y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*WgmTbWoVAn2bPotEr6HUxw.png" /></figure><p>KNN classifier is also a <strong>non-parametric</strong> and <strong>instance-based </strong>algorithm.</p><ul><li><strong>Non-parametric</strong> means that it does not make any explicit assumptions about the function h(x), thus avoiding the risk of incorrectly modeling the data distribution. For example, if our data is highly non-Gaussian, but the learning model we choose is Gaussian distributed (<a href="https://zg104.github.io/Naive_bayes#362">LDA</a>), the result will be very unsatisfactory.</li><li><strong>Instance-based</strong> means that our algorithm has no real learning model. Instead, it chooses to memorize the trained instance and uses it as the “knowledge” in the prediction phase. Specifically, this means that only when a query is made to our database (i.e. when we ask it to predict the label of a given input), the algorithm will use the trained instances to give the results.</li></ul><p>It is worth noting that the minimum training phase of KNN not only costs a “memory cost” (because we have to store a huge data set during testing) but also a computational cost (because classifying a given observation requires the entire data group). Actually, this is not advisable.</p><h3>How KNN Works</h3><p>When performing classification, the K-nearest neighbor algorithm essentially boils down to voting based on the “minority obeying the majority” among the given “invisible” K most similar instances (so it is also called the voting algorithm).</p><p>How to define similarity? We define similarity based on the distance metric between two data points. Euclidean distance is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*FeBsVApXDixuOqlEPZiYqQ.png" /></figure><p>But there are other options such as <strong>Manhattan</strong>, <strong>Chebyshev</strong> and <strong>Hamming distance</strong>.</p><p>Given a positive integer <em>K</em>, an unknown observation value<em> x</em> and a specific measurement method <em>d</em>, KNN classifies through the following steps</p><ul><li>The algorithm runs through the entire dataset to calculate the distance between <em>x</em> and the observations in each training set. We call the <em>K</em> points closest to <em>x</em> in the training data set A. Note that to prevent a tie, <em>K</em> is usually an odd number.</li><li>Next, it estimates the conditional probability of each category, that is, the proportion of points in the set <em>A</em> with a given category label. (Note that I(x) is an indicator function, and it returns 1 when its parameter x is true, otherwise it is 0)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*MKUAPS96g_6i8yIW1dsksw.png" /></figure><p>Finally, the input we entered is assigned to the corresponding category according to the maximum probability.</p><blockquote><em>KNN searches the memorized training observations for the K instances that most closely resemble the new instance and assigns to it the their most common class.</em></blockquote><p>The specific algorithm is as follows:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2FcfBgsIJH8SGCts&amp;display_name=SlideShare&amp;url=https%3A%2F%2Fwww.slideshare.net%2Ftilanigunawardena%2Fk-nearest-neighbors&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Fknn-160904075605-thumbnail-4.jpg%3Fcb%3D1472975797&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/facdd5eaa28fa7dfb625ebeec446ab83/href">https://medium.com/media/facdd5eaa28fa7dfb625ebeec446ab83/href</a></iframe><h3>How to Deal with k</h3><p>So now, you should know how the KNN algorithm works, but the selection of <em>K</em> is still very crucial. Similar to other machine learning algorithms, <em>K</em> is a hyperparameter which is used to control the shape of the decision boundary.</p><p>When K is small, we confine our “eye” to the given prediction area and “turn a blind eye” to the overall distribution of our classifier. It will have the properties of<strong> </strong>low bias but high variance (overfitting). Graphically, the decision boundary will be more uneven.</p><p>On the other hand, a larger <em>K </em>means that there are more average “voters” in each prediction situation (that is, we are more focused on global considerations, considering more data points each time, and the model has stronger generalization ability), Therefore, the adaptability to outliers is higher. A larger <em>K</em> will have a smoother decision boundary, which means that the variance is smaller, but the bias increases (underfitting).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n4LQN1RJ2OQeah9X.png" /></figure><p>When <em>k</em> is 1, that is to say, after calculating the distance between the new test point and the points of all training sets along with sorting, only the nearest <strong>single</strong> point is taken for analysis. If this point belongs to a certain category, then we will assert the test points fall into this category. Obviously, this is too absolute. We should allow more points to participate in the comparison to make the voting results more convincing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZWQ4AAJWl_Yx8jKU.png" /></figure><p>When we increase <em>k</em> to 20, we find that the shape of the entire decision boundary has changed a lot, the jagged shape has been reduced, and the number of voting points has increased from 1 to 20, making the model more generalized in order to avoid overfitting.</p><ul><li>The smaller the k is, the easier it is to overfit; the larger the k is, the easier it is to underfit.</li><li>k is a hyperparameter and needs to be adjusted by cross validation.</li></ul><h3>KNN in Python：Sklearn &amp; Scratch</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d04ffd057f9fd5515685cec93dd830/href">https://medium.com/media/77d04ffd057f9fd5515685cec93dd830/href</a></iframe><h3>Cons &amp; Pros of KNN</h3><blockquote>Pros</blockquote><ul><li>Easy to understand</li><li>No preliminary assumptions about data distribution</li><li>Available for multi-category situations</li></ul><blockquote>Cons</blockquote><ul><li>Inefficient calculation when dealing with large datasets.</li><li>The effect of skewed data is very poor. If the frequency of one type of data is extremely high, it will seriously suppress other types. When voting, we will ignore their existence.</li><li>Bad performance when dealing with high-dimensional data . In this case, the distance measure becomes blurred.</li></ul><h3>Improvements</h3><ul><li>A simple and effective way to improve the partial distribution is to use “weighted voting”. The category of each of the <em>K</em> neighbors is multiplied by a weight proportional to the inverse of the distance from the point to the given test point. This ensures that the closer neighbors contribute more to the final vote than the far neighbors.</li><li>Change the method of measuring distance.</li><li>Normalize the data to make the concept of distance more obvious</li><li>Dimension reduction</li><li>Approximate Nearest-Neighbors (for example, using k-d trees to store training observations) can be used to reduce test time. However, this method often performs poorly in high dimensions (20+). If the dimensionality is too high, try using area sensitive hashing (LHS)</li></ul><h3>KNN Interview Questions &amp; Other Materials</h3><blockquote>Interview Question</blockquote><ul><li><a href="https://www.analyticsvidhya.com/blog/2017/09/30-questions-test-k-nearest-neighbors-algorithm/">30 Questions to test a data scientist on K-Nearest Neighbors (kNN) Algorithm</a></li><li><a href="https://medium.com/@cornell_data/interview-case-study-1-sampling-methods-and-parameter-changes-4799c580aa42">Interview Case Study #1: The Statistics Of KNN Parameter Optimization</a></li><li><a href="https://www.cnblogs.com/xueyunqing/p/10281656.html">KNN interview question (Chinese Version)</a></li></ul><blockquote>Other Materials</blockquote><ul><li><a href="https://cs231n.github.io/classification/#nn">Stanfords <strong>CS231n</strong> notes on KNN</a></li><li><a href="https://scikit-learn.org/stable/modules/neighbors.html">Scikit-learn’s documentation for KNN</a></li><li><a href="https://www.cnblogs.com/pinard/p/6061661.html">KNN Summary by Jianping Liu</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHVXime0nQeI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHVXime0nQeI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHVXime0nQeI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ac294c7d7cae49a8e0da6e96a4f33e/href">https://medium.com/media/10ac294c7d7cae49a8e0da6e96a4f33e/href</a></iframe><h3>Summary</h3><p>K-nearest neighbors (KNN) is a very basic machine learning method, and it is also involuntarily applied in our daily lives. For example, to judge a person’s character, we only need to observe the character of the few people with whom he has the closest contacts. The idea of ​​KNN is used here. The KNN method can do both classification and regression, which is the same as the decision tree algorithm.</p><p>The main difference between regression and classification of KNN is the different decision-making methods when making predictions. When KNN makes classification prediction, it generally chooses the majority voting method, that is, the <em>K</em> samples closest to the predicted sample feature in the training set are predicted as the category with the largest number of categories. When KNN performs regression, the average method is generally selected, that is, the average value of the sample output of the nearest <em>K</em> samples is used as the regression prediction value. Due to the small difference between the two, although this article mainly explains the KNN classification method, the idea is also applicable to the KNN regression method. Since scikit-learn only uses brute-force, KDTree and BallTree, this article only discusses the implementation principles of these algorithms. The rest of the implementation methods, such as BBF tree, MVP tree, etc., are not discussed here.</p><p><em>Originally published at </em><a href="https://zg104.github.io/KNN_tutorial"><em>https://zg104.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c3571562c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/%E4%B8%80%E6%96%87%E6%90%9E%E6%87%82k%E8%BF%91%E9%82%BB%E7%AE%97%E6%B3%95-knn-a1c3571562c1">30 Minutes to Understand K-Nearest Neighbours (KNN) in One Article</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>