Skip to content

BUG: QuantileTransformer() may materialize sparse matrices #34298

Description

@cakedev0

Describe the bug and give evidence about its user-facing impact

In some edge-cases (very sparse matrices), QuantileTransformer(ignore_implicit_zeros=False) materializes sparse matrices, which can lead to OOM or slowdown. Statistical behavior remains correct.

The problem is this line, which can create an array of size n_samples:

column_data = np.zeros(shape=n_samples, dtype=X.dtype)

User-facing impact: I'm not sure, the condition to produce this bug are relatively hard to create. It does cause slowdown for users with moderate-sized sparse matrices (less than 10k non-zeros per cols). But I don't think real users will have a high enough sparsity to cause an OOM.

Still, I think it's worth fixing when we get a chance as it breaks what I call for myself the "sparse contract": when something accepts sparse inputs, it should never materialize a O(n_samples) array, otherwise the sparse support is a bit a lie.

Steps/Code to Reproduce

import numpy as np
from scipy.sparse import csc_matrix
from sklearn.preprocessing import QuantileTransformer

subsample = 10_000  # default value
qt = QuantileTransformer(subsample=subsample)

# create a very sparse X matrix with one column:
n, d = 10**10, 1
# if you set nnz to `subsample + 1`, you don't get the error because
# the sub-sampling code path is used:
nnz = subsample

X = csc_matrix((
    np.random.rand(nnz),
    (np.arange(nnz), np.zeros(nnz))
), shape=(n, d))


qt.fit(X)

Expected Results

No OOM.

Actual Results

[...]
File ~/open-source/skl/scikit-learn/sklearn/preprocessing/_data.py:2864, in QuantileTransformer._sparse_fit(self, X, random_state)
   2862         column_data = np.zeros(shape=len(column_nnz_data), dtype=X.dtype)
   2863     else:
-> 2864         column_data = np.zeros(shape=n_samples, dtype=X.dtype)
   2865     column_data[: len(column_nnz_data)] = column_nnz_data
   2867 if not column_data.size:
   2868     # if no nnz, an error will be raised for computing the
   2869     # quantiles. Force the quantiles to be zeros.

MemoryError: Unable to allocate 74.5 GiB for an array with shape (10000000000,) and data type float64

Versions

System:
    python: 3.14.3 (main, Feb 12 2026, 00:42:54) [Clang 21.1.4 ]
executable: /home/arthur/open-source/skl/scikit-learn/sklearn-env/bin/python
   machine: Linux-6.17.0-35-generic-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.10.dev0
          pip: None
   setuptools: 70.2.0
        numpy: 2.4.6
        scipy: 1.17.1
       Cython: 3.2.5
       pandas: 3.0.3
   matplotlib: 3.10.9
       joblib: 1.5.3
threadpoolctl: 3.6.0
     narwhals: 2.21.2

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 16
         prefix: libscipy_openblas
       filepath: /home/arthur/open-source/skl/scikit-learn/sklearn-env/lib/python3.14/site-packages/numpy.libs/libscipy_openblas64_-32a4b2a6.so
        version: 0.3.31.188.0
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 16
         prefix: libscipy_openblas
       filepath: /home/arthur/open-source/skl/scikit-learn/sklearn-env/lib/python3.14/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so
        version: 0.3.30
threading_layer: pthreads
   architecture: Haswell

       user_api: openmp
   internal_api: openmp
    num_threads: 16
         prefix: libgomp
       filepath: /usr/lib/x86_64-linux-gnu/libgomp.so.1.0.0
        version: None

Interest in fixing the bug

Yes, I see how to solve it and it's not trivial, you have to implement a kind of "sparse-quantile".

Activity

  1. added
    Needs Triage
    on Jun 15, 2026
  2. removed
    Needs Triage
    on Jun 19, 2026
  3. ogrisel commented on Jun 19, 2026

    @ogrisel
    Member

    I agree I can reproduce the bug: on macOS the process reports to use 149 GB on a host with 16 GB (without crashing...) but does not complete either.

  4. ogrisel commented on Jun 19, 2026

    @ogrisel
    Member

    Still, I think it's worth fixing when we get a chance as it breaks what I call for myself the "sparse contract": when something accepts sparse inputs, it should never materialize a O(n_samples) array, otherwise the sparse support is a bit a lie.

    I agree.

  5. Stag51 commented on Jul 9, 2026

    @Stag51

    I've reproduced the bug locally on the current main branch and confirmed the exact failure you described — MemoryError trying to allocate 74.5 GiB at _sparse_fit, line 2863 (column_data = np.zeros(shape=n_samples, dtype=X.dtype)).
    I understand the core problem: the current implementation densifies each sparse column to compute quantiles, which breaks the sparse contract you mentioned. I'll look into implementing a sparse-aware quantile computation that works directly on (nnz values, implicit zero count) rather than materializing the full column.
    If you've already sketched out an approach or have thoughts on the right direction (e.g. how to handle the implicit zeros when computing percentiles), I'd appreciate a pointer before I dive in — want to make sure I'm not duplicating effort or missing an edge case you've already considered.

  6. cakedev0 commented on Aug 31, 2026

    @cakedev0
    MemberAuthor

    There are two ways of fixing this:

    1. re-implement partially numpy.nanquantile but with "native sparse support" (same maths, but avoid to materialize the n_samples array using some tricks), this is what is done in PR FIX avoid densifying sparse input in QuantileTransformer._sparse_fit #34451 by @Stag51
    2. avoid doing that, and instead do some rescaling of the quantiles to compute. I tried it, it works, but it differs from its dense counter-part if a quantile lands on the zero/non-zero frontier. IMO, it's fine, but implementing sparse quantile is not that complex either.

    In both case, this would allow fixing another weird/buggy behavior of the current implementation: see issue #34857.

    I also noticed RobustScaler has the same issue (it materializes a n_samples array and sorts it), and hence would also use a native sparse support quantile implementation.

    So I'm going to implement 2, basing myself on @Stag51 work (I'll mark you as Co-Author of the PR).

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