How to get a dense view of one hot vector

Suppose a Tensorcontains:

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

How to get a tight idea on your own path (without using numpyor iterations)?

[2,1,0]

There tf.one_hot()is to do the opposite, there is also tf.sparse_to_dense()one that seems to be doing this, but I could not figure out how to use it.

+4
source share
3 answers
vec = tf.constant([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
locations = tf.where(tf.equal(vec, 1))
# This gives array of locations of "1" indices below
# => [[0, 2], [1, 1], [2, 0]])

# strip first column
indices = locations[:,1]
sess = tf.Session()
print(sess.run(indices))
# => [2 1 0]
+6
source

tf.argmax(x, axis=1) must complete the task.

+5
source

TensorFlow /. , , , , .

def dense_to_sparse(dense_tensor):
    where_dense_non_zero = tf.where(tf.not_equal(dense_tensor, 0))
    indices = where_dense_non_zero
    values = tf.gather_nd(dense_tensor, where_dense_non_zero)
    shape = dense_tensor.get_shape()

    return tf.SparseTensor(
        indices=indices,
        values=values,
        shape=shape
    )

, . , .

tf.sparse_to_dense, . , [2, 1, 0], . , 0:

indices = tf.where(tf.not_equal(dense_tensor, 0))

, /:

output = indices[:, 1]

, 1 - 1. , , - :

output = indices[:, len(dense_tensor.get_shape()) - 1]

, ( , ). , !

EDIT : Yaroslav's answer is better if you are looking for indexes / locations, where is the input tensor if 1; it will not expand for tensors with non-1/0 values, if necessary.

+2
source

Source: https://habr.com/ru/post/1657311/


All Articles