代码之家  ›  专栏  ›  技术社区  ›  Panfeng Li

tensorflow中的元素分配

  •  0
  • Panfeng Li  · 技术社区  · 7 年前

    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)
    

    然而,在张力流中似乎没有类似的操作。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Jie.Zhou    7 年前

    由于张量值的变化不可通过反向传播追踪,因此永远不能为张量流中的张量赋值,但仍然可以从原始张量中获取另一张量,下面是一个解决方案

    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
  •  0
  •   Kaihong Zhang    7 年前

    其实有一个方法可以达到这个目的。很像@Jie.Zhou的回答,你可以替换 tf.constant 具有 tf.Variable ,然后替换 tf.scatter_nd 具有 tf.scatter_nd_update

    推荐文章