-
Notifications
You must be signed in to change notification settings - Fork 0
/
K-NN Algorithm.py
72 lines (57 loc) · 1.72 KB
/
K-NN Algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# -*- coding: utf-8 -*-
"""K-NN Algorithm.ipynb
"""
import numpy as np
import pandas as pd
from collections import Counter
from matplotlib import pyplot as plt
from sklearn.datasets.samples_generator import make_blobs
def eculidean_distance(point,k):
euc_distance = np.sqrt(np.sum((X - point)**2, axis=1))
return np.argsort(euc_distance)[0:k]
def predict(prediction_points, k):
points_labels = []
for point in prediction_points:
distances = eculidean_distance(point,k)
results =[]
for index in distances:
results.append(y[index])
label = Counter(results).most_common(1)
points_labels.append([point,label[0][0]])
return points_labels
def get_accuracy(predictions):
error = np.sum((predictions-y)**2)
accuracy = 100 - (error/len(y)) *100
return accuracy
# Implement
X, y = make_blobs(
n_samples=100, n_features=2, centers=2,cluster_std=7,
random_state=2020)
X = pd.DataFrame(X)
y = pd.DataFrame(y)
print(f'Independent Variable X : \n{X}')
print(f'Dependent Variable y : \n{y}')
prediction_points = [[-6,15],[-3,4],[-15,5,],[-2,5],[-9,10],[0,-10]]
prediction_points = np.array(prediction_points)
print(f'Point For Predictions :\n{prediction_points}')
results = predict(prediction_points,4)
print(f'Results :\n{results}')
"""# Check Accuracy"""
accu = []
for k in range(1,10):
results = predict(X,k)
predicitions = []
for result in results:
predicitions.append(result[1])
accu.append([get_accuracy(predicitions), k])
print(f'Accuracy :\n{accu}')
accuracy = []
k = []
for a in accu:
k.append(a[1])
accuracy.append(a[0])
plt.figure(figsize=(10,5))
plt.plot(k,accuracy)
plt.xlabel('K-Value')
plt.ylabel('Accuracy')
plt.show()