<?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 Venkatesh Umamaheswaran on Medium]]></title>
        <description><![CDATA[Stories by Venkatesh Umamaheswaran on Medium]]></description>
        <link>https://medium.com/@venkateshumamaheswaran?source=rss-348591115db0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wQM3N1oS1Oihu5BWfwH41A.png</url>
            <title>Stories by Venkatesh Umamaheswaran on Medium</title>
            <link>https://medium.com/@venkateshumamaheswaran?source=rss-348591115db0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:32:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@venkateshumamaheswaran/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[Comprehending K-means and KNN Algorithms]]></title>
            <link>https://becominghuman.ai/comprehending-k-means-and-knn-algorithms-c791be90883d?source=rss-348591115db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c791be90883d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Venkatesh Umamaheswaran]]></dc:creator>
            <pubDate>Mon, 12 Nov 2018 13:01:01 GMT</pubDate>
            <atom:updated>2018-11-14T13:49:27.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Im_pCLx-d9cpDR7s" /></figure><p><strong>Data Science</strong> is an exciting field to work in, consolidating advanced statistical and quantitative skills with real-world programming ability. There are a ton of ‘smart’ algorithms that assist data scientists do the wizardry. To start with, it might all seem complicated, but if we understand and organize algorithms a bit, it’s not even that hard to find and apply the one that we need.</p><p>Today we will discuss about two commonly used algorithms in Machine Learning — <strong>K-Means Clustering and k-Nearest Neighbors algorithm</strong>. They are often confused with each other. The ‘K’ in K-Means Clustering has nothing to do with the ‘K’ in KNN algorithm. k-Means Clustering is an unsupervised learning algorithm that is used for clustering whereas KNN is a supervised learning algorithm used for classification.</p><h3>Trending AI Articles:</h3><blockquote><a href="https://becominghuman.ai/face-detection-with-opencv-and-deep-learning-90b84735f421">1. Face detection with OpenCV and Deep Learning from image</a></blockquote><blockquote><a href="https://becominghuman.ai/an-intuitive-introduction-to-machine-learning-57b2b1bd3d6">2. An intuitive introduction to Machine Learning</a></blockquote><blockquote><a href="https://becominghuman.ai/lets-build-a-simple-neural-net-f4474256647f">3. Let’s build a simple Neural Net!</a></blockquote><blockquote><a href="https://becominghuman.ai/decision-trees-in-machine-learning-f362b296594a">4. Decision Trees in Machine Learning</a></blockquote><h4><strong>K-Means Algorithm</strong></h4><p>The k-means algorithm is an <strong>unsupervised </strong>clustering algorithm. It takes a bunch of unlabeled points and tries to group them into “k” number of clusters.</p><p>It is unsupervised because the points have no external classification.</p><p>The “k” in k-means denotes the number of clusters you want to have in the end. If k = 5, you will have 5 clusters on the data set.</p><blockquote><strong>How it works?</strong></blockquote><blockquote>Step 1: Determine K value by Elbow method and specify the number of clusters K</blockquote><blockquote>Step 2: Randomly assign each data point to a cluster</blockquote><blockquote>Step 3: Determine the cluster centroid coordinates</blockquote><blockquote>Step 4: Determine the distances of each data point to the centroids and re-assign each point to the closest cluster centroid based upon minimum distance</blockquote><blockquote>Step 5: Calculate cluster centroids again</blockquote><blockquote>Step 6: Repeat steps 4 and 5 until we reach global optima where no improvements are possible and no switching of data points from one cluster to other.</blockquote><h4>Implementation using Python</h4><p>Let’s see how K-Means algorithm can be implemented on a simple iris data set using Python.</p><blockquote>Finding the optimum number of clusters for k-means clustering</blockquote><pre>Nc = range(1, 10)<br>kmeans = [KMeans(n_clusters=i) for i in Nc]<br>kmeans<br>score = [kmeans[i].fit(x).score(x) for i in range(len(kmeans))]<br>score<br>pl.plot(Nc,score)<br>pl.xlabel(&#39;Number of Clusters&#39;)<br>pl.ylabel(&#39;Score&#39;)<br>pl.title(&#39;Elbow Curve&#39;)<br>pl.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*-4IIOWqYA9Nb62X9K7Pnbg.png" /><figcaption>Elbow Curve for determining optimum ‘k’ number of clusters</figcaption></figure><blockquote>You can clearly see why it is called ‘The elbow method’ from the above graph, the optimum clusters is where the elbow occurs.</blockquote><blockquote>Now that we have the optimum amount of clusters (k=3), we can move on to applying K-means clustering to the Iris data set</blockquote><pre><strong>#Implementation of K-Means Clustering</strong><br>model = KMeans(n_clusters = 3)<br>model.fit(x)<br>model.labels_<br>colormap = np.array([&#39;Red&#39;, &#39;Blue&#39;, &#39;Green&#39;])<br>z = plt.scatter(x.sepal_length, x.sepal_width, x.petal_length, c = colormap[model.labels_])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*SeTnGHeg8YtousBssUUrkA.png" /><figcaption>K-Means clustering on Iris data set</figcaption></figure><pre><strong>#Accuracy of K-Means Clustering</strong><br>accuracy_score(iris.target,model.labels_)<br>0.8933333333333333</pre><h4><strong>KNN Algorithm</strong></h4><p>The k-nearest neighbors algorithm is a <strong>supervised </strong>classification algorithm. It takes a bunch of labeled points and uses them to learn how to label other points. To label a new point, it looks at the labeled points closest to that new point which are its nearest neighbors, and has those neighbors vote. So whichever label, the most of the neighbors have is the label for the new point. Here “k” in K-Nearest Neighbors is the number of neighbors it checks. It is supervised because you are trying to classify a point based on the known classification of other points.</p><blockquote><strong>How it works?</strong></blockquote><blockquote>Step 1: Determine the value for K</blockquote><blockquote>Step 2: Calculate the distances between the new input (test data) and all the training data. The most commonly used metrics for calculating distance are <strong>Euclidean, Manhattan and Minkowski</strong></blockquote><blockquote>Step 3: Sort the distance and determine k nearest neighbors based on minimum distance values</blockquote><blockquote>Step 4: Analyze the category of those neighbors and assign the category for the test data based on majority vote</blockquote><blockquote>Step 5: Return the predicted class</blockquote><h4><strong>Implementation using Python</strong></h4><p>Let’s make use of the same iris data set to learn how to implement KNN algorithm.</p><pre>plt.figure(figsize=(12, 6))<br>plt.plot(range(1, 40), error, color=&#39;black&#39;, linestyle=&#39;dashed&#39;, marker=&#39;o&#39;,<br>         markerfacecolor=&#39;grey&#39;, markersize=10)<br>plt.title(&#39;Error Rate K Value&#39;)<br>plt.xlabel(&#39;K Value&#39;)<br>plt.ylabel(&#39;Mean Error&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*kT5XLhb7prLueT6MtRDBDQ.png" /><figcaption>Error rate for different values of K</figcaption></figure><p>Now we know for what values of ‘K’, the error rate will be less. Let’s fix k=5 and implement KNN algorithm.</p><pre><strong>#Creating training and test splits</strong><br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)</pre><pre><strong>#Performing Feature Scaling</strong><br>from sklearn.preprocessing import StandardScaler<br>scaler = StandardScaler()<br>scaler.fit(X_train)</pre><pre>X_train = scaler.transform(X_train)<br>X_test = scaler.transform(X_test)</pre><pre><strong>#Training KNN with k=5</strong><br>from sklearn.neighbors import KNeighborsClassifier<br>classifier = KNeighborsClassifier(n_neighbors=5)<br>classifier.fit(X_train, y_train)</pre><pre>y_pred = classifier.predict(X_test)<br>from sklearn.metrics import classification_report, confusion_matrix<br>print(confusion_matrix(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><pre><strong>[[12  0  0]<br> [ 0  9  0]<br> [ 0  0  9]]<br>                 precision    recall  f1-score   support<br><br>    Iris-setosa       1.00      1.00      1.00        12<br>Iris-versicolor       1.00      1.00      1.00         9<br> Iris-virginica       1.00      1.00      1.00         9<br><br>    avg / total       1.00      1.00      1.00        30</strong></pre><blockquote>For complete code, please visit <a href="https://github.com/VenkateshUV/Comprehending-K-Means-and-KNN-Algorithms/blob/master/Knn%20and%20K-Means.ipynb">https://github.com/VenkateshUV/Comprehending-K-Means-and-KNN-Algorithms/blob/master/Knn%20and%20K-Means.ipynb</a></blockquote><p>I hope this article helped you little in understanding what K-Means and K-Nearest Neighbors algorithms are. This is my first blog with Medium and I hope to dig into more data science algorithms in the near future. I welcome questions, notes, suggestions, constructive comments. Please reach out to me at venkateshumamaheswaran@gmail.com. See you next time!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F8f5f8b%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F8f5f8b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href">https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href</a></iframe><figure><a href="https://becominghuman.ai/artificial-intelligence-communities-c305f28e674c"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*2f7OqE2AJK1KSrhkmD9ZMw.png" /></a></figure><figure><a href="https://upscri.be/8f5f8b"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*v-PpfkSWHbvlWWamSVHHWg.png" /></a></figure><figure><a href="https://becominghuman.ai/write-for-us-48270209de63"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Wt2auqISiEAOZxJ-I7brDQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c791be90883d" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/comprehending-k-means-and-knn-algorithms-c791be90883d">Comprehending K-means and KNN Algorithms</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>