MCPcopy Create free account
hub / github.com/lazyprogrammer/machine_learning_examples / predict

Method predict

supervised_class/knn.py:30–60  ·  view source on GitHub ↗
(self, X)

Source from the content-addressed store, hash-verified

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)

Callers 3

scoreMethod · 0.95
postMethod · 0.45
regression.pyFile · 0.45

Calls 1

getMethod · 0.80

Tested by

no test coverage detected