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]
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.]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With