假设我有以下张量:
T = [[0.1, 0.3, 0.7],
[0.2, 0.5, 0.3],
[0.1, 0.1, 0.8]]
我想将其转换为一个单热张量,使得维度 0 上最大值的索引设置为 1,所有其他索引设置为 0,如下所示:
T_onehot = [[0, 0, 1],
[0, 1, 0],
[0, 0, 1]]
我知道有 tf.argmax
可以获取张量中最大元素的索引,但是有没有任何方法可以让我一步完成我想做的事情?
最佳答案
我不知道是否有办法一步完成此操作,但是tensorflow中有一个one_hot
函数:
import tensorflow as tf
T = tf.constant([[0.1, 0.3, 0.7], [0.2, 0.5, 0.3], [0.1, 0.1, 0.8]])
T_onehot = tf.one_hot(tf.argmax(T, 1), T.shape[1])
tf.InteractiveSession()
print(T_onehot.eval())
# [[ 0. 0. 1.]
# [ 0. 1. 0.]
# [ 0. 0. 1.]]
关于python - TensorFlow - 密集向量到独热,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44724948/