MCPcopy Create free account
hub / github.com/rushter/MLAlgorithms / _predict_x

Method _predict_x

mla/knn.py:36–52  ·  view source on GitHub ↗

Predict the label of a single instance x.

(self, x)

Source from the content-addressed store, hash-verified

34 return np.array(predictions)
35
36 def _predict_x(self, x):
37 """Predict the label of a single instance x."""
38
39 # compute distances between x and all examples in the training set.
40 distances = (self.distance_func(x, example) for example in self.X)
41
42 # Sort all examples by their distance to x and keep their target value.
43 neighbors = sorted(
44 ((dist, target) for (dist, target) in zip(distances, self.y)),
45 key=lambda x: x[0],
46 )
47
48 # Get targets of the k-nn and aggregate them (most common one or
49 # average).
50 neighbors_targets = [target for (_, target) in neighbors[: self.k]]
51
52 return self.aggregate(neighbors_targets)
53
54
55class KNNClassifier(KNNBase):

Callers 1

_predictMethod · 0.95

Calls 1

aggregateMethod · 0.95

Tested by

no test coverage detected