Skip to content

T-SNE fails for CSR matrix #9691

Closed
Closed

Description

@romankierzkowski

T-SNE fails for CSR matrix with:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

Code to reproduce:

from sklearn.neighbors import BallTree, kneighbors_graph
from sklearn.manifold import TSNE
X = np.random.randn(100, 10)

bt = BallTree(X, leaf_size=300)
distances = kneighbors_graph(bt, n_neighbors=40, mode="distance", metric="cosine")
X_embedded = TSNE(n_components=2, metric="precomputed").fit_transform(distances)

Reason:
When distance is square Compressed Sparse Row matrix then np.any(X > 0) is also sparse matrix.

in ()
----> 1 X_embedded = TSNE(n_components=2, metric="precomputed").fit_transform(distances)
2
3 ax = plt.scatter(X_embedded[:,0], X_embedded[:,1], c=clusters[0:len(X_embedded)]).axes

/Users/roman/.virtualenvs/wordmap/lib/python2.7/site-packages/sklearn/manifold/t_sne.pyc in fit_transform(self, X, y)
857 Embedding of the training data in low-dimensional space.
858 """
--> 859 embedding = self.fit(X)
860 self.embedding
= embedding
861 return self.embedding_

/Users/roman/.virtualenvs/wordmap/lib/python2.7/site-packages/sklearn/manifold/t_sne.pyc in _fit(self, X, skip_num_points)
645 if X.shape[0] != X.shape[1]:
646 raise ValueError("X should be a square distance matrix")
--> 647 if np.any(X < 0):
648 raise ValueError("All distances should be positive, the "
649 "precomputed distances given as X is not "

/Users/roman/.virtualenvs/wordmap/lib/python2.7/site-packages/scipy/sparse/base.pyc in bool(self)
236 return self.nnz != 0
237 else:
--> 238 raise ValueError("The truth value of an array with more than one "
239 "element is ambiguous. Use a.any() or a.all().")
240 nonzero = bool

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

Activity

  1. rth commented on Sep 5, 2017

    @rth
    Member

    @romankierzkowski I believe BallTree doesn't support sparse arrays, if X is sparse, the line,

    bt = BallTree(X, leaf_size=300)

    should have raised an exception. Is this error reproducible on your system? Also could you please post your python package versions for numpy etc, as described here. Thanks.

  2. romankierzkowski commented on Sep 5, 2017

    @romankierzkowski
    Author

    @rth: X is not sparse, distances is. Ball tree works fine, but T-SNE fails on sparse matrix.

    Here is self-contained gist with error reproduction: https://gist.github.com/romankierzkowski/8eae3f45ea5f50913763292d33afae96


    Darwin-16.7.0-x86_64-i386-64bit
    Python 2.7.10 (default, Feb 7 2017, 00:08:15)
    [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]
    NumPy 1.13.1
    SciPy 0.19.1
    Scikit-Learn 0.19.0

  3. rth commented on Sep 5, 2017

    @rth
    Member

    Aww makes sense. I can reproduce this, thanks for the code snippet! As you say the root cause is that np.any(distance > 0) evaluates to a sparse array instead of a boolean. Apparently, it's a known issue with sparse CSR, not that I was aware it could do that...

    This line was recently introduced in #9032 but question is why the test sklearn/manifold/tests/test_t_sne.py::test_fit_csr_matrix doesn't fail.

    ping @tomMoral @jnothman sounds like a regression in 0.19..

  4. jnothman commented on Sep 5, 2017

    @jnothman
    Member
  5. jnothman commented on Sep 5, 2017

    @jnothman
    Member
  6. rth commented on Sep 5, 2017

    @rth
    Member

    @jnothman You are right, looks like precomputed sparse arrays were not supported before either, (from the _fit method)

    Note that sparse arrays can only be handled by method='exact'.
    It is recommended that you convert your sparse array to dense
    (e.g. X.toarray()) if it fits in memory, or otherwise using a
    dimensionality reduction technique (e.g. TruncatedSVD).

    Not a regression then. sorry for the false alarm.

    This should be more explicitly specified somewhere in the public docstring though..

  7. rth commented on Sep 5, 2017

    @rth
    Member

    When running with 0.18.1 the above code snippet also fails with the traceback below. Related to #9623,

    ~/.miniconda3/envs/sklearn-test-new/lib/python3.6/site-packages/sklearn/neighbors/base.py in _init_params(self, n_neighbors, radius, algorithm, leaf_size, metric, p, metric_params, n_jobs)
        140         elif metric not in VALID_METRICS[alg_check]:
        141             raise ValueError("Metric '%s' not valid for algorithm '%s'"
    --> 142                              % (metric, algorithm))
        143 
        144         if self.metric_params is not None and 'p' in self.metric_params:
    
    ValueError: Metric 'cosine' not valid for algorithm 'auto'

    finally after removing the cosine metric this yields,

    TypeError: A sparse matrix was passed, but dense data is required for method="barnes_hut". Use X.toarray() to convert to a dense numpy array if the array is small enough for it to fit in memory. Otherwise consider dimensionality reduction techniques (e.g. TruncatedSVD)

    so this wasn't supported in 0.18 either.. Sorry for the confusion.

  8. jnothman commented on Sep 5, 2017

    @jnothman
    Member
  9. added
    Moderate
    on Sep 5, 2017
  10. ogrisel commented on Sep 6, 2017

    @ogrisel
    Member

    This is something @tomMoral and I discussed when working on #9032. We need a unified way to pass neighbors to some estimators (t-SNE, DBSCAN and probably many others). Those neighbors could be precomputed, a NearestNeighbors instance or a string for a NearestNeighbors method.

  11. jnothman commented on Sep 6, 2017

    @jnothman
    Member
  12. thechargedneutron commented on Sep 14, 2017

    @thechargedneutron
    Contributor

    @jnothman Is someone working on this? I would like to take it as my first "moderate" bug. :) In case, it's open, what needs to be done here? As mentioned above, "it should be feasible to support kneighbors_graph output in tsne as precomputed (although it should be squared distances really)", we need to add this compatibility and add some tests. Please, correct me if I am wrong.

  13. jnothman commented on Sep 15, 2017

    @jnothman
    Member
  14. thechargedneutron commented on Sep 22, 2017

    @thechargedneutron
    Contributor

    @jnothman I did some minor changes in the code in class TSNE similar to that done in dbscan. I am trying to go past each line where there is an error due to numpy array and csr_matrix array. But, I am stuck at _binary_search_perplexity which is in manifold._utils.pyx. I could not find a way to make that work since _binary_search_perplexity is in a pyx format and I guess I am on a wrong track.
    The error is raised at Line 61 in manifold.t_sne.py:

    conditional_P = _utils._binary_search_perplexity(
            distances, None, desired_perplexity, verbose)
    
  15. jnothman commented on Sep 25, 2017

    @jnothman
    Member
  16. renewang commented on Nov 22, 2017

    @renewang

    Hi! Is still anyone working on this issue? I'm interested in understanding tSNE. Is possible for me to work on this issue?

  17. amueller commented on Nov 22, 2017

    @amueller
    Member

    @renewang this might be a bit hairy for a first contribution (sorry if I'm mistaken and it's not your first). I would start with something that's tagged "good first issue" or "easy".

  18. renewang commented on Nov 23, 2017

    @renewang

    Thanks for reply! But the truth is I'm going to debug through tSNE code anyway. And @thechargedneutron already has some prior study on this issue. So I think it would be good for me to study tSNE code while solving a relevant bug under guidance from scikit-learn experts. How do you think?

  19. thechargedneutron commented on Nov 24, 2017

    @thechargedneutron
    Contributor

    From what I investigated, I think we need to use np.argpartition in csr_matrix. But the problem is that csr_matrix is just a vector and hence raises an error when axis=1. Is there a function analogous to np.argpartition in scipy?

  20. jnothman commented on Nov 26, 2017

    @jnothman
    Member
  21. TomDLT commented on Sep 18, 2019

    @TomDLT
    Member

    Fixed in #10482

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

    EnhancementModeratehelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions