Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in tensorflow, how do I convert a list of indices to an indicator vector?

My input are lists of indices like

[1,3], [0,1,2]

how can I convert them into fixed length indicator vectors?

[0, 1, 0, 1], [1, 1, 1, 0]
like image 654
dontloo Avatar asked Feb 26 '19 08:02

dontloo


1 Answers

import tensorflow as tf

indices = [[1, 3, 0], [0, 1, 2]]
many_hot = tf.one_hot(indices, depth=4)
many_hot = tf.reduce_sum(many_hot, axis=1)

with tf.Session() as sess:
    print(sess.run(many_hot))

This prints

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

Note that this only works if all the indices have the same amount of indices in each entry of the list. If this is not the case, you could do it with a loop:

import tensorflow as tf

indices = [[1, 3], [0, 1, 2]]
many_hots = []
for idx in indices:
    many_hot = tf.one_hot(idx, depth=4)
    many_hot = tf.reduce_sum(many_hot, axis=0)
    many_hots.append(many_hot)

many_hot = tf.stack(many_hots)

with tf.Session() as sess:
    print(sess.run(many_hot))

This prints

[[0. 1. 0. 1.]
 [1. 1. 1. 0.]]
like image 104
kafman Avatar answered Sep 30 '22 19:09

kafman