Repository navigation
Fix ValueError in KNeighborsClassifier with brute force and p=1 - #33048
Conversation
ogrisel
left a comment
There was a problem hiding this comment.
Thanks for the PR. From my analysis in the upstream issue, this fix sounds correct to me. Here is some feedback on the changelog entry and the test:
| @@ -0,0 +1 @@ | |||
| Fixed a :class:~sklearn.neighbors.KNeighborsClassifier failure when using algorithm='brute', p=1 and string labels. | |||
There was a problem hiding this comment.
This entry should be edited to follow the instructions in:
| assert_allclose(loocv, nn_model.predict(None)) | ||
|
|
||
|
|
||
| def test_kneighbors_classifier_brute_manhattan_string_labels(): |
There was a problem hiding this comment.
Rather than specialize this test for the Manhattan distance metric, let's check that KNC works with string labels for any combination of algorithm and metric.
| def test_kneighbors_classifier_brute_manhattan_string_labels(): | |
| @pytest.mark.parametrize("metric", COMMON_VALID_METRICS + DISTANCE_METRIC_OBJS) | |
| @pytest.mark.parametrize("algorithm", ALGORITHMS) | |
| def test_kneighbors_classifier_with_string_labels(metric, algorithm): |
|
You might need to sync this branch with |
|
@AAAZZZR please update the PR with the feedback above. You might even take the following comment into account to implement a better fix: #33034 (comment), but the previous review feedback would still hold. |
|
|
| weights=self.weights, | ||
| Y_labels=self._y, | ||
| unique_Y_labels=self.classes_, | ||
| unique_Y_labels=np.arange(len(self.classes_), dtype=np.intp), |
There was a problem hiding this comment.
Could apply the same fix to RadiusNeighborsClassMode.compute below.
extend test for all metrics
jeremiedbb
left a comment
There was a problem hiding this comment.
I extended the test for all metrics and fixed RadiusNeighbors as well.
Radiusneighbors uses the unique_Y_labels values so I kept it for consistency. We can still revisit the idea of a refactoring later.
LGTM
Reference Issues/PRs
Fixes #33034
What does this implement/fix? Explain your changes.
When using
KNeighborsClassifierwithalgorithm="brute"andp=1(Manhattan distance), the code path utilizesArgKminClassMode. Previously,self.classes_(which can contain strings) was passed directly to theunique_Y_labelsargument of the Cython method, causing aValueErrorwhen it attempted to interpret strings as integers.I have updated the call to pass
np.arange(len(self.classes_), dtype=np.intp)instead, which provides the correct integer indices expected by the underlying Cython implementation.Any other comments?
Added a regression test case in
sklearn/neighbors/tests/test_neighbors.py.