如何在tensorflow中的特定索引处插入特定值?

7
假设我有一个形状为100x1的张量input,另一个形状为20x1的张量inplace和一个形状为100x1index_tensorindex_tensor表示我想要将inplace的值插入到input的位置。 index_tensor只有20个True值,其余值为False。 我尝试在下面解释所需的操作。 enter image description here 如何使用tensorflow实现此操作。 assign操作仅适用于tf.Variable,而我希望将其应用于tf.nn.rnn的输出。 我读到可以使用tf.scatter_nd,但它要求inplaceindex_tensor具有相同的形状。
我想使用这个的原因是,我从rnn得到一个输出,然后从中提取一些值并将它们馈送到某些密集层,我希望将这个密集层的输出插回到我从rnn操作中获得的原始张量中。由于某些原因,我不想对整个rnn输出应用密集层操作,如果我不将密集层的结果插入到rnn输出中,那么密集层就有点无用了。

任何建议将不胜感激。

1个回答

3
因为您拥有的张量是不可变的,所以您无法对其进行重新赋值或原地更改。您需要使用标准操作来修改它的值。以下是如何执行此操作:
input_array = np.array([2, 4, 7, 11, 3, 8, 9, 19, 11, 7])
inplace_array = np.array([10, 20])
indices_array = np.array([0, 0, 1, 0, 0, 0, 1, 0, 0, 0])
# [[2], [6]] 
indices = tf.cast(tf.where(tf.equal(indices_array, 1)), tf.int32)
# [0, 0, 10, 0, 0, 0, 20, 0, 0, 0]
scatter = tf.scatter_nd(indices, inplace_array, shape=tf.shape(input_array))
# [1, 1, 0, 1, 1, 1, 0, 1, 1, 1]
inverse_mask = tf.cast(tf.math.logical_not(indices_array), tf.int32)
# [2, 4, 0, 11, 3, 8, 0, 19, 11, 7]
input_array_zero_out = tf.multiply(inverse_mask, input_array)
# [2, 4, 10, 11, 3, 8, 20, 19, 11, 7]
output = tf.add(input_array_zero_out, tf.cast(scatter, tf.int32))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接