KNN (K-nearest neighbors) Classification
Tags: machinelearning, datascience, knn, 100daysofdatascience
Published: 2023-02-01 10:02:40

## Import necessary libraries:
The code imports numpy, pandas, seaborn, matplotlib, and scikit-learn libraries, which are commonly used for data manipulation, visualization, and machine learning tasks.


```python
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
```

## Load the data: 
The code reads a csv file containing the dataset into a pandas dataframe using pd.read_csv() method.


```python
# Load your data into a pandas dataframe
df = pd.read_csv("/kaggle/input/knn-data1/KNN_Project_Data")
```


```python
df
```




<div>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>XVPM</th>
      <th>GWYH</th>
      <th>TRAT</th>
      <th>TLLZ</th>
      <th>IGGA</th>
      <th>HYKR</th>
      <th>EDFS</th>
      <th>GUUB</th>
      <th>MGJM</th>
      <th>JHZC</th>
      <th>TARGET CLASS</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1636.670614</td>
      <td>817.988525</td>
      <td>2565.995189</td>
      <td>358.347163</td>
      <td>550.417491</td>
      <td>1618.870897</td>
      <td>2147.641254</td>
      <td>330.727893</td>
      <td>1494.878631</td>
      <td>845.136088</td>
      <td>0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1013.402760</td>
      <td>577.587332</td>
      <td>2644.141273</td>
      <td>280.428203</td>
      <td>1161.873391</td>
      <td>2084.107872</td>
      <td>853.404981</td>
      <td>447.157619</td>
      <td>1193.032521</td>
      <td>861.081809</td>
      <td>1</td>
    </tr>
    <tr>
      <th>2</th>
      <td>1300.035501</td>
      <td>820.518697</td>
      <td>2025.854469</td>
      <td>525.562292</td>
      <td>922.206261</td>
      <td>2552.355407</td>
      <td>818.676686</td>
      <td>845.491492</td>
      <td>1968.367513</td>
      <td>1647.186291</td>
      <td>1</td>
    </tr>
    <tr>
      <th>3</th>
      <td>1059.347542</td>
      <td>1066.866418</td>
      <td>612.000041</td>
      <td>480.827789</td>
      <td>419.467495</td>
      <td>685.666983</td>
      <td>852.867810</td>
      <td>341.664784</td>
      <td>1154.391368</td>
      <td>1450.935357</td>
      <td>0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>1018.340526</td>
      <td>1313.679056</td>
      <td>950.622661</td>
      <td>724.742174</td>
      <td>843.065903</td>
      <td>1370.554164</td>
      <td>905.469453</td>
      <td>658.118202</td>
      <td>539.459350</td>
      <td>1899.850792</td>
      <td>0</td>
    </tr>
    <tr>
      <th>...</th>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <th>995</th>
      <td>1343.060600</td>
      <td>1289.142057</td>
      <td>407.307449</td>
      <td>567.564764</td>
      <td>1000.953905</td>
      <td>919.602401</td>
      <td>485.269059</td>
      <td>668.007397</td>
      <td>1124.772996</td>
      <td>2127.628290</td>
      <td>0</td>
    </tr>
    <tr>
      <th>996</th>
      <td>938.847057</td>
      <td>1142.884331</td>
      <td>2096.064295</td>
      <td>483.242220</td>
      <td>522.755771</td>
      <td>1703.169782</td>
      <td>2007.548635</td>
      <td>533.514816</td>
      <td>379.264597</td>
      <td>567.200545</td>
      <td>1</td>
    </tr>
    <tr>
      <th>997</th>
      <td>921.994822</td>
      <td>607.996901</td>
      <td>2065.482529</td>
      <td>497.107790</td>
      <td>457.430427</td>
      <td>1577.506205</td>
      <td>1659.197738</td>
      <td>186.854577</td>
      <td>978.340107</td>
      <td>1943.304912</td>
      <td>1</td>
    </tr>
    <tr>
      <th>998</th>
      <td>1157.069348</td>
      <td>602.749160</td>
      <td>1548.809995</td>
      <td>646.809528</td>
      <td>1335.737820</td>
      <td>1455.504390</td>
      <td>2788.366441</td>
      <td>552.388107</td>
      <td>1264.818079</td>
      <td>1331.879020</td>
      <td>1</td>
    </tr>
    <tr>
      <th>999</th>
      <td>1287.150025</td>
      <td>1303.600085</td>
      <td>2247.287535</td>
      <td>664.362479</td>
      <td>1132.682562</td>
      <td>991.774941</td>
      <td>2007.676371</td>
      <td>251.916948</td>
      <td>846.167511</td>
      <td>952.895751</td>
      <td>1</td>
    </tr>
  </tbody>
</table>
<p>1000 rows × 11 columns</p>
</div>



## Data visualization: 
The code creates a scatter plot matrix using the sns.pairplot method from the seaborn library and plots it using the plt.show method from the matplotlib library. This scatter plot matrix is used to visualize the relationships between the variables in the data.


```python
# scatter plot matrix
sns.pairplot(df, hue='TARGET CLASS')
plt.show()
```


    

![KNN visualization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mfqk27ss51hot3xs1hh.png)
    


## Split the dataset into training and testing sets: 
The code splits the dataset into two parts: training and testing. The train_test_split method from scikit-learn is used to split the data into 80% training data and 20% testing data. The X variable is assigned the values of the dataframe with the target column dropped and y variable is assigned the values of the target column.


```python
# Split the dataset into training and testing sets
X = df.drop("TARGET CLASS", axis=1)
y = df["TARGET CLASS"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```

## Pre-process the data: 
The code scales the data using the StandardScaler method from scikit-learn. The method fit_transform is applied to the training data and transform is applied to the testing data. This scaling is necessary because different features in the data have different ranges, and it is important to pre-process the data before applying a machine learning model.


```python
# Pre-process the data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```

## Training and testing the KNN model: 
The code trains a K-nearest neighbors (KNN) model using the training data and the KNeighborsClassifier method from scikit-learn. The KNN model is then tested using the testing data, and the accuracy of the model is calculated using the accuracy_score method from scikit-learn.


```python
# Train the KNN model
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
```




    KNeighborsClassifier()




```python
# Evaluate the model
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy*100)
```

    Accuracy: 82.0


## GitHub link: [Complete-Data-Science-Bootcamp](https://github.com/anurag629/Complete-Data-Science-Bootcamp)

## Main Post: [Complete-Data-Science-Bootcamp](https://dev.to/anurag629/complete-data-science-roadmap-bootcamp-from-noob-to-expert-4ee2)


<a href="https://www.buymeacoffee.com/anurag629" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>