【问题标题】:How to insert certain values at certain indices of a tensor in tensorflow?如何在张量流中张量的某些索引处插入某些值?
【发布时间】:2019-11-01 10:50:33
【问题描述】:

假设我有一个形状为100x1 的张量input 和另一个形状为20x1 的张量index_tensor 形状为100x1index_tensor 代表input 的位置,我想在其中插入来自inplace 的值。 index_tensor 只有 20 个 True 值,其余值为 False。我尝试在下面解释所需的操作。 使用tensorflow如何实现这个操作。

assign 操作仅适用于tf.Variable,而我想将其应用于tf.nn.rnn 的输出。

我读到可以使用tf.scatter_nd,但它要求inplaceindex_tensor 具有相同的形状。

我想使用它的原因是我从 rnn 得到一个输出,然后我从中提取一些值并将它们提供给一些密集层,这个来自密集层的输出,我想插入回原来的张量,我从 rnn 操作中获得。由于某些原因,我不想对 rnn 的整个输出应用密集层操作,如果我不将密集层的结果插入到 rnn 的输出中,那么密集层有点没用。

任何建议都将不胜感激。

【问题讨论】:

    标签: python tensorflow keras mutable tensor


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2020-10-30
      • 2018-09-15
      • 2020-12-25
      相关资源
      最近更新 更多