<jupyter_start><jupyter_text>KNN Algorithm and implementation using heart.csv file<jupyter_code># Initialization
import pandas as pd
import numpy as np
heart = pd.read_csv("heart.csv");
heart.head(5)
def calculateDistance(targetRow, rows, columns):
    result = []
    for i in range(0, len(rows)):
        sumArr = []
        for column in columns:
            sumArr.append(abs(targetRow[column] - rows.iloc[i][column]))
        result.append({
            "sum": np.sum(sumArr),
            "indice": i
        })
    return result
h_train = heart.drop(columns=["target"])
h_train.head(5)
# for i in range(0, len(h_train)):
#     print(sorted(calculateDistance(h_train.iloc[i], h_train, h_train.columns), key=lambda k: k["sum"])[0:k])
def getKNNTargets(test, train, k = 3):
    target = []
    for i in range(0, len(test)):
        # calculate distances for first k rows
        srtArr = sorted(calculateDistance(test.iloc[i], train, test.columns), key=lambda k: k["sum"])[:k]
        indices = list(map(lambda x: x["indice"], srtArr)) # first k labels
        kTargetLabels = [train.iloc[x]["target"] for x in indices];
        # We take mode cause our target label is in discrete form (classification)
        mode = max(set(kTargetLabels), key=kTargetLabels.count)
        # pick index of the most frequent (mode) label
        labelIndex = kTargetLabels.index(mode)
        print(f"Mode: {mode}")
#         print(kTargetLabels)
        res = {
            "row": i,
            "target": train.iloc[indices[labelIndex]]["target"] # use the label of most frequent target label
        }
        print(res)
        target.append(res)
    return target
testRange = int(len(heart)/2)
KNN = getKNNTargets(heart.drop(columns=["target"]).iloc[:testRange], heart.iloc[testRange:])
KNNResultWTarger = heart.iloc[testRange:]
correct = 0
for i in range(0, len(KNN)):
    if KNN[i]["target"] == KNNResultWTarger.iloc[i]["target"]:
        correct += 1

accuracy = correct/len(KNN)
from math import ceil
print(f"Accuracy: {(ceil(accuracy*100))}%")<jupyter_output>Accuracy: 85%
{'fraction_non_alphanumeric': 0.14347826086956522, 'fraction_numerical': 0.007729468599033816, 'mean_word_length': 3.369198312236287, 'pattern_counts': {'":': 4, '<': 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': '411346', 'license': 'Apache-2.0', 'n_tokens_mistral': 695, 'n_tokens_neox': 680, 'n_words': 168, 'path': 'KNN.ipynb', 'repo_name': 'm-yasir/knn-implementation', 'size': '2070'}