Skip to content

Gaussian Mixture: Diagonal covariance vectors might contain unreasonably negative values when the input datatype is np.float32 #30382

Open
ogrisel/scikit-learn
#34

Description

@mekleo

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: 12

Activity

  1. added
    Needs Triage
    on Dec 2, 2024
  2. ogrisel commented on Dec 3, 2024

    @ogrisel
    Member

    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_spherical that directly calls into _estimate_gaussian_covariances_diag which does the following:

    def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar):
    """Estimate the diagonal covariance vectors.
    Parameters
    ----------
    responsibilities : array-like of shape (n_samples, n_components)
    X : array-like of shape (n_samples, n_features)
    nk : array-like of shape (n_components,)
    means : array-like of shape (n_components, n_features)
    reg_covar : float
    Returns
    -------
    covariances : array, shape (n_components, n_features)
    The covariance vector of the current components.
    """
    avg_X2 = np.dot(resp.T, X * X) / nk[:, np.newaxis]
    avg_means2 = means**2
    avg_X_means = means * np.dot(resp.T, X) / nk[:, np.newaxis]
    return avg_X2 - 2 * avg_X_means + avg_means2 + reg_covar

    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:

    (w a - b)^2 = w^2 a^2 - 2 w a b + b^
    

    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:

    return ((resp.T @ X) / nk[:, np.newaxis] - means) ** 2 + reg_covar

    because the responsibility weights are not simple scalar weights. So maybe it's not possible to do the factored computation.

  3. ogrisel commented on Dec 3, 2024

    @ogrisel
    Member

    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.

  4. added and removed
    Needs Triage
    on Dec 3, 2024
  5. ogrisel commented on Dec 3, 2024

    @ogrisel
    Member

    /ping @jeremiedbb if you have better suggestions.

  6. mekleo commented on Dec 3, 2024

    @mekleo
    ContributorAuthor

    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:

        # Convert to a new array of float or float64 depending on the platform
        X2 = X.astype(float)
        # In-place squaring
        X2 **= 2 
        avg_X2 = np.dot(resp.T, X2) / nk[:, np.newaxis]
        avg_means2 = means**2
        return np.clip(avg_X2 - avg_means2, 0, None) + reg_covar

    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.

  7. ogrisel commented on Dec 4, 2024

    @ogrisel
    Member

    Using float (alias to np.float64) instead of float64 would be supported on 32-bit platforms as well

    Yes, on the CPU, but not with PyTorch tensors on mps devices (if we ever convert this estimator to support the array API):

    >>> import torch
    >>> torch.ones(5, dtype=torch.float64, device="mps")
    Traceback (most recent call last):
      Cell In[6], line 1
        torch.ones(5, dtype=torch.float64, device="mps")
    TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead.
  8. mekleo commented on Dec 4, 2024

    @mekleo
    ContributorAuthor
  9. ogrisel commented on Dec 4, 2024

    @ogrisel
    Member

    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

    I don't think this is true: I tried your suggestion and many existing tests fail.

  10. ogrisel commented on Dec 4, 2024

    @ogrisel
    Member

    In this example, you still use np.float64. Just use float

    I would rather not use implicit precision levels in the source code. But, in this particular case, this does not change anything: Python float are promoted to float64 both by NumPy and Pytorch:

    >>> import torch
    >>> torch.ones(5, dtype=float, device="mps")
    Traceback (most recent call last):
      Cell In[5], line 1
        torch.ones(5, dtype=float, device="mps")
    TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead.

    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.

  11. mekleo commented on Dec 4, 2024

    @mekleo
    ContributorAuthor

    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

    I don't think this is true: I tried your suggestion and many existing tests fail.

    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.

  12. mekleo commented on Dec 4, 2024

    @mekleo
    ContributorAuthor

    In this example, you still use np.float64. Just use float

    I would rather not use implicit precision levels in the source code. But, in this particular case, this does not change anything: Python float are promoted to float64 both by NumPy and Pytorch:

    >>> import torch
    >>> torch.ones(5, dtype=float, device="mps")
    Traceback (most recent call last):
      Cell In[5], line 1
        torch.ones(5, dtype=float, device="mps")
    TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead.

    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.

    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

  13. ogrisel commented on Dec 4, 2024

    @ogrisel
    Member

    I guess on torch you will use torch.float that maps to torch.float32.

    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).

  14. ogrisel commented on Dec 4, 2024

    @ogrisel
    Member

    This is surprising as means is exactly set to np.dot(resp.T, X) / nk[:, np.newaxis] in function _estimate_gaussian_parameters line 288.

    I agree, I don't understand either. Maybe there are bugs in our tests?

  15. ogrisel commented on Dec 4, 2024

    @ogrisel
    Member

    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.

  16. mekleo commented on Dec 5, 2024

    @mekleo
    ContributorAuthor

    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.

        # Align X to the other operands' floating-point precision
        # as squaring X immediately would increase its precision error and the
        # mismatch with operands of different precision
        X2 = np.zeros(X.shape) 
        X2 += X
        # In-place squaring of X2
        X2 **= 2
        avg_X2 = np.dot(resp.T, X2) / nk[:, np.newaxis]
        avg_means2 = means**2
        return avg_X2 - avg_means2 + reg_covar
  17. ogrisel commented on Dec 5, 2024

    @ogrisel
    Member

    But np.zeros(X.shape) is implicitly float64 right? So everything else is doing float64 operations in the end.

    If the point is to perform computation in float64, why not let the user pass the input data directly as float64 in the first place?

  18. mekleo commented on Dec 5, 2024

    @mekleo
    ContributorAuthor

    But np.zeros(X.shape) is implicitly float64 right? So everything else is doing float64 operations in the end.

    If the point is to perform computation in float64, why not let the user pass the input data directly as float64 in the first place?

    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)

  19. ogrisel commented on Dec 5, 2024

    @ogrisel
    Member

    I had not realized that resp and means are allocated in float64 and therefore means_ and covariances_ also as a result.

    In general, the contract is that if the input is float32, the library should do most computations in float32 and 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 the ValueError raised to tell the user to convert the input explicitly to float64.

  20. mekleo commented on Dec 5, 2024

    @mekleo
    ContributorAuthor

    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.

  21. ogrisel commented on Dec 5, 2024

    @ogrisel
    Member

    I am not sure degrading scikit-learn's overall internal computation accuracy is the best route.

    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.

  22. ogrisel commented on Jan 8, 2025

    @ogrisel
    Member

    We can now confirm that working in float32 can lead to significant improvements both in train time and memory usage:

    #30415 (comment)

  23. ogrisel commented on Nov 18, 2026

    @ogrisel
    Member

    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).

  24. ogrisel commented on Nov 18, 2026

    @ogrisel
    Member

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions