tensorflow2.0 one_hot()函数

转载自@Dymc的博客tensorflow2.0之one_hot函数使用

one_hot()函数的主要功能是将张量转换成one_hot(独热)类型的张量输出。

使用语法
one_hot(
	indices,		#输入的tensor,在深度学习中一般是给定的labels,通常是数字列表,属于一维输入输入,也可是多维
	depth,			#一个标量,用于定义one hot维度的深度
	on_value=None,		#定义在indices[j] = i 时填充输出的值的标量,默认为1
	off_value=None,			#定义在indices[j] !=i 时填充输出的值的标量,默认为0
	axis=-1,			#要填充的轴,默认为-1,即一个新的最内层轴
	dtype=None,			#默认为int32
	name=None
)

简单看个例子,理解一下上面的语法:

import tensorflow as tf
labels = [0, 6, 5, 4, 2]
res = tf.one_hot(
	indices=labels,
	depth=10,
	on_value=1,
	off_value=0,
	axis=-1
	)
print(res)

输出结果:

tf.Tensor(
[[1 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]], shape=(5, 10), dtype=int32)

可以看到张量res的形状为 5 ∗ 10 ( 5 ∗ d e p t h ) 5*10(5 * depth) 510(5depth),并且
res[0][0] = 1
res[1][6] = 1
res[2][5] = 1
res[3][4] = 1
res[4][2] = 1
其余均为0。
indices用来确定生成的张量中哪些位置为on_value
axis的取值不同会影响输出的shape结构。主要有以下几种情况:

axisindices为向量indices 为矩阵
-1n * depthw * h * depth
0depth * ndepth * w * h
1w * depth * h
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值