TensorFlow学习(三):tf.scatter_nd函数

 

scatter_nd(indices,updates,shape,name=None)

根据indices将updates散布到新的(初始为零)张量。

根据索引对给定shape的零张量中的单个值或切片应用稀疏updates来创建新的张量。此运算符是tf.gather_nd运算符的反函数,它从给定的张量中提取值或切片。

警告:更新应用的顺序是非确定性的,所以如果indices包含重复项的话,则输出将是不确定的。

indices是一个整数张量,其中含有索引形成一个新的形状shape张量。indices的最后的维度可以是shape的最多的秩:

indices.shape[-1] <= shape.rank

indices的最后一个维度对应于沿着shape的indices.shape[-1]维度的元素的索引(if indices.shape[-1] = shape.rank)或切片(if indices.shape[-1] < shape.rank)的索引。updates是一个具有如下形状的张量:

indices.shape[:-1] + shape[indices.shape[-1]:]

最简单的分散形式是通过索引将单个元素插入到张量中。例如,假设我们想要在8个元素的1级张量中插入4个分散的元素。

TensorFlow函数

在Python中,这个分散操作看起来像这样:

indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
shape = tf.constant([8])
scatter = tf.scatter_nd(indices, updates, shape)
with tf.Session() as sess:
  print(sess.run(scatter))

由此产生的张量将如下所示:

[0, 11, 0, 10, 9, 0, 0, 12]

我们也可以一次插入一个更高阶张量的整个片。例如,如果我们想要在具有两个新值的矩阵的第三维张量中插入两个切片。

TensorFlow函数

在Python中,这个分散操作看起来像这样:

indices = tf.constant([[0], [2]])
updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]],
                       [[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]]])
shape = tf.constant([4, 4, 4])
scatter = tf.scatter_nd(indices, updates, shape)
with tf.Session() as sess:
  print(sess.run(scatter))

由此产生的张量将如下所示:

[[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

函数参数

  • indices:一个Tensor;必须是以下类型之一:int32,int64;指数张量。
  • updates:一个Tensor;分散到输出的更新。
  • shape:一个Tensor;必须与indices具有相同的类型;1-d;得到的张量的形状。
  • name:操作的名称(可选)。

函数返回值

此函数将返回一个Tensor,它与updates有相同的类型;根据indices应用的一个新具有给定的形状和更新的张量。

  • 15
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值