Numpy tensorflow中的元素赋值

Numpy tensorflow中的元素赋值,numpy,tensorflow,Numpy,Tensorflow,在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
中,它可以像

>>> 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中似乎不存在类似的操作。

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

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

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

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

事实上,有一种方法可以做到这一点。与@Jie.Zhou的答案非常相似,您可以将
tf.constant
替换为
tf.Variable
,然后将
tf.scatter\u nd
替换为
tf.scatter\u\u update
实际上有一种方法可以实现这一点。与@Jie.Zhou的答案非常相似,您可以将
tf.constant
替换为
tf.Variable
,然后将
tf.scatter\u nd
替换为
tf.scatter\u更新

tf.select
替换为
tf.where
。此外,这里我想分配随机值,但不只是从原始数组或
0
s<代码>tf。选择将替换为
tf。其中
。此外,这里我想分配随机值,但不只是从原始数组或
0
s。