Home > Mobile >  How to get number of values in each row of a sparse tensor?
How to get number of values in each row of a sparse tensor?

Time:11-19

I have a Sparse Tensor as follows:

st = tf.sparse.from_dense([[1, 0, 2, 5], [3, 0, 0, 4], [0, 0, 0, 0], [1, 1, 3, 0], [1, 2, 2, 2]])
print(st)
SparseTensor(indices=tf.Tensor(
[[0 0]
 [0 2]
 [0 3]
 [1 0]
 [1 3]
 [3 0]
 [3 1]
 [3 2]
 [4 0]
 [4 1]
 [4 2]
 [4 3]], shape=(12, 2), dtype=int64), values=tf.Tensor([1 2 5 3 4 1 1 3 1 2 2 2], shape=(12,), dtype=int32), dense_shape=tf.Tensor([5 4], shape=(2,), dtype=int64))

I want to convert this sparse tensor to another 1D tensor of shape (5, 1) where the only column represents the number (or size) of values in each of the rows.

For example, for the above sparse tensor, desired 1D tensor would be [3, 2, 0, 3, 4].

How do you think I could do it?

Sorry, I tried going through the TensorFlow api docs but couldn't find anything to try that I could paste here on what I have already tried.

Thanks in advance.

CodePudding user response:

You can use bin count on the indices.

tf.math.bincount(tf.cast(st.indices[:,0], tf.int32))
  • Related