张量和稀疏张量有什么区别?

2024-06-16 10:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解张量流张量稀疏张量的含义和用法。

根据文件

张量

Tensor is a typed multi-dimensional array. For example, you can represent a mini-batch of images as a 4-D array of floating point numbers with dimensions [batch, height, width, channels].

稀疏张量

TensorFlow represents a sparse tensor as three separate dense tensors: indices, values, and shape. In Python, the three tensors are collected into a SparseTensor class for ease of use. If you have separate indices, values, and shape tensors, wrap them in a SparseTensor object before passing to the ops below.

我的理解是张量用于运算、输入和输出。稀疏张量只是张量(稠密)的另一种表示。希望有人能进一步解释这些差异,以及它们的用例。


Tags: andoftheyouasbatcharraythree
2条回答

马修做得很好,但我想用一个例子来说明稀疏张量。

如果张量有很多值为零,则可以称之为稀疏。

让我们考虑一个稀疏的一维张量

[0, 7, 0, 0, 8, 0, 0, 0, 0]

相同张量的稀疏表示只关注非零值

values = [7,8]

我们还必须记住这些值出现在哪里,通过它们的索引

indices = [1,5]

对于这个一维示例,一维索引表单将使用一些方法,但一般来说,索引具有多个维度,因此表示这样的索引将更加一致(并且在任何地方都有效):

indices = [[1], [5]]

关于值和指数,我们还没有足够的信息。有多少个零?我们表示张量的稠密形状。

 dense_shape = [9]

这三样东西,值、索引和稠密形状,是张量的稀疏表示

在TensorFlow2.0中,它可以实现为

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)

不同之处在于计算速度。如果一个大张量有很多很多个零,通过迭代非零元素来执行计算会更快。因此,您应该将数据存储在SparseTensor中,并使用SparseTensors的特殊操作。

矩阵和稀疏矩阵的关系类似。稀疏矩阵在动态系统中很常见,数学家已经发展了许多特殊的运算方法。

相关问题 更多 >