【发布时间】:2020-10-30 20:12:03
【问题描述】:
假设我在张量流中有两个张量,A,B(形状相同)。假设这些都是稀疏的。我需要知道其中一个张量在给定索引处具有非零值而另一个张量具有零值的实例的计数。所以,我正在寻找许多位置(i,j 对),其中一个矩阵在那里具有非零值,而另一个矩阵在那里具有零值。如何有效地做到这一点?
【问题讨论】:
标签: python tensorflow
假设我在张量流中有两个张量,A,B(形状相同)。假设这些都是稀疏的。我需要知道其中一个张量在给定索引处具有非零值而另一个张量具有零值的实例的计数。所以,我正在寻找许多位置(i,j 对),其中一个矩阵在那里具有非零值,而另一个矩阵在那里具有零值。如何有效地做到这一点?
【问题讨论】:
标签: python tensorflow
我会这样做:
import tensorflow as tf
tensor1 = tf.constant([[0, 1], [0, 2]])
tensor2 = tf.constant([[1, 0], [0, 2]])
a = tf.math.equal(tensor1, tf.zeros_like(tensor1))
b = tf.math.equal(tensor2, tf.zeros_like(tensor2))
c = tf.math.equal(a, b)
c = tf.cast(c, tf.int32)
c = tf.math.reduce_sum(c)
【讨论】:
import tensorflow as tf
a = tf.sparse.SparseTensor(
[[0,1], [1,1]], [1,2], [2,2]
)
b = tf.sparse.SparseTensor(
[[0,0], [0,1],[1,0]], [1,2,1], [2,2]
)
res = tf.reduce_sum(
tf.cast(tf.math.logical_xor(
tf.math.not_equal(tf.sparse.to_dense(a), 0),
tf.math.not_equal(tf.sparse.to_dense(b), 0)
), 'int32')
)
【讨论】:
这样就可以了。它根据这些条件对 True 案例进行汇总,逐个元素:
a 和 b 的值不相等a 不为零b 不为零tf.reduce_sum(
tf.cast(
tf.logical_and(
tf.not_equal(tf.sparse.to_dense(a), tf.sparse.to_dense(b)),
tf.cast(tf.sparse.to_dense(a), tf.bool),
tf.cast(tf.sparse.to_dense(b), tf.bool)),
tf.int32))
基于这两个稀疏张量:
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[1, 0, 2],
[0, 1, 0],
[0, 2, 1]])>
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[2, 2, 2],
[0, 0, 0],
[0, 2, 1]])>
完整示例:
import tensorflow as tf
a = tf.SparseTensor(indices=[[0, 0], [0, 2], [1, 1], [2, 1], [2, 2]],
values=[1, 2, 1, 2, 1], dense_shape=[3, 3])
b = tf.SparseTensor(indices=[[0, 0], [0, 1], [0, 2], [2, 1], [2, 2]],
values=[2, 2, 2, 2, 1], dense_shape=[3, 3])
tf.sparse.to_dense(a)
tf.sparse.to_dense(b)
tf.reduce_sum(
tf.cast(
tf.logical_and(
tf.not_equal(tf.sparse.to_dense(a), tf.sparse.to_dense(b)),
tf.cast(tf.sparse.to_dense(a), tf.bool),
tf.cast(tf.sparse.to_dense(b), tf.bool)),
tf.int32))
【讨论】: