| 9 | |
| 10 | |
| 11 | class KNNBase(BaseEstimator): |
| 12 | def __init__(self, k=5, distance_func=euclidean): |
| 13 | """Base class for Nearest neighbors classifier and regressor. |
| 14 | |
| 15 | Parameters |
| 16 | ---------- |
| 17 | k : int, default 5 |
| 18 | The number of neighbors to take into account. If 0, all the |
| 19 | training examples are used. |
| 20 | distance_func : function, default euclidean distance |
| 21 | A distance function taking two arguments. Any function from |
| 22 | scipy.spatial.distance will do. |
| 23 | """ |
| 24 | |
| 25 | self.k = None if k == 0 else k # l[:None] returns the whole list |
| 26 | self.distance_func = distance_func |
| 27 | |
| 28 | def aggregate(self, neighbors_targets): |
| 29 | raise NotImplementedError() |
| 30 | |
| 31 | def _predict(self, X=None): |
| 32 | predictions = [self._predict_x(x) for x in X] |
| 33 | |
| 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): |
nothing calls this directly
no outgoing calls
no test coverage detected