您的位置:首页 > 其它

tf.one_hot()函数简介

2018-02-04 01:07 1321 查看
tf.one_hot()函数是将input转化为one-hot类型数据输出,相当于将多个数值联合放在一起作为多个相同类型的向量,可用于表示各自的概率分布,通常用于分类任务中作为最后的FC层的输出,有时翻译成“独热”编码。

tensorflow的help中相关说明如下:

one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
Returns a one-hot tensor.


indices表示输入的多个数值,通常是矩阵形式;depth表示输出的尺寸。

由于one-hot类型数据长度为depth位,其中只用一位数字表示原输入数据,这里的on_value就是这个数字,默认值为1,one-hot数据的其他位用off_value表示,默认值为0。

tf.one_hot()函数规定输入的元素indices从0开始,最大的元素值不能超过(depth - 1),因此能够表示(depth + 1)个单位的输入。若输入的元素值超出范围,输出的编码均为 [0, 0 … 0, 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 : ', array([[ 1.,  0.,  0.],
#       [ 0.,  1.,  0.],
#       [ 0.,  0.,  1.]], dtype=float32))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tensorflow