<?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 Isa Gafarli on Medium]]></title>
        <description><![CDATA[Stories by Isa Gafarli on Medium]]></description>
        <link>https://medium.com/@isaqafarli98?source=rss-9762698e8762------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KxA_y0NXXtDkpiXx</url>
            <title>Stories by Isa Gafarli on Medium</title>
            <link>https://medium.com/@isaqafarli98?source=rss-9762698e8762------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:34:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isaqafarli98/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[What is KNN algorithm and how it works?]]></title>
            <link>https://medium.com/@isaqafarli98/what-is-knn-algorithm-and-how-it-works-5cd338452f8c?source=rss-9762698e8762------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd338452f8c</guid>
            <category><![CDATA[knn-algorithm]]></category>
            <dc:creator><![CDATA[Isa Gafarli]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 09:43:32 GMT</pubDate>
            <atom:updated>2023-03-24T09:47:15.186Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays machine learning is hot topic with its algorithms in most industries. Therefore, people try to learn and implement these algorithms in their industries. Now, we will talk about one of the simplest algorithms which is called KNN (K-Nearest Neighbor). Many newbies to Machine Learning confuse it with K means algorithm. However, we can easily say that only the letter K is similar between the two algorithms.</p><p>KNN refers to a supervised algorithm and works on the basis of similarity. What does it mean basis of similarity or neighborhood? It means that we have historical data and new data. As a result, algorithm learns similarity between new cases and available data then appends new cases which are almost identical to the available categories. For instance, we have historical data which consists of features of apples and oranges like size, color and so on. Then we add new cases of these features in order to predict type of fruits. For example, we take 5 neighbors (based on identical features) which are near new data. If three of them are apples and two of them are oranges, model predicts that this new case is apple.</p><p>1. KNN algorithm is available for regression models but mostly it is used for classification.</p><p>2. It is nonparametric algorithm; it means that there is not any presupposition in underlying data.</p><p>3. KNN is not learning from training datasets. Mostly it is used full dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*TvGpKq4m0-IKmfjUdwULRQ.png" /><figcaption>Adding new case to available cases</figcaption></figure><blockquote>HOW KNN ALGORITHM IS WORKING?</blockquote><p>In this part, I will explain all parts detailed.</p><ol><li>Pick value for k.</li></ol><p>Firstly, in order to define how many neighbors should be of new cases, we must select a value for k. <strong>Here it is created a question that how we select best k?</strong></p><p><strong>Solution: Elbow Method (it will be explained at end of article)</strong></p><p>2. Calculate distance unknown case from all cases.</p><p>In order to calculate distance among data points, it is mostly used Euclidian Distance. It is just simple mathematic formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*0zt44v3UjAlF26XifOXVdA.png" /><figcaption>Euclidian Distance</figcaption></figure><p>3. After calculating distance, select k number of neighbors due to distance.</p><p>4. Finally, take most repeatable similarity of available data with new cases.</p><p>5. Model is ready.</p><p>As I mentioned before that, how should we choose k. The important case in this model to find optimal k. We find optimal k by Elbow Method. What is Elbow method?</p><p>Elbow method is relationship with k numbers and their accuracy or error rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*C0-UvOpl9dLFQCWgp9mTyg.png" /><figcaption>Elbow Graph</figcaption></figure><p>As graph illustrates that optimal k is 20. We can see from graph that after 20 curve is increasing or goes constantly, therefore, most optimal k is 20.</p><p>Of course, while setting up model, must be considered value of k. If k is low, model causes <strong>overfitting</strong>, but if k is high, model causes <strong>underfitting.</strong></p><h3>Advantages of algorithm:</h3><ol><li>It is so easy to use.</li><li>It is very powerful for noisy data.</li><li>It is working very good in large training data.</li></ol><h3>Disadvantages of algorithm:</h3><ol><li>It is difficult to define value of k.</li><li>It is very costly to calculate distance among data points</li></ol><h3>KNN Implementation in Python</h3><p><strong>Importing Libraries and creating model</strong></p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import classification_report, confusion_matrix, accuracy_score</pre><pre>df= pd.read_csv(&#39;gene_expression.csv&#39;)<br>X = df.drop(&#39;Cancer Present&#39;, axis=1)<br>y = df[&#39;Cancer Present&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)<br>scaler= StandardScaler()<br>scaler.fit(X_train)<br>scaled_X_train= scaler.transform(X_train)<br>scaled_X_test= scaler.transform(X_test)<br></pre><pre>knn_model= KNeighborsClassifier(n_neighbors = 15)<br>knn_model.fit(scaled_X_train, y_train)<br>y_pred= knn_model.predict(scaled_X_test)<br>pd.DataFrame({&#39;Y_Test&#39;:y_test, &#39;Y_Pred&#39;: y_pred})</pre><pre>accuracy_score(y_test, y_pred)<br>confusion_matrix(y_test, y_pred)<br>print(classification_report(y_test, y_pred))</pre><p><strong>Elbow Method</strong></p><pre>test_error_rate = []<br><br><br>for k in range (1, 30):<br>    knn_model = KNeighborsClassifier(n_neighbors = k)<br>    knn_model.fit(scaled_X_train, y_train)<br>    <br>    y_pred_test = knn_model.predict(scaled_X_test)<br>    <br>    test_error=1 - accuracy_score(y_test, y_pred_test)<br>    test_error_rate.append(test_error)</pre><pre>plt.figure(figsize=(10, 6))<br>plt.plot(range(1, 30), test_error_rate, label=&#39;Test Error&#39;)<br>plt.legend()<br>plt.ylabel(&#39;Error Rate&#39;)<br>plt.xlabel(&#39;K Value&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyb-_UX-2yqTr1CDUHCk1Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd338452f8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>