介绍
实现one hot编码,返回 one-hot tensor
关于 one hot编码,详见:
https://www.malaoshi.top/show_1EF3QPTxusan.html
语法
tf.one_hot(
indices,
depth,
on_value=None,
off_value=None,
axis=None,
dtype=None,
name=None
)
参数
- indices:tensor
- depth:编码深度,必须传入
- on_value:编码的开始值,默认为1。与 dtype 相匹配
- off_value:编码的结束值,默认为0。与 dtype 相匹配
- axis=None:轴
- dtype=None:数据类型
返回值
tensor
例子
一维
import numpy as np
import tensorflow as tf
arr=np.array([0,1,2,3])
oh=tf.one_hot(arr,depth=4)
oh
执行结果:
<tf.Tensor: id=549, shape=(4, 4), dtype=float32, numpy=
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]], dtype=float32)>
二维
arr=np.array([[0,1,2,3],[3,2,1,0]])
oh=tf.one_hot(arr,depth=4)
oh
执行结果:
<tf.Tensor: id=576, shape=(2, 4, 4), dtype=float32, numpy=
array([[[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]],
[[0., 0., 0., 1.],
[0., 0., 1., 0.],
[0., 1., 0., 0.],
[1., 0., 0., 0.]]], dtype=float32)>