Repository navigation
Description
Describe the bug
The Gaussian Mixture implementation shows numerical instabilities on single-precision floating point input numbers, that even large values of the regularization parameter reg_covar (like 0.1) cannot mitigate.
More specifically, diagonal covariance elements must not be negative. However, due to the numerical instabilities intrinsic to floating point arithmetic, they might end up being tiny negative numbers that reg_covar must compensate.
It turns out that, for some input float32 , the covariance can reach the unreasonable value of -0.99999979.
This is because squaring float32 numbers significantly magnifies their precision errors.
The proposed solution consists in converting float32 values to float64 before squaring them.
Care must be taken to not increase memory consumption in the overall process.
Hence, as avgX_means is equal to avg_means2, the return value can be simplified.
Steps/Code to Reproduce
import numpy as np
from sklearn.mixture import GaussianMixture
model = GaussianMixture(n_components=2, covariance_type="spherical", reg_covar=0.1)
model.fit(np.array([[9999.0], [0.0]], dtype=np.float32))
model.covariances_Expected Results
array([0.1, 0.1])Actual Results
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [132], in <cell line: 49>()
45 skgm._estimate_gaussian_covariances_diag = _optimized_estimate_gaussian_covariances_diag
48 model = GaussianMixture(n_components=2,covariance_type="spherical", reg_covar=0.1)
---> 49 model.fit(np.array([[9999.0], [0.0]], dtype=np.float32))
50 model.covariances_
File [~\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\mixture\_base.py:200](http://localhost:8888/lab/tree/~/AppData/Local/Programs/Python/Python39/lib/site-packages/sklearn/mixture/_base.py#line=199), in BaseMixture.fit(self, X, y)
174 def fit(self, X, y=None):
175 """Estimate model parameters with the EM algorithm.
176
177 The method fits the model ``n_init`` times and sets the parameters with
(...)
198 The fitted mixture.
199 """
--> 200 self.fit_predict(X, y)
201 return self
File [~\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\mixture\_base.py:253](http://localhost:8888/lab/tree/~/AppData/Local/Programs/Python/Python39/lib/site-packages/sklearn/mixture/_base.py#line=252), in BaseMixture.fit_predict(self, X, y)
250 self._print_verbose_msg_init_beg(init)
252 if do_init:
--> 253 self._initialize_parameters(X, random_state)
255 lower_bound = -np.inf if do_init else self.lower_bound_
257 if self.max_iter == 0:
File [~\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\mixture\_base.py:160](http://localhost:8888/lab/tree/~/AppData/Local/Programs/Python/Python39/lib/site-packages/sklearn/mixture/_base.py#line=159), in BaseMixture._initialize_parameters(self, X, random_state)
155 else:
156 raise ValueError(
157 "Unimplemented initialization method '%s'" % self.init_params
158 )
--> 160 self._initialize(X, resp)
File [~\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\mixture\_gaussian_mixture.py:723](http://localhost:8888/lab/tree/~/AppData/Local/Programs/Python/Python39/lib/site-packages/sklearn/mixture/_gaussian_mixture.py#line=722), in GaussianMixture._initialize(self, X, resp)
721 if self.precisions_init is None:
722 self.covariances_ = covariances
--> 723 self.precisions_cholesky_ = _compute_precision_cholesky(
724 covariances, self.covariance_type
725 )
726 elif self.covariance_type == "full":
727 self.precisions_cholesky_ = np.array(
728 [
729 linalg.cholesky(prec_init, lower=True)
730 for prec_init in self.precisions_init
731 ]
732 )
File [~\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\mixture\_gaussian_mixture.py:347](http://localhost:8888/lab/tree/~/AppData/Local/Programs/Python/Python39/lib/site-packages/sklearn/mixture/_gaussian_mixture.py#line=346), in _compute_precision_cholesky(covariances, covariance_type)
345 else:
346 if np.any(np.less_equal(covariances, 0.0)):
--> 347 raise ValueError(estimate_precision_error_message)
348 precisions_chol = 1.0 / np.sqrt(covariances)
349 return precisions_chol
ValueError: Fitting the mixture model failed because some components have ill-defined empirical covariance (for instance caused by singleton or collapsed samples). Try to decrease the number of components, or increase reg_covar.Versions
System:
python: 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)]
executable: C:\Users\leonce.mekinda\AppData\Local\Programs\Python\Python39\python.exe
machine: Windows-10-10.0.19043-SP0
Python dependencies:
sklearn: 1.1.1
pip: 22.0.4
setuptools: 58.1.0
numpy: 1.22.4
scipy: 1.8.1
Cython: 0.29.30
pandas: 1.4.3
matplotlib: 3.5.2
joblib: 1.1.0
threadpoolctl: 3.1.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
prefix: libopenblas
filepath: C:\Users\leonce.mekinda\AppData\Local\Programs\Python\Python39\Lib\site-packages\numpy\.libs\libopenblas.EL2C6PLE4ZYW3ECEVIV3OXXGRN2NRFM2.gfortran-win_amd64.dll
version: 0.3.18
threading_layer: pthreads
architecture: Haswell
num_threads: 12
user_api: openmp
internal_api: openmp
prefix: vcomp
filepath: C:\Users\leonce.mekinda\AppData\Local\Programs\Python\Python39\Lib\site-packages\sklearn\.libs\vcomp140.dll
version: None
num_threads: 12
user_api: blas
internal_api: openblas
prefix: libopenblas
filepath: C:\Users\leonce.mekinda\AppData\Local\Programs\Python\Python39\Lib\site-packages\scipy\.libs\libopenblas.XWYDX2IKJW2NMTWSFYNGFUWKQU3LYTCZ.gfortran-win_amd64.dll
version: 0.3.17
threading_layer: pthreads
architecture: Haswell
num_threads: 12Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsNo status
Activity
ogrisel commentedon Dec 3, 2024
Thanks for the report.
For information, I updated the description is use the markdown delimiter for the verbatim code blocks to make it more readable.
It seems that in this case, we use
_estimate_gaussian_covariances_sphericalthat directly calls into_estimate_gaussian_covariances_diagwhich does the following:scikit-learn/sklearn/mixture/_gaussian_mixture.py
Lines 209 to 232 in 8ded7f4
So there is indeed a possibility for catastrophic cancellation.
Converting to float64 might help, but if one we want to adapt this code to work with array API on GPU devices, some devices might not support float64 operation (e.g. the built-in GPUs of macOS machines).
However the code looks like:
and I was wondering if computing the left hand side instead of the right hand size wouldn't be more numerically stable. But this does not actually match. In particular this is not exactly the same as:
because the responsibility weights are not simple scalar weights. So maybe it's not possible to do the factored computation.
ogrisel commentedon Dec 3, 2024
As an alternative, I tried to clip negative values in #30401, and it seems to fix your reproducer. The existing tests still pass locally. Let's see on the CI.
ogrisel commentedon Dec 3, 2024
/ping @jeremiedbb if you have better suggestions.
mekleo commentedon Dec 3, 2024
Thank you for taking care of it.
Using float (alias to np.float64) instead of float64 would be supported on 32-bit platforms as well, and provide the floating point double-precision of all the other computations on 64-bit platforms:
Note that avg_X_means is exactly avg_means2. This is why this term can be removed and the returned value simplified
to return np.clip(avg_X2 - avg_means2, 0, None )+ reg_covar
Returning ((resp.T @ X) / nk[:, np.newaxis] - means) ** 2 would not be correct because the responsibility matrix must not be squared.
ogrisel commentedon Dec 4, 2024
Yes, on the CPU, but not with PyTorch tensors on
mpsdevices (if we ever convert this estimator to support the array API):mekleo commentedon Dec 4, 2024
ogrisel commentedon Dec 4, 2024
I don't think this is true: I tried your suggestion and many existing tests fail.
ogrisel commentedon Dec 4, 2024
I would rather not use implicit precision levels in the source code. But, in this particular case, this does not change anything: Python
floatare promoted tofloat64both by NumPy and Pytorch:And even putting potential array API / torch support aside, I would rather avoid duplicating a datastructure of the size of X to change it's dtype from float32 to float64 to avoid triping the memory usage when fitting GMM on large data if we can.
mekleo commentedon Dec 4, 2024
This is surprising as means is exactly set to np.dot(resp.T, X) / nk[:, np.newaxis] in function _estimate_gaussian_parameters line 288.
Another strong indicator is that the simplified return value is merely the known variance formula: mean of squares - squared mean.
mekleo commentedon Dec 4, 2024
I guess on torch you will use torch.float that maps to torch.float32.
Regarding the array duplication, the original code does X * X, which already creates a new array. What the proposed code does is to create a new array and then square values in-place
ogrisel commentedon Dec 4, 2024
But then we won't fix the numerical stability problem on torch while we would for NumPy and the code would not be implicit (+ the array API would not allow expressing what you suggest). I would rather have some code that works consistently across all array API libraries (if possible).
ogrisel commentedon Dec 4, 2024
I agree, I don't understand either. Maybe there are bugs in our tests?
ogrisel commentedon Dec 4, 2024
Actually, maybe I made a mistake. I pushed the simplified computation in #30401 (without casting to float64) and still clipping the negative values, and both your reproducer and the existing tests are fine.
mekleo commentedon Dec 5, 2024
I just figured out there is an embarrassingly simple solution that implicitly aligns the input array with the floating-point precision of other operands without overhead. It means that it fixes the issue on every platform.
Indeed, the problem with clipping the result is that we keep having significantly erroneous results (positive and negative) due to that precision mismatch, but we just prevent them from being negative.
ogrisel commentedon Dec 5, 2024
But
np.zeros(X.shape)is implicitly float64 right? So everything else is doingfloat64operations in the end.If the point is to perform computation in float64, why not let the user pass the input data directly as
float64in the first place?mekleo commentedon Dec 5, 2024
That's a great question. The user has a dataframe with np.float32 values and the library does not specify it will fail or misbehave unless float64 is used. The problem is scikit-learn mixing internally operands of different precisions, implicitly converting some to double-precision (like the means in means**2, via np.dot(resp.T, X) / nk[:, np.newaxis]) and letting some other unaltered (like X in X * X)
ogrisel commentedon Dec 5, 2024
I had not realized that
respandmeansare allocated infloat64and thereforemeans_andcovariances_also as a result.In general, the contract is that if the input is float32, the library should do most computations in
float32and that the fitted numerical parameters should use the same precision when we can. Let's start with a PR that tries to do that as much as possible (and add some tests), and improve the message of theValueErrorraised to tell the user to convert the input explicitly tofloat64.mekleo commentedon Dec 5, 2024
I am not sure degrading scikit-learn's overall internal computation accuracy is the best route. IMHO, the library should leverage the computational capabilities of the platform it is running on.
ogrisel commentedon Dec 5, 2024
The goal would not to degrade the accuracy but give the user more control over the speed/memory usage/numerical accuracy tradeoff.
Currently, the float precision level of the inputs of the fit method of the estimator. Maybe it's a bit implicit, but it naturally reflects how NumPy functions typically behave: they work at the precision level of the input data. We have already implemented this approach in other estimators, but it has not been systematically generalized to all estimators in scikit-learn.
ogrisel commentedon Jan 8, 2025
We can now confirm that working in float32 can lead to significant improvements both in train time and memory usage:
#30415 (comment)
ogrisel commentedon Nov 18, 2026
Adding the array API label because fixing this would it possible to use GMM more efficiently on float32 centric hardware acceleration (e.g. many GPUs).
ogrisel commentedon Nov 18, 2026
I think I have a fix for this catastrophic cancellation problem. I will open a PR soon-ish.
EDIT: an early AI generated draft against my own fork is here: ogrisel#34 if you are curious. I plan to more carefully assess the tradeoffs and open it against the upstream repo once done.
FIX GEMM fast path with stable fallback for diag covariance