Tensorflow——————API 使用方法记录

1.tf.one_hot

 返回一个onehot tensor

tf.one_hot(
    indices,   
    depth,
    on_value=None,
    off_value=None,
    axis=None,
    dtype=None,
    name=None
)
  • indices: tensor类型值得索引.

  • depth: 代表one-hot得深度,可以理解为对应得类别数.

  • on_value: 一个标量值,索引位置上得值. (default: 1).

  • off_value: 索引之外的值. (default: 0)

  • axis: 新的维度,也就是填充的所在轴 (default: -1,).

  • dtype: The data type of the output tensor.

  • name: op节点名称 (optional).

一个N维的输入,则输出维度为N+1,意思就是:如果输入是一个标量,则输出为一个固定深度的向量;如果输入是一个 固定深度的向量,则输出是一个二维tensor。上述两个输入,又分两个情况(axis=-1或者0)。

# 输入为标量  
[features, depth] if axis == -1
[depth, features] if axis == 0

# 输入为固定长度的向量
[batch, features x depth] if axis == -1
[batch, depth x features] if axis == 1
[depth, batch x features] if axis == 0

举例如下:

# 标量
indices = 3
depth = 4
a = tf.one_hot(indices, depth, axis=-1) 
sess = tf.InteractiveSession()
print(sess.run(a))

# 输出
# axis=-1或者0,结果都是一样的,因为就一个维度,怎么取都是那一个。。。。。
[0. 0. 0. 1.]

--------------------------------------------------------------------------------

# 输入为固定长度向量
indices = [0, 1, 3, 2]
depth = 5
a = tf.one_hot(indices, depth, axis=-1) 
sess = tf.InteractiveSession()
print(sess.run(a))

# axis=-1时
[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0.]]
# axis=0时
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 0. 1.]
 [0. 0. 1. 0.]
 [0. 0. 0. 0.]]

当输出为[batch, features]时(训练的时候都是批次的),输出维度应该是这样的:

[batch, features, depth] if axis == -1
[batch, depth, features] if axis == 1
[depth, batch, features] if axis == 0

举例:

# 对这种输入的one-hot,我是一般不会遇到,平时模型训练,label都是一维的
indices = [[0, 2], [1, -1], [2, 3]]
depth = 5
a = tf.one_hot(indices, depth, axis=-1) 
sess = tf.InteractiveSession()
print(sess.run(a))

# 输出
# aixs=-1
[[[1. 0. 0. 0. 0.]
  [0. 0. 1. 0. 0.]]

 [[0. 1. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]

 [[0. 0. 1. 0. 0.]
  [0. 0. 0. 1. 0.]]]

# axis=0
[[[1. 0.]
  [0. 0.]
  [0. 0.]]

 [[0. 0.]
  [1. 0.]
  [0. 0.]]

 [[0. 1.]
  [0. 0.]
  [1. 0.]]

 [[0. 0.]
  [0. 0.]
  [0. 1.]]

 [[0. 0.]
  [0. 0.]
  [0. 0.]]]

持续更新·············

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值