Atr*_*ema 7 python mutable keras tensorflow tensor
假设我有一个inputshape张量100x1、另一个inplaceshape张量20x1和一个index_tensorshape 100x1。代表我想要插入值index_tensor的位置。只有20 个 True 值,其余值为 False。我尝试在下面解释所需的操作。
inputinplaceindex_tensor
使用tensorflow如何实现这个操作。
assign操作仅适用于tf.Variable我想将其应用于 的输出tf.nn.rnn。
我读到可以使用,tf.scatter_nd但它需要inplace和index_tensor具有相同的形状。
我想使用它的原因是我从 rnn 获得输出,然后我从中提取一些值并将它们输入到某个致密层,而来自致密层的输出,我想插入回从 rnn 获得的原始张量中手术。由于某些原因,我不想对 rnn 的整个输出应用密集层操作,如果我不将密集层的结果插入到 rnn 的输出中,那么密集层就没用了。
任何建议将不胜感激。
因为您拥有的张量是不可变的,所以您不能为其分配新值,也不能就地更改它。您要做的就是使用标准操作修改其值。以下是您可以如何做到这一点:
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3997 次 |
| 最近记录: |