python - 如何在 tensorflow 中的张量的某些索引处插入某些值?

标签 python tensorflow keras mutable tensor

假设我有一个张量 input 的形状 100x1 和另一个张量 inplace 的形状 20x1 和一个形状为 100x1index_tensorindex_tensor 表示 input 的位置,我想从 inplace 中插入值。 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 的输出中,那么密集层就没用了。

任何建议将不胜感激。

最佳答案

因为您拥有的张量是不可变的,所以您不能为其分配新值,也不能就地更改它。您要做的是使用标准操作修改它的值。以下是您的操作方法:

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))

关于python - 如何在 tensorflow 中的张量的某些索引处插入某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56655103/

相关文章:

Python - Windows 关机事件

python - WALS Model Tensorflow - 为新用户获取推荐

python - 凯拉斯错误 : Expected to see 1 array

python - 如何统计有多少条记录在字段中具有最小值? ( Django )

python - 在 Windows 中显示资源管理器的文件属性对话框

python - 查找共享相同多对多关系的重复记录集

python - 在谷歌云存储上保存模型历史

python - 在带有 Tensorflow 张量的 Keras 模型中使用 InputLayer(或 Input)有什么好处?

python - 在 Keras 中多次调用 "fit_generator()"

python-3.x - 使用 model.predict 输出作为另一个模型的输入