gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:00:55 26 4
gpt4 key购买 nike

我的输入是像这样的索引列表

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

如何将它们转换为固定长度的指标向量?

[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))

这打印

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

请注意,这仅在所有索引在列表的每个条目中具有相同数量的索引时才有效。如果不是这种情况,您可以使用循环来完成:

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))

这打印

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

关于python - 在 tensorflow 中,如何将索引列表转换为指标向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54881627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com