Skip to content

FIX convert integer X to float in mixture inference methods - #35609

Open
un1u3 wants to merge 1 commit into
scikit-learn:mainfrom
un1u3:fix-gmm-integer-input
Open

un1u3 wants to merge 1 commit into
scikit-learn:mainfrom
un1u3:fix-gmm-integer-input

Conversation

@un1u3

@un1u3 un1u3 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Reference Issues/PRs

closes #35583

What does this implement/fix? Explain your changes.

fit validates X with dtype=[xp.float64, xp.float32], but score_samples,
predict and predict_proba call validate_data(self, X, reset=False) without a
dtype, so integer X stays integer. With covariance_type="full",
_estimate_log_gaussian_prob allocates log_prob with dtype=X.dtype, so the
squared Mahalanobis distances are truncated to integers. This gives wrong
score_samples, score and bic/aic, and can change predict and
predict_proba.

import numpy as np
from sklearn.mixture import GaussianMixture

rng = np.random.RandomState(0)
X = np.r_[rng.randint(0, 8, (40, 2)), rng.randint(5, 14, (40, 2))]
m = GaussianMixture(n_components=2, random_state=0).fit(X)

print(m.bic(X), m.bic(X.astype(float)))
print(m.score(X), m.score(X.astype(float)))

On main:

839.0390007466375 872.5069400975487
-4.942729423532655 -5.151904044475851

With this PR(1.10.dev0)
image

The fix passes the same dtype to validate_data in the three inference
methods, so inference converts X the same way fit does. score goes through
score_samples, and BayesianGaussianMixture shares BaseMixture, so both are
covered. Fixing the validation step, rather than the allocation in
_estimate_log_gaussian_prob, fixes the root cause: inference should see the
same input dtype as fit.

-        X = validate_data(self, X, reset=False)
+        xp, _ = get_namespace(X)
+        X = validate_data(self, X, dtype=[xp.float64, xp.float32], reset=False)

Float input is unchanged: float32 and float64 pass through as before.

The new test in test_mixture.py checks that both estimators, with all four
covariance types, give the same score_samples, predict_proba and predict
for integer X and the same data as float64. Without the fix, the two "full"
cases fail.

Introduce yourself

Hello, I am Unique. I use scikit-learn to build machine learning systems and quickly experiment with my ideas. I have contributed to scikit-learn before (#33117, #33118), and I fixed this too..

AI usage disclosure

I used AI assistance for:

  • Test/benchmark generation
  • Research and understanding
  • To check if code can be more optimized
  • To enhance the writing of this pr

Any other comments?

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GaussianMixture returns wrong scores and probabilities for integer X since 1.7

1 participant