在张量流条件下减少总和

为我提供了具有随机行的2D张量。应用tf.math.greater()tf.cast(tf.int32)之后,剩下的张量为0和1。我现在想将归约和应用于该矩阵,但有一个条件:如果至少有一个1求和,并且后面跟随一个0,我也要删除所有后面的1,这意味着1 0 1应该导致1而不是2

我试图用tf.scan()解决问题,但是我仍然无法提出一个能够处理以0开头的函数,因为该行可能看起来像:0 0 0 1 0 1 一种想法是将矩阵的下部设置为1(据我所知,对角线剩下的一切始终为0),然后运行类似tf.scan()的函数来滤除斑点(请参见代码和错误消息)下面)。

Let z be the matrix after tf.cast.

helper = tf.matrix_band_part(tf.ones_like(z),-1,0)
z = tf.math.logical_or(tf.cast(z,tf.bool),tf.cast(helper,tf.bool))
z = tf.cast(z,tf.int32)
z = tf.scan(lambda a,x: x if a == 1 else 0,z)

结果:

ValueError: Incompatible shape for value ([]),expected ([5])

jiabing305 回答:在张量流条件下减少总和

IIUC,这是一种无需扫描或循环即可完成所需操作的方法。这可能有点令人费解,实际上是对列进行了两次迭代(一个cumsum和一个cumprod),但是作为矢量化操作,我认为它可能更快。代码为TF 2.x,但在TF 1.x中运行相同(显然,最后一行除外)。

import tensorflow as tf

# Example data
a = tf.constant([[0,0],[1,[0,1,1],1]])
# Cumsum columns
c = tf.math.cumsum(a,axis=1)
# Column-wise differences
diffs = tf.concat([tf.ones([tf.shape(c)[0],c.dtype),c[:,1:] - c[:,:-1]],axis=1)
# Find point where we should not sum anymore (cumsum is not zero and difference is zero)
cutoff = tf.equal(a,0) & tf.not_equal(c,0)
# Make mask
mask = tf.math.cumprod(tf.dtypes.cast(~cutoff,tf.uint8),axis=1)
# Compute result
result = tf.reduce_max(c * tf.dtypes.cast(mask,axis=1)
print(result.numpy())
# [0 1 2 1 3 2 3 4]
本文链接:https://www.f2er.com/3160615.html

大家都在问