0

I have the following tensor:

indices = tf.constant([[1, 2], [0, 2], [1, 0]])

and I would like to create the following tensor:

[[0, 1, 1],
 [1, 0, 1],
 [1, 1, 0]]

Basically, I want a square matrix with the shape of indices.shape[0] where its elements are all zero except in the corresponding indices in indices tensor.

I tried tf.scatter_nd but no luck!

1
  • 1
    Depending on your data flow, you might find it useful to use sparse tensors. Note that the format of your matrix is very similar to the the repsentation of sparse tensors. When needed, sparse tensors can be converted to usual ones by calling `sparse.to_dense' method. Commented Apr 7, 2021 at 15:01

1 Answer 1

1

You indices tensor carries some implicit information that you should make explicit. For scatter_nd to work, you need to provide some pairs (i,j), where i is the index of the first dimension, and j the index of the second dimension.

You can restructure you indices Tensor the following way:

indices = tf.constant([[1, 2], [0, 2], [1, 0]])
j_indices = tf.reshape(indices, [-1, 1])
i_indices = tf.expand_dims(tf.repeat(tf.range(3), 2), axis=-1)
new_indices = tf.concat([i_indices, j_indices], axis=-1)

New indices contains the (i,j) indexes:

>>> new_indices
<tf.Tensor: shape=(6, 2), dtype=int32, numpy=
array([[0, 1],
       [0, 2],
       [1, 0],
       [1, 2],
       [2, 1],
       [2, 0]], dtype=int32)>

And you can use that with scatter_nd:

>>> tf.scatter_nd(new_indices, updates=tf.ones(tf.shape(new_indices)[0]), shape=[3, 3])
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[0., 1., 1.],
       [1., 0., 1.],
       [1., 1., 0.]], dtype=float32)>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.