Skip to content

Fix classification predictions with non-numeric class labels - #830

Open
TemRevil wants to merge 2 commits into
elastic:mainfrom
TemRevil:fix/classification-string-class-labels
Open

TemRevil wants to merge 2 commits into
elastic:mainfrom
TemRevil:fix/classification-string-class-labels

Conversation

@TemRevil

@TemRevil TemRevil commented Aug 3, 2026

Copy link
Copy Markdown

Closes #434.

predict() always casts classification results to np.int_, which blows up for any classifier trained on non-numeric class labels. The iris dataset's species names are the obvious example:

ValueError: invalid literal for int() with base 10: 'setosa'

Fix tries the np.int_ cast first, then falls back to letting numpy infer the dtype if that cast raises. Kept the try-first order on purpose: turns out Elasticsearch can return numeric class labels as numeric-looking strings (depending on how the model got serialized), so a plain "is this a string" check would have broken the existing int-labeled classifier tests. Found that out the hard way while testing this against a real cluster.

Verified against a real Elasticsearch 9.2.0 instance, not mocked:

  • Trained a RandomForestClassifier on iris with the actual string species names, imported it, watched predict() throw the ValueError above pre-fix, then confirmed it returns string predictions matching sklearn's own output post-fix.
  • Ran the existing test_decision_tree_classifier cases (all 4 parametrizations) to make sure numeric-labeled classifiers still come back as np.int_. No regression there.
  • Added test_decision_tree_classifier_string_class_labels next to them, same pattern, covering the case from the issue.

Also fixed the predict() docstring, it still claimed results are always float or int.

MLModel.predict() always cast classification results to np.int_, which
raises a ValueError for any classifier trained on string class labels
(e.g. the standard iris dataset's species names). Try the int cast
first for backward compatibility, since Elasticsearch can return
numeric class labels as numeric-looking strings, and only fall back to
letting numpy infer the dtype when the cast actually fails.

Fixes elastic#434
@cla-checker-service

cla-checker-service Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

💚 CLA has been signed

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong type-casting for prediction of classification models

1 participant