Skip to content

LocalOutlierFactor with Mahalanobis distance returns different results based on n_jobs parameter #32753

Open

Description

@sroener

Describe the bug

I encountered the following bug while doing an outlier analysis on a large dataset:

To detect outliers in a dataset with known outliers, I followed these steps:

  1. compute the covariance for a set of preselected numerical features with either MinCovDet or EmpiricalCovariance and extracted the inverse matrix VI using the precision_ parameter.
  2. I initialized the LocalOutlierFactor class with the metric mahalanobis, passed VI, and set n_jobs to 1
  3. I used fit_predict()to get the outlier predictions

Everything looked as expected.

Later on, I tried speeding up the computation by adding a few cores to n_jobs and had to realise that no outliers were detected anymore. After some debugging, I found that:

  1. outlier detection seems not to work when using multiple cores (all samples are marked as inliers)
  2. this effect seems to be tied to mahalanobis distance, because the bug does not appear with minkowski (p=2) distance regardless of the number of cores.

One workaround seems to be to precompute the mahalanobis distance and passing it to the LOF, but this is again using only one core for the computation and is not feasible for large datasets due to the size of the full pairwise distance matrix.

Steps/Code to Reproduce

import numpy as np
from sklearn.covariance import MinCovDet
from sklearn.neighbors import LocalOutlierFactor
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt

RNG = np.random.RandomState(42)


def make_data(n_inliers=200, n_outliers=10, n_features=10):
    # Inliers: standard normal in 10D
    X_in = RNG.normal(loc=0.0, scale=1.0, size=(n_inliers, n_features))
    # Outliers: shifted by +8 in all dimensions
    X_out = RNG.normal(loc=8.0, scale=1.0, size=(n_outliers, n_features))
    X = np.vstack([X_in, X_out])
    y_true = np.hstack([np.ones(n_inliers, dtype=int), -np.ones(n_outliers, dtype=int)])
    return X, y_true


def robust_inverse_covariance(X, random_state=0):
    # Fit robust covariance estimator
    mcd = MinCovDet(random_state=random_state).fit(X)
    cov = mcd.covariance_  # shape (n_features, n_features)
    # Compute inverse covariance (VI) expected by 'mahalanobis' metric
    VI = mcd.precision_ 
    # ensure dtype=float64 and C-contiguous so it serializes safely across processes
    VI = np.ascontiguousarray(VI, dtype=np.float64)
    return VI, cov


def run_lof(X, VI, n_neighbors=20, n_jobs=1):
    lof = LocalOutlierFactor(
        n_neighbors=n_neighbors,
        metric='mahalanobis',
        metric_params={'VI': VI},
        n_jobs=n_jobs
    )
    # fit_predict returns -1 for outliers and 1 for inliers
    labels = lof.fit_predict(X)
    return labels


def run_lof_precomputed(X, VI, n_neighbors=20, n_jobs=1):
    # compute full pairwise Mahalanobis distance matrix in the main process
    D = cdist(X, X, metric='mahalanobis', VI=VI)
    lof = LocalOutlierFactor(
        n_neighbors=n_neighbors,
        metric='precomputed',
        n_jobs=n_jobs
    )
    labels = lof.fit_predict(D)
    return labels


def stats(labels):
    unique, counts = np.unique(labels, return_counts=True)
    return dict(zip(unique.tolist(), counts.tolist()))


# Executing example
## make data
X, y_true = make_data(n_inliers=200, n_outliers=10, n_features=10)

## plot data
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y_true, cmap='coolwarm', edgecolor='k')
plt.title("Toy dataset with inliers (blue) and outliers (red)")
plt.xlabel("Feature 0")
plt.ylabel("Feature 1")
plt.show()

## Fit MinCovDet on the whole dataset 
VI, cov = robust_inverse_covariance(X, random_state=42)

## Run LOF with a single core (n_jobs=1)
labels_n1 = run_lof(X, VI, n_neighbors=20, n_jobs=1)
print("n_jobs=1 unique counts:", stats(labels_n1))
## expected result: n_jobs=1 unique counts: {-1: 11, 1: 199}

## Run LOF allowing multiple cores (n_jobs=4)
labels_n4 = run_lof(X, VI, n_neighbors=20, n_jobs=4)
print("n_jobs=4 unique counts:", stats(labels_n4))
## exprected result: n_jobs=4 unique counts: {1: 210}


## fix attempt: precompute Mahalanobis with single core and LOF with multiple
labels_precomputed = run_lof_precomputed(X, VI, n_neighbors=20, n_jobs=4)
print("precomputed (n_jobs=4) unique counts:", stats(labels_precomputed))
## expected result: precomputed (n_jobs=4) unique counts: {-1: 11, 1: 199}

## Print outlier labels
pred_outliers = np.where(labels_n1 == -1)[0]
print("Indices detected as outliers by n_jobs=1", pred_outliers)
## expected output: Indices detected as outliers by n_jobs=1: [116 200 201 202 203 204 205 206 207 208 209]
y_true_outliers = np.where(y_true == -1)[0]
print("Indices of true outliers:", y_true_outliers)
## expected output: Indices of true outliers: [200 201 202 203 204 205 206 207 208 209]

Expected Results

It shouldn't matter how many cores are passed to the 'n_jobs' parameters. The results should be comparable, or at least detect some outliers.

Actual Results

Results for LOF should be comparable, but are wildly different based on changes to the 'n_jobs' parameter, with all other parameters staying the same:

Results for n_jobs=1:
n_jobs=1 unique counts: {-1: 11, 1: 199}

Results for n_jobs=4:
n_jobs=4 unique counts: {1: 210}

Versions

Python dependencies:
      sklearn: 1.7.2
          pip: 25.2
   setuptools: 80.9.0
        numpy: 2.3.4
        scipy: 1.15.2
       Cython: None
       pandas: 2.2.3
   matplotlib: 3.10.6
       joblib: 1.5.2
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 5
         prefix: libscipy_openblas
       filepath: /home/USER/environments/conda_environments/MY_ENV/lib/python3.11/site-packages/numpy.libs/libscipy_openblas64_-8fb3d286.so
        version: 0.3.30
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 5
         prefix: libopenblas
       filepath: /home/USER/environments/conda_environments/MY_ENV/lib/libopenblasp-r0.3.30.so
        version: 0.3.30
threading_layer: pthreads
   architecture: Zen

       user_api: openmp
   internal_api: openmp
    num_threads: 5
         prefix: libgomp
       filepath: /home/USER/environments/conda_environments/MY_ENV/lib/libgomp.so.1.0.0
        version: None

Activity

  1. added
    Needs Triage
    on Nov 20, 2025
  2. Aaraviitkgp commented on Nov 21, 2025

    @Aaraviitkgp

    @sroener I think the issue occurs when n_jobs>1 it requires parallel processing, joblib tries to pickle metric_params and the array gets pickled in non standard format, then when it gets unpickled it is incorrect or incomplete. In case of n_jobs=1 no parallel processing happens so different results are produced.

  3. Aaraviitkgp commented on Nov 21, 2025

    @Aaraviitkgp

    @adrinjalali @lesteve can I raise a pr on this issue?

  4. sroener commented on Nov 21, 2025

    @sroener
    Author

    @Aaraviitkgp I think you are right. I found a workaround apart from precomputing. Changing the joblib backend from "loky" to "multiprocessing" also fixed the issue.

    Is there a way to make the serialization of the parameters more robust? I tried to minimize errors by using np.ascontiguousarray(VI, dtype=np.float64), but it didn't help.

  5. Aaraviitkgp commented on Nov 21, 2025

    @Aaraviitkgp

    @sroener I think a change has to be made in the _lof.py file for more robust solution, I have looked into it and I think by the LOF pickles metric_params internally the VI array might have already been corrupted. I think that's why np.ascontiguousarray(VI, dtype=np.float64) does not work.

  6. adrinjalali commented on Nov 21, 2025

    @adrinjalali
    Member

    I'd be very surprised if pickle is the issue. This requires investigation to figure out where exactly the difference comes from. Feel free to investigate @Aaraviitkgp , we'd appreciate that.

  7. added
    Needs Investigation
    and removed
    Needs Triage
    on Nov 21, 2025
  8. Aaraviitkgp commented on Nov 21, 2025

    @Aaraviitkgp

    @adrinjalali you were right pickle is not the issue, I've traced the bug and found that LOF calls kneighbors multiple times on the same fitted NearestNeighbors instance, and these repeated calls with n_jobs > 1 cause the VI matrix in metric_params to become corrupted through concurrent access, resulting in NaN values in the distance calculations.

  9. Aaraviitkgp commented on Nov 21, 2025

    @Aaraviitkgp

    import numpy as np
    from sklearn.neighbors import LocalOutlierFactor
    from sklearn.covariance import EmpiricalCovariance
    rng = np.random.RandomState(42)
    X = np.vstack([rng.randn(100, 5), rng.randn(10, 5) + 5])
    cov = EmpiricalCovariance().fit(X)
    VI = cov.precision_
    print("Running LOF 10 times with n_jobs=4:")
    for i in range(10):
    lof = LocalOutlierFactor(n_neighbors=20, metric='mahalanobis',
    metric_params={'VI': VI}, n_jobs=4)
    predictions = lof.fit_predict(X)
    has_nan = np.isnan(lof.negative_outlier_factor_).any()
    print(f" Run {i+1}: NaN = {has_nan}")

    print("\nRunning LOF 10 times with n_jobs=1:")
    for i in range(10):
    lof = LocalOutlierFactor(n_neighbors=20, metric='mahalanobis',
    metric_params={'VI': VI}, n_jobs=1)
    predictions = lof.fit_predict(X)
    has_nan = np.isnan(lof.negative_outlier_factor_).any()
    print(f" Run {i+1}: NaN = {has_nan}")

  10. Aaraviitkgp commented on Nov 25, 2025

    @Aaraviitkgp

    @adrinjalali any update on this issue.

  11. sroener commented on Nov 25, 2025

    @sroener
    Author

    @Aaraviitkgp Interesting, but why does changing the parallel_backend to "multiprocessing" solve the issue? This sounds more to a backend problem in joblibs standard backend "loky". May have something to do with serialization of nested data structures like VI (an numpy array) in a dictionary. This would also explain why minkowski distance works without an error, havin only one parameter passed, which is an integer.

  12. Aaraviitkgp commented on Nov 25, 2025

    @Aaraviitkgp

    @sroener in parallel_backend threads share same memory space which means all threads access the same VI which in return causes the error whereas in multi_processing, all threads have different memory space so it does not cause the error. I think as loky default prefer the first way which is why in locky it causes error. but I can be wrong .

  13. sroener commented on Nov 26, 2025

    @sroener
    Author

    I just tested different joblib backends/configurations in the following combinations using the with joblib.parallel_backend()context manager:

    backends: ["loky", "multiprocessing", "threading", "sequential"]

    The error occurs only with the backend set to threading, or when no backend context manager is used. This would add some evidence to the error being caused by multithreading. An interesting observation was that with multiprocessing, the results were always the same. With multithreading, the results sometimes varied.

  14. adrinjalali commented on Dec 15, 2025

    @adrinjalali
    Member

    Having a minimal reproducer where only relevant parts and maybe only some basic code with joblib parallelisation is included, should be a good next step for this issue to move forward. Thanks for the investigation so far.

  15. Aaraviitkgp commented on Dec 16, 2025

    @Aaraviitkgp
    import numpy as np
    from sklearn.covariance import MinCovDet
    from sklearn.neighbors import LocalOutlierFactor
    from scipy.spatial.distance import cdist
    
    # -----------------------------
    # Data generation
    # -----------------------------
    rng = np.random.RandomState(42)
    
    n_inliers = 200
    n_outliers = 10
    n_features = 10
    
    X_in = rng.normal(0.0, 1.0, size=(n_inliers, n_features))
    X_out = rng.normal(8.0, 1.0, size=(n_outliers, n_features))
    
    X = np.vstack([X_in, X_out])
    
    y_true = np.hstack([
        np.ones(n_inliers, dtype=int),
        -np.ones(n_outliers, dtype=int),
    ])
    
    # -----------------------------
    # Robust inverse covariance
    # -----------------------------
    mcd = MinCovDet(random_state=42).fit(X)
    VI = np.ascontiguousarray(mcd.precision_, dtype=np.float64)
    
    # -----------------------------
    # LOF with n_jobs = 1
    # -----------------------------
    lof_n1 = LocalOutlierFactor(
        n_neighbors=20,
        metric="mahalanobis",
        metric_params={"VI": VI},
        n_jobs=1,
    )
    
    labels_n1 = lof_n1.fit_predict(X)
    
    print(
        "n_jobs=1 counts:",
        dict(zip(*np.unique(labels_n1, return_counts=True)))
    )
    
    # -----------------------------
    # LOF with n_jobs = 4 (buggy)
    # -----------------------------
    lof_n4 = LocalOutlierFactor(
        n_neighbors=20,
        metric="mahalanobis",
        metric_params={"VI": VI},
        n_jobs=4,
    )
    
    labels_n4 = lof_n4.fit_predict(X)
    
    print(
        "n_jobs=4 counts:",
        dict(zip(*np.unique(labels_n4, return_counts=True)))
    )
    
    # -----------------------------
    # Precompute distances
    # -----------------------------
    D = cdist(X, X, metric="mahalanobis", VI=VI)
    
    lof_pre = LocalOutlierFactor(
        n_neighbors=20,
        metric="precomputed",
        n_jobs=4,
    )
    
    labels_pre = lof_pre.fit_predict(D)
    
    print(
        "precomputed counts:",
        dict(zip(*np.unique(labels_pre, return_counts=True)))
    )
    
    # -----------------------------
    # Diagnostics
    # -----------------------------
    print(
        "Detected outliers (n_jobs=1):",
        np.where(labels_n1 == -1)[0]
    )
    
    print(
        "True outliers:",
        np.where(y_true == -1)[0]
    )
  16. Aaraviitkgp commented on Dec 16, 2025

    @Aaraviitkgp

    simple code for bug reproduction

  17. lesteve commented on Dec 16, 2025

    @lesteve
    Member

    @Aaraviitkgp readability counts, a lot! Can you please edit your snippet and add triple back-quotes aka fenced code blocks to format error messages code snippets. Bonus points if you use syntax highlighting with py for python snippets and pytb for tracebacks.

  18. Aaraviitkgp commented on Dec 16, 2025

    @Aaraviitkgp

    @Aaraviitkgp readability counts, a lot! Can you please edit your snippet and add triple back-quotes aka fenced code blocks to format error messages code snippets. Bonus points if you use syntax highlighting with py for python snippets and pytb for tracebacks.

    I have edited it please check if any other issue.

  19. adrinjalali commented on Dec 16, 2025

    @adrinjalali
    Member

    Please share the output of the script when you post it.

    This is the output now:

    **n_jobs=1 counts: {np.int64(-1): np.int64(11), np.int64(1): np.int64(199)}
    /home/adrin/Projects/gh/me/scikit-learn/sklearn/utils/parallel.py:184: RuntimeWarning: invalid value encountered in sqrt
      return self.function(*args, **kwargs)
    /home/adrin/Projects/gh/me/scikit-learn/sklearn/utils/parallel.py:184: RuntimeWarning: invalid value encountered in sqrt
      return self.function(*args, **kwargs)
    /home/adrin/Projects/gh/me/scikit-learn/sklearn/utils/parallel.py:184: RuntimeWarning: invalid value encountered in sqrt
      return self.function(*args, **kwargs)
    /home/adrin/Projects/gh/me/scikit-learn/sklearn/utils/parallel.py:184: RuntimeWarning: invalid value encountered in sqrt
      return self.function(*args, **kwargs)
    n_jobs=4 counts: {np.int64(1): np.int64(210)}
    precomputed counts: {np.int64(-1): np.int64(11), np.int64(1): np.int64(199)}
    Detected outliers (n_jobs=1): [116 200 201 202 203 204 205 206 207 208 209]
    True outliers: [200 201 202 203 204 205 206 207 208 209]

    that indicates there are some numerical issues which might cause the disparity. We need an example where things run correctly.

  20. Aaraviitkgp commented on Dec 21, 2025

    @Aaraviitkgp
    import numpy as np
    from sklearn.neighbors import LocalOutlierFactor
    from sklearn.covariance import MinCovDet
    import warnings
    
    
    warnings.filterwarnings('ignore')
    
    rng = np.random.RandomState(42)
    # -----------------------------
    # Generate Data
    # -----------------------------
    X_inliers = rng.randn(200, 10)
    X_outliers = rng.randn(10, 10) + 8
    X = np.vstack([X_inliers, X_outliers])
    
    # -----------------------------
    # Robust inverse covariance
    # -----------------------------
    mcd = MinCovDet(random_state=42).fit(X)
    VI = np.ascontiguousarray(mcd.precision_, dtype=np.float64)
    
    # -----------------------------
    # LOF with n_jobs = 1
    # -----------------------------
    lof_single = LocalOutlierFactor(
        n_neighbors=20,
        metric='mahalanobis',
        metric_params={'VI': VI},
        n_jobs=1
    )
    labels_single = lof_single.fit_predict(X)
    outliers_single = np.where(labels_single == -1)[0]
    
    # -----------------------------
    # LOF with n_jobs = 4 (buggy)
    # -----------------------------
    lof_parallel = LocalOutlierFactor(
        n_neighbors=20,
        metric='mahalanobis',
        metric_params={'VI': VI},
        n_jobs=4
    )
    labels_parallel = lof_parallel.fit_predict(X)
    outliers_parallel = np.where(labels_parallel == -1)[0]
    
    
    true_outliers = np.arange(200, 210)
    
    print(f"Detected outliers (n_jobs=1): {outliers_single}")
    print(f"True outliers: {true_outliers}")
  21. Aaraviitkgp commented on Dec 21, 2025

    @Aaraviitkgp

    this is output :

    Detected outliers (n_jobs=1): [116 200 201 202 203 204 205 206 207 208 209]
    True outliers: [200 201 202 203 204 205 206 207 208 209]

  22. BillyLjm commented on Dec 22, 2025

    @BillyLjm

    The non-thread-safe object seems to be the self.buffer for the Mahalanobis Distance implementation in sklearn/metrics/_dist_metrics.pyx.tp excerpted below.
    I imagine the class would have to be rewritten without that array and with multithreading in mind?

    ### sklearn\metrics\_dist_metrics.pyx.tp | line 1600
    #------------------------------------------------------------
    # Mahalanobis Distance
    #  d = sqrt( (x - y)^T V^-1 (x - y) )
    cdef class MahalanobisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}):
    	""" ... """
        cdef float64_t[::1] buffer
    
        def __init__(self, V=None, VI=None):
            if VI is None:
                if V is None:
                    raise ValueError("Must provide either V or VI "
                                     "for Mahalanobis distance")
                VI = np.linalg.inv(V)
            if VI.ndim != 2 or VI.shape[0] != VI.shape[1]:
                raise ValueError("V/VI must be square")
    
            self.mat = np.asarray(VI, dtype=np.float64, order='C')
    
            self.size = self.mat.shape[0]
    
            # We need to create a buffer to store the vectors' coordinates' differences
            self.buffer = np.zeros(self.size, dtype=np.float64)
  23. Shu6136713 commented on Jan 21, 2026

    @Shu6136713

    If it's okey, we'd like to work on it to resolve this issue.

  24. Shu6136713 commented on Feb 2, 2026

    @Shu6136713

    @adrinjalali , @ogrisel

    We thought of a number of approaches to the solution.

    Solution 1 - Naive:
    Do not use a shared buffer at all.
    Advantage - solves the problem, disadvantage - exponential memory allocations.

    Solution 2 - Medium:
    Pass a flag to init of Mahalanobis, which will tell whether to use a shared buffer.
    The flag will be True if and only if n_jobs == 1 (or None).
    Advantage - when n_jobs = 1 there will be optimal performance, disadvantage - when n_jobs >1 there will be exponential as above.

    Solution 3 - Advanced:
    Allocate a buffer to each thread. Keep a map of buffers according to the current thread ID- using tss.

    What do you think?

  25. lesteve commented on Aug 7, 2026

    @lesteve
    Member

    Here is a reproducer, this is due to our implementation of Mahalanobis distance with self.buffer being shared of as mentioned by someone else.

    For potential contributors, more than a PR attempt, a reproducer like this is something super useful 1. This allow to have a better understanding of the problem and make sure there is a real problem:

    from concurrent.futures import ThreadPoolExecutor
    
    import numpy as np
    
    from sklearn.neighbors import BallTree
    
    rng = np.random.RandomState(42)
    X = rng.normal(size=(100, 10))
    VI = np.linalg.inv(np.cov(X.T))
    tree = BallTree(X, metric="mahalanobis", VI=VI)
    
    expected_dist, expected_ind = tree.query(X, k=20)
    
    for attempt in range(10):
        with ThreadPoolExecutor(max_workers=4) as executor:
            chunks = list(
                executor.map(
                    lambda X_chunk: tree.query(X_chunk, k=20), np.array_split(X, 4)
                )
            )
        actual_dist = np.vstack([dist for dist, _ in chunks])
        actual_ind = np.vstack([ind for _, ind in chunks])
    
        if not (
            np.allclose(actual_dist, expected_dist)
            and np.array_equal(actual_ind, expected_ind)
        ):
            print(f"thread-safety failure on attempt {attempt + 1}")
            print(f"incorrect distances: {np.count_nonzero(actual_dist != expected_dist)}")
            print(f"incorrect indices: {np.count_nonzero(actual_ind != expected_ind)}")
            break
    else:
        raise AssertionError("The thread-safety failure did not reproduce")

    I have opened a draft PR fixing the issue: #34671.

    Footnotes

    1. compared to the original reproducer (thanks @sroener for providing a reproducer in the first place 🙏) it is a bit simpler (only use BallTree and no joblib which shows that joblib is not to blame here) ↩

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

    BugNeeds Investigation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions