我的输入是索引列表,如
[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)
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)
归档时间: |
|
查看次数: |
72 次 |
最近记录: |