擅长:python、mysql、java
<p>马修做得很好,但我想用一个例子来说明稀疏张量。</p>
<p><strong>如果张量有很多值为零,则可以称之为稀疏。</strong></p>
<p>让我们考虑一个稀疏的一维张量</p>
<pre><code>[0, 7, 0, 0, 8, 0, 0, 0, 0]
</code></pre>
<p>相同张量的稀疏表示只关注非零值</p>
<pre><code>values = [7,8]
</code></pre>
<p>我们还必须记住这些值出现在哪里,通过它们的索引</p>
<pre><code>indices = [1,5]
</code></pre>
<p>对于这个一维示例,一维索引表单将使用一些方法,但一般来说,索引具有多个维度,因此表示这样的索引将更加一致(并且在任何地方都有效):</p>
<pre><code>indices = [[1], [5]]
</code></pre>
<p>关于值和指数,我们还没有足够的信息。有多少个零?我们表示张量的稠密形状。</p>
<pre><code> dense_shape = [9]
</code></pre>
<p>这三样东西,值、索引和稠密形状,是张量的稀疏表示</p>
<p>在TensorFlow2.0中,它可以实现为</p>
<pre><code>x = tf.SparseTensor(values=[7,8],indices=[[1],[5]],dense_shape=[9])
x
#o/p: <tensorflow.python.framework.sparse_tensor.SparseTensor at 0x7ff04a58c4a8>
print(x.values)
print(x.dense_shape)
print(x.indices)
#o/p:
tf.Tensor([7 8], shape=(2,), dtype=int32)
tf.Tensor([9], shape=(1,), dtype=int64)
tf.Tensor(
[[1]
[5]], shape=(2, 1), dtype=int64)
</code></pre>