【问题标题】:Element-wise assignment in tensorflow张量流中的元素分配
【发布时间】:2018-08-07 14:43:54
【问题描述】:

numpy,可以很容易做到

>>> img
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]], dtype=int32)
>>> img[img>5] = [1,2,3,4]
>>> img
array([[1, 2, 3],
       [4, 5, 1],
       [2, 3, 4]], dtype=int32)

但是,tensorflow中似乎没有类似的操作。

【问题讨论】:

标签: numpy tensorflow


【解决方案1】:

你永远不能在张量流中为张量赋值,因为张量值的变化不能通过反向传播来追踪,但你仍然可以从原始张量获得另一个张量,这是一个解决方案

import tensorflow as tf
tf.enable_eager_execution()
img = tf.constant(list(range(1, 10)), shape=[3, 3])
replace_mask = img > 5
keep_mask = tf.logical_not(replace_mask)
keep = tf.boolean_mask(img, keep_mask)

keep_index = tf.where(keep_mask)
replace_index = tf.where(replace_mask)

replace = tf.random_uniform((tf.shape(replace_index)[0],), 0, 10, tf.int32)

updates = tf.concat([keep, replace], axis=0)
indices = tf.concat([keep_index, replace_index], axis=0)

result = tf.scatter_nd(tf.cast(indices, tf.int32), updates, shape=tf.shape(img))

【讨论】:

    【解决方案2】:

    其实是有办法实现的。与@Jie.Zhou 的回答非常相似,您可以将tf.constant 替换为tf.Variable,然后将tf.scatter_nd 替换为tf.scatter_nd_update

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2019-03-20
      • 2018-07-02
      • 2018-04-18
      • 2016-06-16
      相关资源
      最近更新 更多