Repository navigation
Closed
Labels
Description
Describe the bug
When used with algorithm="brute" (or algorithm="auto" and the heuristic suggests brute force) and p = 1, KNeighborsClassifier.predict crashes when y labels are non-integers.
Note that this only crashes for this specific param combination, and p=2, for example, works fine with non-integer labels.
This happens because self.classes_ is passed to unique_Y_labels here:
| unique_Y_labels=self.classes_, |
And the docs for ArgKminClassMode.compute say:
unique_Y_labels : ndarray
An array containing all unique indices contained in the
corresponding `Y_labels` array.
while self.classes_ contains actual values, not indices.
Steps/Code to Reproduce
import random
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
# generate random data
rng = np.random.default_rng()
x = rng.normal(size=(5, 3))
y = random.choices(['foo', 'bar'], k=5)
kn = KNeighborsClassifier(algorithm='brute', p=1)
kn = kn.fit(x, y)
kn.predict(rng.normal(size=(2, 3)))Expected Results
No error.
Actual Results
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/home/stas/Documents/Work/polymerize/ml_dev/.venv/lib/python3.11/site-packages/sklearn/neighbors/_classification.py", line 266, in predict
probabilities = self.predict_proba(X)
^^^^^^^^^^^^^^^^^^^^^
File "/home/stas/Documents/Work/polymerize/ml_dev/.venv/lib/python3.11/site-packages/sklearn/neighbors/_classification.py", line 352, in predict_proba
probabilities = ArgKminClassMode.compute(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/stas/Documents/Work/polymerize/ml_dev/.venv/lib/python3.11/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py", line 589, in compute
unique_Y_labels=np.array(unique_Y_labels, dtype=np.intp),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: np.str_('bar')Versions
System:
python: 3.11.14 (main, Dec 9 2025, 19:02:23) [Clang 21.1.4 ]
executable: /home/stas/Documents/Work/polymerize/ml_dev/.venv/bin/python
machine: Linux-6.14.0-37-generic-x86_64-with-glibc2.39
Python dependencies:
sklearn: 1.8.0
pip: None
setuptools: None
numpy: 2.4.0
scipy: 1.16.3
Cython: None
pandas: 2.3.1
matplotlib: 3.10.8
joblib: 1.5.3
threadpoolctl: 3.6.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
num_threads: 4
prefix: libscipy_openblas
filepath: /home/stas/Documents/Work/polymerize/ml_dev/.venv/lib/python3.11/site-packages/numpy.libs/libscipy_openblas64_-fdde5778.so
version: 0.3.30
threading_layer: pthreads
architecture: Haswell
user_api: blas
internal_api: openblas
num_threads: 4
prefix: libscipy_openblas
filepath: /home/stas/Documents/Work/polymerize/ml_dev/.venv/lib/python3.11/site-packages/scipy.libs/libscipy_openblas-b75cc656.so
version: 0.3.29.dev
threading_layer: pthreads
architecture: Haswell
user_api: openmp
internal_api: openmp
num_threads: 4
prefix: libgomp
filepath: /home/stas/Documents/Work/polymerize/ml_dev/.venv/lib/python3.11/site-packages/scikit_learn.libs/libgomp-e985bcbb.so.1.0.0
version: None
Activity
sterliakov commentedon Jan 9, 2026
FWIW looks like
ArgKminClassMode64.computedoes not really care aboutunique_Y_labelsvalues, that could be justnp.zeros_like(unique_Y_labels, dtype=np.intp), for example - it only uses the shape? Then it can be removed completely, only passing the total count of classes instead.AAAZZZR commentedon Jan 12, 2026
As discussed, the crash happens because unique_Y_labels receives raw string labels from self.classes_, but the underlying ArgKminClassMode implementation expects integer types (even if it only uses the shape).
I've implemented a fix using np.arange(len(self.classes_), dtype=np.intp) to pass the correct indices, which solves the crash without modifying the Cython extensions.
I'm working on the PR and will submit it shortly.
AAAZZZR commentedon Jan 12, 2026
Apologies, I am a new contributor and I didn't notice the rule about waiting for the 'Needs Triage' label to be removed. I just wanted to help fix the crash. Please let me know if I need to adjust anything.
ogrisel commentedon Jan 16, 2026
I agree this is a bug. The docstring of the
ArgKminClassMode.computemethod states thatY_labelsis "An array containing the index of the class membership of the associated samples inY. This is used in labelingX."So both
Y_labelsandunique_Y_labelsare expected to be encoded as integers prior to passing them toArgKminClassMode.compute.EDIT: I confirm that
self._yis always manually integer encoded at fit time in the base class:scikit-learn/sklearn/neighbors/_base.py
Lines 506 to 509 in b764229
unique_Y_labelsvalues is inconsistent.sterliakov commentedon Jan 16, 2026
Yes, that matches my observations. Looking at
ArgKminClassModeimplementation, it seems like this array can be avoided altogether, it only looks at its.shape[0]- passing just a number of classes could be more efficient?Crescens-beep commentedon Feb 9, 2026
Hi! I'm interested in working on this issue as part of my preparation for GSoC.
I've reproduced the bug and understand the problem -
self.classes_contains actual label values butArgKminClassMode.computeexpects label indices. The fix would likely involve passingnp.arange(len(self.classes_))or usingnp.searchsortedto convert labels to indices before passing to the function.Would it be possible to assign this issue to me? I'm familiar with scikit-learn's contribution guidelines and ready to submit a PR with tests.
Thank you!