在tensorflow中,如何将索引列表转换为指标向量?

don*_*loo 6 python tensorflow

我的输入是索引列表,如

[1,3], [0,1,2]
Run Code Online (Sandbox Code Playgroud)

如何将它们转换为固定长度指示矢量?

[0, 1, 0, 1], [1, 1, 1, 0]
Run Code Online (Sandbox Code Playgroud)

kaf*_*man 5

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))
Run Code Online (Sandbox Code Playgroud)

这打印

[[1. 1. 0. 1.]
 [1. 1. 1. 0.]]
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于所有索引在列表的每个条目中具有相同数量的索引的情况.如果不是这种情况,你可以用循环来做:

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))
Run Code Online (Sandbox Code Playgroud)

这打印

[[0. 1. 0. 1.]
 [1. 1. 1. 0.]]
Run Code Online (Sandbox Code Playgroud)

  • 正如对未来的评论一样,TensorFlow 2.x将支持[参差不齐的张量](https://www.tensorflow.org/guide/ragged_tensors),因此可以在不循环的情况下针对不同数量的索引执行此操作. (2认同)