自1.15版本起,Tensorflow提供了tf.sparse.from_dense
。例如:
In [1]: import tensorflow as tf
In [2]: x = tf.eye(3) * 5
In [3]: x
Out[3]:
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[5., 0., 0.],
[0., 5., 0.],
[0., 0., 5.]], dtype=float32)>
应用
tf.sparse.from_dense
:
In [4]: y = tf.sparse.from_dense(x)
In [5]: y.values
Out[5]: <tf.Tensor: shape=(3,), dtype=float32, numpy=array([5., 5., 5.], dtype=float32)>
In [6]: y.indices
Out[6]:
<tf.Tensor: shape=(3, 2), dtype=int64, numpy=
array([[0, 0],
[1, 1],
[2, 2]])>
通过应用tf.sparse.to_dense
来验证身份:
In [7]: tf.sparse.to_dense(y) == x
Out[7]:
<tf.Tensor: shape=(3, 3), dtype=bool, numpy=
array([[ True, True, True],
[ True, True, True],
[ True, True, True]])>