Skip to content

K-Means: Should subtract X_means from initial centroids iff it's also subtracted from X #6740

Closed

Description

@tomtung

Description

The bug happens when X is sparse and initial cluster centroids are given. In this case the means of each of X's columns are computed and subtracted from init for no reason.

Steps/Code to Reproduce

import numpy as np
import scipy
from sklearn.cluster import KMeans
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data

# Get a local optimum
centers = KMeans(n_clusters=3).fit(X).cluster_centers_

# Fit starting from a local optimum shouldn't change the solution
np.testing.assert_allclose(
    centers,
    KMeans(n_clusters=3, init=centers, n_init=1).fit(X).cluster_centers_
)

# The same should be true when X is sparse
X_sparse = scipy.sparse.csr_matrix(X)
np.testing.assert_allclose(
    centers,
    KMeans(n_clusters=3, init=centers, n_init=1).fit(X_sparse).cluster_centers_
)

Expected Results

Both asserts should pass.

Actual Results

The second assert fails.

Versions

Darwin-15.4.0-x86_64-i386-64bit
Python 2.7.11 (default, Jan 22 2016, 08:29:18)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)]
NumPy 1.11.0
SciPy 0.17.0
Scikit-Learn 0.17.1

Activity

  1. changed the title [-]K-Means: Should subtract `X_means` from initial centroids iff it's also subtracted from `X`[/-] [+]K-Means: Should subtract X_means from initial centroids iff it's also subtracted from X[/+] on May 2, 2016
  2. yupbank commented on May 4, 2016

    @yupbank
    Contributor

    I think the problem is because, the order of cluster center changed

    you can try to sort the n_center first and then the test would pass.

  3. tomtung commented on May 4, 2016

    @tomtung
    Author

    I think that the center being re-ordered in the previous example is just the symptom of the problem. Since the iris data is low-dimensional, close to (0,0), and we provided the correct n_clusters, it's likely that even the provided init centers are not handled correctly we will converge to the same result anyways.

    The root problem is that, when X is sparse, the provided init centers are effectively discarded and replaced with init - X_mean, which are potentially really bad init centers.

    To better demonstrate this:

    import numpy as np
    import scipy
    from sklearn.cluster import KMeans
    from sklearn import datasets
    
    iris = datasets.load_iris()
    X = iris.data
    
    # Get a local optimum
    # Here we change from the previous example to n_clusters=4, n_init=1
    centers = KMeans(n_clusters=4, n_init=1, init='random', random_state=1).fit(X).cluster_centers_
    
    # Fit starting from a local optimum shouldn't change the solution
    np.testing.assert_allclose(
        centers,
        KMeans(n_clusters=4, init=centers, n_init=1).fit(X).cluster_centers_
    )
    
    # The same should be true when X is sparse, but wasn't before the bug fix
    X_sparse = scipy.sparse.csr_matrix(X)
    np.testing.assert_allclose(
        centers,
        KMeans(n_clusters=4, init=centers, n_init=1).fit(X_sparse).cluster_centers_
    )

    And in the assert error, you can see that the centers are not just reordered but very different.

    ---------------------------------------------------------------------------
    AssertionError                            Traceback (most recent call last)
    <ipython-input-14-5f1d0ee571fe> in <module>()
         20 np.testing.assert_allclose(
         21         centers,
    ---> 22         KMeans(n_clusters=4, init=centers, n_init=1).fit(X_sparse).cluster_centers_
         23 )
    
    /usr/local/lib/python2.7/site-packages/numpy/testing/utils.pyc in assert_allclose(actual, desired, rtol, atol, equal_nan, err_msg, verbose)
       1389     header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol)
       1390     assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
    -> 1391                          verbose=verbose, header=header)
       1392
       1393 def assert_array_almost_equal_nulp(x, y, nulp=1):
    
    /usr/local/lib/python2.7/site-packages/numpy/testing/utils.pyc in assert_array_compare(comparison, x, y, err_msg, verbose, header, precision)
        731                                 names=('x', 'y'), precision=precision)
        732             if not cond:
    --> 733                 raise AssertionError(msg)
        734     except ValueError:
        735         import traceback
    
    AssertionError:
    Not equal to tolerance rtol=1e-07, atol=0
    
    (mismatch 100.0%)
     x: array([[ 5.370588,  3.8     ,  1.517647,  0.276471],
           [ 5.883607,  2.740984,  4.388525,  1.434426],
           [ 6.853846,  3.076923,  5.715385,  2.053846],
           [ 4.818182,  3.221212,  1.436364,  0.227273]])
     y: array([[ 6.293617,  2.9     ,  4.951064,  1.729787],
           [ 5.58    ,  2.633333,  3.986667,  1.233333],
           [ 5.006   ,  3.418   ,  1.464   ,  0.244   ],
           [ 7.086957,  3.126087,  6.013043,  2.143478]])
    
  4. added
    Easy
    on Oct 11, 2016
  5. added this to the 0.19 milestone on Oct 13, 2016
  6. jkarno commented on Nov 3, 2016

    @jkarno
    Contributor

    @amueller I can work on this. Is there anything else that needs to be done besides adding the test case to the current 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

    BugEasy

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions