如何最好地在张量流中实现矩阵掩码操作?

Zak*_*irn 4 python numpy image-processing tensorflow

我有一个案例,我需要在 tensorflow 的图像处理应用程序中填充一些漏洞(丢失的数据)。“洞”很容易定位,因为它们是零,而好的数据不是零。我想用随机数据填充漏洞。使用 python numpy 很容易做到这一点,但在 tensorflow 中做到这一点需要一些工作。我想出了一个解决方案,想看看是否有更好或更有效的方法来做同样的事情。我知道 tensorflow 尚不支持更高级的 numpy 类型索引,但有一个函数 tf.gather_nd() 似乎对此很有希望。但是,我无法从文档中得知我想要做什么。如果有人能告诉我如何使用 tf.gather_nd() 来做,我将不胜感激。此外,tf。boolean_mask() 不适用于我正在尝试做的事情,因为它不允许您将输出用作索引。在 python 中,我想做什么:

a = np.ones((2,2))
a[0,0]=a[0,1] = 0
mask = a == 0
a[mask] = np.random.random_sample(a.shape)[mask]
print('new a = ', a)
Run Code Online (Sandbox Code Playgroud)

我最终在 Tensorflow 中做了什么来实现同样的事情(跳过填充数组的步骤)

zeros = tf.zeros(tf.shape(a))  
mask = tf.greater(a,zeros)
mask_n = tf.equal(a,zeros)
mask = tf.cast(mask,tf.float32)
mask_n = tf.cast(mask_n,tf.float32
r = tf.random_uniform(tf.shape(a),minval = 0.0,maxval=1.0,dtype=tf.float32)
r_add = tf.multiply(mask_n,r)
targets = tf.add(tf.multiply(mask,a),r_add)
Run Code Online (Sandbox Code Playgroud)

Aar*_*ron 5

我认为这三行可能会做你想要的。首先,你做一个面具。然后,您创建随机数据。最后,用随机数据填充掩码值。

mask = tf.equal(a, 0.0)
r = tf.random_uniform(tf.shape(a), minval = 0.0,maxval=1.0,dtype=tf.float32)
targets = tf.where(mask, r, a)
Run Code Online (Sandbox Code Playgroud)