gpt4 book ai didi

python - 使用 Tensorflow SparseTensors 进行高效 bool 掩蔽

转载 作者:行者123 更新时间:2023-12-01 07:15:25 25 4
gpt4 key购买 nike

所以,我想屏蔽 SparseTensor 的整行。使用 tf.boolean_mask 很容易做到这一点,但没有与 SparseTensor 等效的方法。目前,我可以只遍历 SparseTensor.indices 中的所有索引并过滤掉所有不是屏蔽行的索引,例如:

masked_indices = list(filter(lambda index: masked_rows[index[0]], indices))

其中 masked_rows 是一个一维数组,表示该索引处的行是否被屏蔽。

但是,这确实很慢,因为我的 SparseTensor 相当大(它有 90k 个索引,但会变得更大)。在对过滤后的索引应用 SparseTensor.mask 之前,在单个数据点上需要花费相当多的时间。该方法的另一个缺陷是它实际上也没有删除行(尽管在我的例子中,全零的行也可以)。

是否有更好的方法按行屏蔽 SparseTensor,或者这是最好的方法?

最佳答案

你可以这样做:

import tensorflow as tf

def boolean_mask_sparse_1d(sparse_tensor, mask, axis=0): # mask is assumed to be 1D
mask = tf.convert_to_tensor(mask)
ind = sparse_tensor.indices[:, axis]
mask_sp = tf.gather(mask, ind)
new_size = tf.math.count_nonzero(mask)
new_shape = tf.concat([sparse_tensor.shape[:axis], [new_size],
sparse_tensor.shape[axis + 1:]], axis=0)
new_shape = tf.dtypes.cast(new_shape, tf.int64)
mask_count = tf.cumsum(tf.dtypes.cast(mask, tf.int64), exclusive=True)
masked_idx = tf.boolean_mask(sparse_tensor.indices, mask_sp)
new_idx_axis = tf.gather(mask_count, masked_idx[:, axis])
new_idx = tf.concat([masked_idx[:, :axis],
tf.expand_dims(new_idx_axis, 1),
masked_idx[:, axis + 1:]], axis=1)
new_values = tf.boolean_mask(sparse_tensor.values, mask_sp)
return tf.SparseTensor(new_idx, new_values, new_shape)

# Test
sp = tf.SparseTensor([[1], [3], [4], [6]], [1, 2, 3, 4], [7])
mask = tf.constant([True, False, True, True, False, False, True])
out = boolean_mask_sparse_1d(sp, mask)
print(out.indices.numpy())
# [[2]
# [3]]
print(out.values.numpy())
# [2 4]
print(out.shape)
# (4,)

关于python - 使用 Tensorflow SparseTensors 进行高效 bool 掩蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57998859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com