2

Suppose I have a list

x = [0, 1, 3, 5]

And I want to get a tensor with dimensions

s = (10, 7)

Such that the first column of the rows with indexes defined in x are 1, and 0 otherwise.

For this particular example, I want to obtain the tensor containing:

T = [[1, 0, 0, 0, 0, 0, 0],
     [1, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [1, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [1, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0]]

Using numpy, this would be the equivalent:

t = np.zeros(s)
t[x, 0] = 1

I found this related answer, but it doesn't really solve my problem.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
Filipe Aleixo
  • 3,924
  • 3
  • 41
  • 74

1 Answers1

3

Try this:

import tensorflow as tf 

indices = tf.constant([[0, 1],[3, 5]], dtype=tf.int64)
values = tf.constant([1, 1])
s = (10, 7)

st = tf.SparseTensor(indices, values, s)
st_ordered = tf.sparse_reorder(st)
result = tf.sparse_tensor_to_dense(st_ordered)

sess = tf.Session()
sess.run(result)

Here is the output:

array([[0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]], dtype=int32)

I slightly modified your indexes so you can see the x,y format of the indices

To obtain what you originally asked, set:

indices = tf.constant([[0, 0], [1, 0],[3, 0], [5, 0]], dtype=tf.int64)

Output:

array([[1, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]], dtype=int32)
MZHm
  • 2,388
  • 1
  • 18
  • 24
  • 1
    Thanks! Do you know how I can have dense_shape dynamically set? I have asked this question here https://stackoverflow.com/questions/44650464/tensorflow-sparsetensor-with-dynamically-set-dense-shape – Filipe Aleixo Jun 20 '17 at 10:34
  • Sure. Posted an answer at the link you sent – MZHm Jun 20 '17 at 12:30