text_html_output_1.png
from sklearn.neighbors import KNeighborsClassifier

from sklearn.preprocessing import StandardScaler

import numpy as np # linear algebra

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

data = pd.read_csv('../input/diabetes.csv')

y = data['Outcome']
feature_data = data.drop('Outcome', axis=1)

scaled_features = StandardScaler().fit_transform(feature_data.values)
scaled_data = pd.DataFrame(scaled_features, index=feature_data.index, columns=feature_data.columns)

train_scaled = pd.concat([scaled_data, y], axis=1)

def EuclideanD(d1, d2, length):
    distance = 0
    for l in range(length):
        distance += np.square(d1[l] - d2[l])
    return np.sqrt(distance)

def KNN(train, test, k):
    result = []
    length = test.shape[1]
    for y in range(len(test)):
        distances = {}
        sort = {}
        for x in range(len(train)):
            dist = EuclideanD(test.iloc[y], train.iloc[x], length)
            '\n            basically we are iterating over the no. of features by calculating test.shape[1], and in EucliedeanD, we calculate distance \n            for the data point by using Euclidean formula for the respective features of a data point and then return sigma(distance)\n            '
            distances[x] = dist
            sorted_d = sorted(distances.items(), key=lambda item: item[1])
        neighbours = []
        for x in range(k):
            neighbours.append(sorted_d[x][0])
        majorityclassvotes = {}
        for i in range(len(neighbours)):
            response = train.iloc[neighbours[i]][-1]
            if response in majorityclassvotes:
                majorityclassvotes[response] += 1
            else:
                majorityclassvotes[response] = 1
        majorityvotesorted = sorted(majorityclassvotes.items(), key=lambda item: item[1], reverse=True)
        result.append(majorityvotesorted[0][0])
    return result

test_data = [[0.42, 0.8, 0.25, 0.7, -0.12, 0.65, 0.36, 1.9], [-0.3, 0.5, 0.7, 0.2, -0.34, 0.86, 0.56, 2.8]]
test = pd.DataFrame(test_data)
k = 3
result = KNN(train_scaled, test, k)

from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(train_scaled.iloc[:, 0:8], train_scaled['Outcome'])
print(neigh.predict(test))