一、独热编码
独热编码(one-hot encoding),独热编码一般是在有监督学习中对数据集进行标注时候使用的,指的是在分类问题中,将存在数据类别的那一类用X表示,不存在的用Y表示,这里的X常常是1, Y常常是0。
e.g.如果我们有3类问题,有数据(Xi,Yi),其中类别Yi有3种取值。
如果Yj为第一类那么其独热编码为:
如果Yj为第二类那么其独热编码为:
只对存在有该类别的数的位置上进行标记为1,其他皆为0。一般用于计算交叉熵损失函数。
二、tf.one_hot()
tf.one_hot()函数是将input转化为one-hot类型数据输出,相当于将多个数值联合放在一起作为多个相同类型的向量,可用于表示各自的概率分布,通常用于分类任务中作为最后的FC层的输出,有时翻译成“独热”编码。
one_hot(
indices,#输入,这里是一维的
depth,# one hot dimension.
on_value=None,#output 默认1
off_value=None,#output 默认0
axis=None,
dtype=None,
name=None
)
需要指定indices,和depth,其中depth是编码深度,on_value和off_value相当于是编码后的开闭值,如同我们刚才描述的X值和Y值,需要和dtype相同类型(指定了dtype的情况下),axis指定编码的轴。
indices表示输入的多个数值,通常是矩阵形式;depth表示输出的尺寸。
由于one-hot类型数据长度为depth位,其中只用一位数字表示原输入数据,这里的on_value就是这个数字,默认值为1,one-hot数据的其他位用off_value表示,默认值为0。
indices = 0 对应的输出是[1, 0 … 0, 0], indices = 1 对应的输出是[0, 1 … 0, 0], 依次类推,最大可能值的输出是[0, 0 … 0, 1]。
三、例子
import tensorflow as tf
classes = 3
labels = tf.constant([0,1,2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels,classes)
sess = tf.Session()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
output = sess.run(output)
print("output of one-hot is : ",output)
output of one-hot is :
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]