Skip to content

KNeighborsClassifier fails on non-numeric labels with ValueError on certain parameters combination #33034

Closed

Description

@sterliakov

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

  1. added
    Needs Triage
    on Jan 9, 2026
  2. sterliakov commented on Jan 9, 2026

    @sterliakov
    ContributorAuthor

    FWIW looks like ArgKminClassMode64.compute does not really care about unique_Y_labels values, that could be just np.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.

  3. AAAZZZR commented on Jan 12, 2026

    @AAAZZZR
    Contributor

    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.

  4. AAAZZZR commented on Jan 12, 2026

    @AAAZZZR
    Contributor

    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.

  5. removed
    Needs Triage
    on Jan 16, 2026
  6. ogrisel commented on Jan 16, 2026

    @ogrisel
    Member

    I agree this is a bug. The docstring of the ArgKminClassMode.compute method states that Y_labels is "An array containing the index of the class membership of the associated samples in Y. This is used in labeling X."

    So both Y_labels and unique_Y_labels are expected to be encoded as integers prior to passing them to ArgKminClassMode.compute.

    EDIT: I confirm that self._y is always manually integer encoded at fit time in the base class:

    self._y = np.empty(y.shape, dtype=np.intp)
    for k in range(self._y.shape[1]):
    classes, self._y[:, k] = np.unique(y[:, k], return_inverse=True)
    self.classes_.append(classes)
    . So passing raw labels in the unique_Y_labels values is inconsistent.

  7. sterliakov commented on Jan 16, 2026

    @sterliakov
    ContributorAuthor

    Yes, that matches my observations. Looking at ArgKminClassMode implementation, 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?

  8. Crescens-beep commented on Feb 9, 2026

    @Crescens-beep

    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 but ArgKminClassMode.compute expects label indices. The fix would likely involve passing np.arange(len(self.classes_)) or using np.searchsorted to 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions