如何从 tf.SparseTensor 中删除明确的 0?

How can I drop explicit 0's from tf.SparseTensor?

在我的模型训练的每个时期,tf.SparseTensor 都会更改其值以具有更明确的零。去除这样的显式零将使显式边的数量变少,从而使整个计算速度更快。

所以,我需要一种方法来从 tf.SparseTensor 中删除显式零以使其更多 "slim"。有谁知道这样做的方法吗?

您可以使用 tf.sparse_retain() 操作解决此问题:

st = ...  # A `tf.SparseTensor` object.

# Compute a vector of booleans indicating which values of `st` should be dropped
# (if False) or retained (if True)
is_nonzero = tf.not_equal(st.values, 0)

# `tf.sparse_retain()` computes a new `tf.SparseTensor` with the specified values
# retained in the output.
st_without_zeros = tf.sparse_retain(st, is_nonzero)