-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfknn.py
133 lines (94 loc) · 2.97 KB
/
fknn.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import operator
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.base import BaseEstimator, ClassifierMixin
class FuzzyKNN(BaseEstimator, ClassifierMixin):
def __init__(self, k=3, plot=False):
self.k = k
self.plot = plot
def fit(self, X, y=None):
self._check_params(X,y)
self.X = X
self.y = y
self.xdim = len(self.X[0])
self.n = len(y)
classes = list(set(y))
classes.sort()
self.classes = classes
self.df = pd.DataFrame(self.X)
self.df['y'] = self.y
self.memberships = self._compute_memberships()
self.df['membership'] = self.memberships
self.fitted_ = True
return self
def predict(self, X):
if self.fitted_ == None:
raise Exception('predict() called before fit()')
else:
m = 2
y_pred = []
for x in X:
neighbors = self._find_k_nearest_neighbors(pd.DataFrame.copy(self.df), x)
votes = {}
for c in self.classes:
den = 0
for n in range(self.k):
dist = np.linalg.norm(x - neighbors.iloc[n,0:self.xdim])
den += 1 / (dist ** (2 / (m-1)))
neighbors_votes = []
for n in range(self.k):
dist = np.linalg.norm(x - neighbors.iloc[n,0:self.xdim])
num = (neighbors.iloc[n].membership[c]) / (dist ** (2 / (m-1)))
vote = num/den
neighbors_votes.append(vote)
votes[c] = np.sum(neighbors_votes)
pred = max(votes.items(), key=operator.itemgetter(1))[0]
y_pred.append((pred, votes))
return y_pred
def score(self, X, y):
if self.fitted_ == None:
raise Exception('score() called before fit()')
else:
predictions = self.predict(X)
y_pred = [t[0] for t in predictions]
confidences = [t[1] for t in predictions]
return accuracy_score(y_pred=y_pred, y_true=y)
def _find_k_nearest_neighbors(self, df, x):
X = df.iloc[:,0:self.xdim].values
df['distances'] = [np.linalg.norm(X[i] - x) for i in range(self.n)]
df.sort_values(by='distances', ascending=True, inplace=True)
neighbors = df.iloc[0:self.k]
return neighbors
def _get_counts(self, neighbors):
groups = neighbors.groupby('y')
counts = {group[1]['y'].iloc[0]:group[1].count()[0] for group in groups}
return counts
def _compute_memberships(self):
memberships = []
for i in range(self.n):
x = self.X[i]
y = self.y[i]
neighbors = self._find_k_nearest_neighbors(pd.DataFrame.copy(self.df), x)
counts = self._get_counts(neighbors)
membership = dict()
for c in self.classes:
try:
uci = 0.49 * (counts[c] / self.k)
if c == y:
uci += 0.51
membership[c] = uci
except:
membership[c] = 0
memberships.append(membership)
return memberships
def _check_params(self, X, y):
if type(self.k) != int:
raise Exception('"k" should have type int')
if self.k >= len(y):
raise Exception('"k" should be less than no of feature sets')
if self.k % 2 == 0:
raise Exception('"k" should be odd')
if type(self.plot) != bool:
raise Exception('"plot" should have type bool')