python - TensorFlow - 密集向量到独热

标签 python tensorflow

假设我有以下张量:

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/

相关文章:

Tensorflow 服务性能与直接推理相比非常慢

python - Keras 嵌套模型单独保存和加载权重或查看所有嵌套模型的摘要

python - 用字符串替换 'match' 对象,Python

python - 打印文件名

python - 比较两个字典 - float

python - 根据现有检查点定义 TensorFlow 网络键名称

Python 多处理 : Crash in subprocess?

python - 可以在 pandas 数据框中创建子列吗?

python - 正确预处理 1D CNN 的 csv 数据

python - tensorflow 中的三阶张量与二阶张量相乘