TensorFlow- 基础语法-one_hot()

参考声明:https://blog.csdn.net/nini_coded/article/details/79250600

0.函数简介:

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

1.函数用法:

one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)

    Returns a one-hot tensor.

    The locations represented by indices in `indices` take value `on_value`,

    while all other locations take value `off_value`.

indices反映了位置信息,one_hot()函数根据这一位置信息,

在相应位置填入on_value的值;

在其他位置上填入off_valuse的值;

indices 输入数据,tensor
depth 输出的的尺寸
on_value

当indices[j] = i,输出的位置填入的on_value,默认为1

off_value 当indices[j] != i,输出的位置填入的off_value,默认为0
axis 默认为-1
dtype 输出tensor的类型
name 定义计算的名称


由于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]。

2.程序示例:

# -*-coding:utf-8 -*-
import tensorflow as tf

indices = [0,1,2,3,4,5]
depth = 6
one_hot_value = tf.one_hot(indices=indices,depth=depth)

with tf.Session() as sess:
    print(sess.run(one_hot_value))
#result:
# [[1. 0. 0. 0. 0. 0.]
#  [0. 1. 0. 0. 0. 0.]
#  [0. 0. 1. 0. 0. 0.]
#  [0. 0. 0. 1. 0. 0.]
#  [0. 0. 0. 0. 1. 0.]
#  [0. 0. 0. 0. 0. 1.]]

猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/82317169
今日推荐