spreisel
spreisel

Reputation: 391

How to index sparse tensors in TensorFlow?

Is there a way to index a cell/section of a sparse tensor like in case of a dense tensor?

# dens_tensor.shape = [10, 10, 10]
dense_cell = dense_tensor[0,0,1]

If not, does someone know a workaround to index a sparse tensor?

Upvotes: 2

Views: 3070

Answers (1)

Siddhanth Gupta
Siddhanth Gupta

Reputation: 91

A SparseTensor has a field called indices which would allow you to get a 2D Tensor of dimensions (N, ndims) where N = number of non-zero entries in the sparse matrix, and ndims = dimensionality of the sparse matrix.

Given this 2D tensor, you can certainly search for your required index within the tensor. AFAIK, tensorflow does not have such a search, but you could do a session.run() on the 2D tensor, and then search for your index (0, 0, 1) within this 2D numpy array (https://stackoverflow.com/a/25823710/5249801).

If you find your required index (0, 0, 1) at say, index x in your numpy array tf.Session().run(sparse_matrix.indices), then the value you're looking for is also at index x in the dense 2D tensor sparse_matrix.values

Upvotes: 1

Related Questions