| 20 | |
| 21 | |
| 22 | class KNN(object): |
| 23 | def __init__(self, k): |
| 24 | self.k = k |
| 25 | |
| 26 | def fit(self, X, y): |
| 27 | self.X = X |
| 28 | self.y = y |
| 29 | |
| 30 | def predict(self, X): |
| 31 | y = np.zeros(len(X)) |
| 32 | for i,x in enumerate(X): # test points |
| 33 | sl = SortedList() # stores (distance, class) tuples |
| 34 | for j,xt in enumerate(self.X): # training points |
| 35 | diff = x - xt |
| 36 | d = diff.dot(diff) |
| 37 | if len(sl) < self.k: |
| 38 | # don't need to check, just add |
| 39 | sl.add( (d, self.y[j]) ) |
| 40 | else: |
| 41 | if d < sl[-1][0]: |
| 42 | del sl[-1] |
| 43 | sl.add( (d, self.y[j]) ) |
| 44 | # print "input:", x |
| 45 | # print "sl:", sl |
| 46 | |
| 47 | # vote |
| 48 | votes = {} |
| 49 | for _, v in sl: |
| 50 | # print "v:", v |
| 51 | votes[v] = votes.get(v,0) + 1 |
| 52 | # print "votes:", votes, "true:", Ytest[i] |
| 53 | max_votes = 0 |
| 54 | max_votes_class = -1 |
| 55 | for v,count in iteritems(votes): |
| 56 | if count > max_votes: |
| 57 | max_votes = count |
| 58 | max_votes_class = v |
| 59 | y[i] = max_votes_class |
| 60 | return y |
| 61 | |
| 62 | def score(self, X, Y): |
| 63 | P = self.predict(X) |
| 64 | return np.mean(P == Y) |
| 65 | |
| 66 | |
| 67 | if __name__ == '__main__': |
no outgoing calls
no test coverage detected