Repository navigation
Description
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 = boolValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
Activity
rth commentedon Sep 5, 2017
@romankierzkowski I believe BallTree doesn't support sparse arrays, if
Xis sparse, the line,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.
romankierzkowski commentedon Sep 5, 2017
@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
rth commentedon Sep 5, 2017
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_matrixdoesn't fail.ping @tomMoral @jnothman sounds like a regression in 0.19..
jnothman commentedon Sep 5, 2017
jnothman commentedon Sep 5, 2017
rth commentedon Sep 5, 2017
@jnothman You are right, looks like precomputed sparse arrays were not supported before either, (from the _fit method)
Not a regression then. sorry for the false alarm.
This should be more explicitly specified somewhere in the public docstring though..
rth commentedon Sep 5, 2017
When running with 0.18.1 the above code snippet also fails with the traceback below. Related to #9623,
finally after removing the cosine metric this yields,
so this wasn't supported in 0.18 either.. Sorry for the confusion.
jnothman commentedon Sep 5, 2017
ogrisel commentedon Sep 6, 2017
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
NearestNeighborsinstance or a string for aNearestNeighborsmethod.jnothman commentedon Sep 6, 2017
thechargedneutron commentedon Sep 14, 2017
@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.
jnothman commentedon Sep 15, 2017
thechargedneutron commentedon Sep 22, 2017
@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_perplexitywhich 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:
jnothman commentedon Sep 25, 2017
renewang commentedon Nov 22, 2017
Hi! Is still anyone working on this issue? I'm interested in understanding tSNE. Is possible for me to work on this issue?
amueller commentedon Nov 22, 2017
@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".
renewang commentedon Nov 23, 2017
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?
thechargedneutron commentedon Nov 24, 2017
From what I investigated, I think we need to use
np.argpartitionin 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 tonp.argpartitionin scipy?jnothman commentedon Nov 26, 2017
TomDLT commentedon Sep 18, 2019
Fixed in #10482