Predict the label of a single instance x.
(self, x)
| 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 | |
| 55 | class KNNClassifier(KNNBase): |