<jupyter_start><jupyter_text>Importing required packages<jupyter_code>import numpy as np
import pandas as pd
from collections import Counter
class knn:
    
    # Intializing k 
    def __init__(self,k = 10):
        self.k = k
        print("Initalized k with :",k)
        
    # Finding distance between 2 data points to find the similarity
    def euclidDistance(self , x1, x2):
        return (np.sqrt(np.sum(np.square(x1 - x2))))
    
    #Finding nearest neighbors
    def predict(self, trainData, labels , testPoint):
        distances = {}
        
        # calculating distance of data point from each point in dataset
        for i in range(len(trainData)):
            distances[i] = self.euclidDistance(trainData.iloc[i] , testPoint)
        
        # selecting the "k" nearest points
        neighbors = sorted(distances.items(), key = lambda kv:(kv[1], kv[0]))[:self.k]
        neighborLabels = []
        
        # getting labels of the "k" nearest points
        for neigh in neighbors:
            neighborLabels.append(labels[neigh[0]])
        
        outputClass = Counter(neighborLabels)
        print("The given data point belongs to :",max(outputClass))
file = './iris.csv'
trainData = pd.read_csv(file)
trainData.head()
model = knn(15)
dataPoint = [1,5,2,4]
features = trainData.iloc[:,:-1]
target = trainData.iloc[:,-1]
model.predict(features, target , dataPoint)<jupyter_output>The given data point belongs to : setosa
{'fraction_non_alphanumeric': 0.1090407177363699, 'fraction_numerical': 0.012422360248447204, 'mean_word_length': 2.8157894736842106, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '80742', 'license': 'MIT', 'n_tokens_mistral': 448, 'n_tokens_neox': 441, 'n_words': 125, 'path': 'K-NearestNeighbor/K-NearestNeighbor.ipynb', 'repo_name': 'TarunNanduri/Artificial-Intelligence', 'size': '1449'}