text_plain_output_1.png
import numpy as np # linear algebra

import operator

import pandas as pd

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

train_x = pd.read_csv('/kaggle/input/iris/Iris.csv')

def euclidian_distance(row1, row2, length):
    distance = 0
    for x in range(length):
        distance += np.square(row1[x] - row2[x])
    return np.sqrt(distance)

def get_neighbors(dataset, sorted_distances, k):
    neighbors = []
    for x in range(k):
        neighbors.append(sorted_distances[x][0])
    return neighbors

def get_sorted_distances(dataset, testInstance):
    distances = {}
    for x in range(len(dataset)):
        dist = euclidian_distance(testInstance, dataset.iloc[x], testInstance.shape[1])
        distances[x] = dist[0]
    sorted_distances = sorted(distances.items(), key=operator.itemgetter(1))
    return sorted_distances

def get_sorted_votes(dataset, neighbors):
    class_votes = {}
    for x in range(len(neighbors)):
        response = dataset.iloc[neighbors[x]][-1]
        if response in class_votes:
            class_votes[response] += 1
        else:
            class_votes[response] = 1
    sorted_votes = sorted(class_votes.items(), key=operator.itemgetter(1), reverse=True)
    return sorted_votes

def knn(dataset, testInstance, k):
    sorted_distances = get_sorted_distances(dataset, testInstance)
    neighbors = get_neighbors(dataset, sorted_distances, k)
    sorted_votes = get_sorted_votes(dataset, neighbors)
    return (sorted_votes[0][0], neighbors)

iris = train_x[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm', 'Species']]

row = pd.DataFrame([list(iris.iloc[0].to_numpy()[0:-1])])

result = []
for i in range(len(iris)):
    row = pd.DataFrame([list(iris.iloc[i].to_numpy()[0:-1])])
    result.append(knn(iris, row, 3))

result