数字标签转化为one-hot形式的tensor

刚刚入tensorflow的大坑,根据自己的理解今天来记录一下如何将数字标签转化为one-hot形式。有错误的请谅解哈哈哈
what is form of one-hot ?即用包含0和1的tensor来表示数字标签,数字1所在的索引值(从0开始)即为我们的数字标签,例如我们有0-9的数字标签,则标签5所对应的one-hot形式为[0 , 0 , 0 , 0 , 0 ,1 , 0 , 0 , 0 , 0],因为1所在位置的索引值为5。
And how to transform the digital labels into one-hot tensor ? 我先把tensorflow 官网(tensorflow.google.cn)上的代码贴出来:

《数字标签转化为one-hot形式的tensor》

现在看看每一个语句的作用:

1.batch_size = tf.size(labels)

我们需要对所有的数字标签进行转换,所以第一步,先通过上述语句获取标签的个数。比如,我们的标签数组为 labels = [1 , 4 , 6 , 8 , 3 , 7],则有
《数字标签转化为one-hot形式的tensor》

2.labels_1 = tf.expand_dims(labels, 1)

该语句的是将labels的维度索引轴axis为1处(从0开始)插入1的尺寸。现在我们先看看labels的shape:
《数字标签转化为one-hot形式的tensor》
那么,经过语句2之后,有《数字标签转化为one-hot形式的tensor》

如上所述
从一开始的shape[6](axis=0处有6个值)变成了shape[6,1](axis=0时有6个值,axis=1处插入1),不清楚的话可以试试:
labels_1 = tf.expand_dims(labels, 0)

补充: tf.expand_dims(input, axis=None)函数表示给定输入tensor,在输入shape的维度索引轴axis处插入为1的尺寸。 维度索引轴从0开始; 如果axis为负数,则从后向前计数。

3.indices =    tf.expand_dims(tf.range(0,batch_size,1),1)

tf.range(start, limit, delta=1)函数是用来生成tensor等差序列,序列在start到limit之间(包含start不包含limit),步长为dalta。
语句3先生成0-5的向量,再同语句2同样的扩展维度:
《数字标签转化为one-hot形式的tensor》

4.concated = tf.concat([indices, labels_1],1)

concated = tf.concat([indices, labels_1],concat_dim)表示在第concat_dim+1个维度叠加,例如,语句4的输出为:

《数字标签转化为one-hot形式的tensor》
其中,concat_dim=0(第一个维度)可以认为是行,concat_dim=1(第二个维度)为列,所以语句4 在列上叠加。更多维度的信息自行查阅。

5.onehot_labels = tf.sparse_to_dense(concated, tf.stack([batch_size, 10]), 1.0, 0.0)

在语句5中,concated矩阵(如上图)表示[0,1],[1,4]….[5,9]有值,tf.stack([batch_size, 10])表示输出的one-hot矩阵,每一行表示一个标签对应的ont-hot形式。1.0为one-hot的意义所在,即ont-hot矩阵中对应于concated矩阵有值的位置为1.0,然后0.0表示没值的位置为0.0。
语句5 的输出结果如图:
《数字标签转化为one-hot形式的tensor》

    原文作者:m0_37190018
    原文地址: https://blog.csdn.net/m0_37190018/article/details/82257754
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞