Thanks to visit codestin.com
Credit goes to github.com

Skip to content

MAINT Do not compute distances for uniform weighting for knn-based estimators' predictions #22280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions sklearn/neighbors/_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,14 @@ def predict(self, X):
y : ndarray of shape (n_queries,) or (n_queries, n_outputs)
Class labels for each data sample.
"""
neigh_dist, neigh_ind = self.kneighbors(X)
if self.weights == "uniform":
# In that case, we do not need the distances to perform
# the weighting so we do not compute them.
neigh_ind = self.kneighbors(X, return_distance=False)
neigh_dist = None
else:
neigh_dist, neigh_ind = self.kneighbors(X)

classes_ = self.classes_
_y = self._y
if not self.outputs_2d_:
Expand Down Expand Up @@ -255,7 +262,13 @@ def predict_proba(self, X):
The class probabilities of the input samples. Classes are ordered
by lexicographic order.
"""
neigh_dist, neigh_ind = self.kneighbors(X)
if self.weights == "uniform":
# In that case, we do not need the distances to perform
# the weighting so we do not compute them.
neigh_ind = self.kneighbors(X, return_distance=False)
neigh_dist = None
else:
neigh_dist, neigh_ind = self.kneighbors(X)

classes_ = self.classes_
_y = self._y
Expand Down
8 changes: 7 additions & 1 deletion sklearn/neighbors/_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,13 @@ def predict(self, X):
y : ndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int
Target values.
"""
neigh_dist, neigh_ind = self.kneighbors(X)
if self.weights == "uniform":
# In that case, we do not need the distances to perform
# the weighting so we do not compute them.
neigh_ind = self.kneighbors(X, return_distance=False)
neigh_dist = None
else:
neigh_dist, neigh_ind = self.kneighbors(X)

weights = _get_weights(neigh_dist, self.weights)

Expand Down