第15章 TensorFlow 中的稀疏张量:高效存储与处理指南
第15章:稀疏张量
处理稀疏张量
使用集合保持井井有条
根据您的偏好保存和分类内容。
在 TensorFlow.org 上查看
在 Google Colab 中运行
在 GitHub 上查看
下载笔记本
TensorFlow 中的稀疏张量
TensorFlow 通过 tf.sparse.SparseTensor 对象来表示稀疏张量。目前,TensorFlow 中的稀疏张量使用坐标列表(COO)格式进行编码。这种编码格式针对超稀疏矩阵(如嵌入层)进行了优化。
稀疏张量的 COO 编码由以下部分组成:
- values:形状为 [N] 的一维张量,包含所有非零值。
- indices:形状为 [N, rank] 的二维张量,包含非零值的索引。
- dense_shape:形状为 [rank] 的一维张量,指定张量的形状。
在 tf.sparse.SparseTensor 的语境下,非零值是指未被显式编码的值。COO 稀疏矩阵的 values 中可能包含显式的零值,但在提及稀疏张量中的非零值时,通常不包括这些“显式零值”。
创建 tf.sparse.SparseTensor
通过直接指定其 values、indices 和 dense_shape 来构造稀疏张量。
import tensorflow as tf
2024-10-25 01:24:09.202320: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:477] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1729819449.223893 16549 cuda_dnn.cc:8310] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
E0000 00:00:1729819449.230517 16549 cuda_blas.cc:1418] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
st1 = tf.sparse.SparseTensor(indices=[[0, 3], [2, 4]],
values=[10, 20],
dense_shape=[3, 10])
W0000 00:00:1729819451.911465 16549 gpu_device.cc:2344] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
使用 print() 函数打印稀疏张量时,会显示三个组件张量的内容:
print(st1)
SparseTensor(indices=tf.Tensor(
[[0 3]
[2 4]], shape=(2, 2), dtype=int64), values=tf.Tensor([10 20], shape=(2,), dtype=int32), dense_shape=tf.Tensor([ 3 10], shape=(2,), dtype=int64))
如果将非零值与其对应的索引对齐,理解稀疏张量的内容会更容易。下面定义一个辅助函数,以格式化方式打印稀疏张量,使每个非零值单独一行显示。
def pprint_sparse_tensor(st):
s = "<SparseTensor shape=%s \n values={" % (st.dense_shape.numpy().tolist(),)
for (index, value) in zip(st.indices, st.values):
s += f"\n %s: %s" % (index.numpy().tolist(), value.numpy().tolist())
return s + "}>"
print(pprint_sparse_tensor(st1))
<SparseTensor shape=[3, 10]
values={
[0, 3]: 10
[2, 4]: 20}>
您也可以通过 tf.sparse.from_dense 从稠密张量构造稀疏张量,并使用 tf.sparse.to_dense 将其转换回稠密张量。
st2 = tf.sparse.from_dense([[1, 0, 0, 8], [0, 0, 0, 0], [0, 0, 3, 0]])
print(pprint_sparse_tensor(st2))
<SparseTensor shape=[3, 4]
values={
[0, 0]: 1
[0, 3]: 8
[2, 2]: 3}>
st3 = tf.sparse.to_dense(st2)
print(st3)
tf.Tensor(
[[1 0 0 8]
[0 0 0 0]
[0 0 3 0]], shape=(3, 4), dtype=int32)
操作稀疏张量
使用 tf.sparse 包中的工具来操作稀疏张量。像 tf.math.add 这样用于稠密张量算术操作的 Ops,不适用于稀疏张量。
使用 tf.sparse.add 将形状相同的稀疏张量相加。
st_a = tf.sparse.SparseTensor(indices=[[0, 2], [3, 4]],
values=[31, 2],
dense_shape=[4, 10])
st_b = tf.sparse.SparseTensor(indices=[[0, 2], [3, 0]],
values=[56, 38],
dense_shape=[4, 10])
st_sum = tf.sparse.add(st_a, st_b)
print(pprint_sparse_tensor(st_sum))
<SparseTensor shape=[4, 10]
values={
[0, 2]: 87
[3, 0]: 38
[3, 4]: 2}>
使用 tf.sparse.sparse_dense_matmul 将稀疏张量与稠密矩阵相乘。
st_c = tf.sparse.SparseTensor(indices=([0, 1], [1, 0], [1, 1]),
values=[13, 15, 17],
dense_shape=(2,2))
mb = tf.constant([[4], [6]])
product = tf.sparse.sparse_dense_matmul(st_c, mb)
print(product)
tf.Tensor(
[[ 78]
[162]], shape=(2, 1), dtype=int32)
使用 tf.sparse.concat 将稀疏张量拼接在一起,并使用 tf.sparse.slice 将它们拆分。
sparse_pattern_A = tf.sparse.SparseTensor(indices = [[2,4], [3,3], [3,4], [4,3], [4,4], [5,4]],
values = [1,1,1,1,1,1],
dense_shape = [8,5])
sparse_pattern_B = tf.sparse.SparseTensor(indices = [[0,2], [1,1], [1,3], [2,0], [2,4], [2,5], [3,5],
[4,5], [5,0], [5,4], [5,5], [6,1], [6,3], [7,2]],
values = [1,1,1,1,1,1,1,1,1,1,1,1,1,1],
dense_shape = [8,6])
sparse_pattern_C = tf.sparse.SparseTensor(indices = [[3,0], [4,0]],
values = [1,1],
dense_shape = [8,6])
sparse_patterns_list = [sparse_pattern_A, sparse_pattern_B, sparse_pattern_C]
sparse_pattern = tf.sparse.concat(axis=1, sp_inputs=sparse_patterns_list)
print(tf.sparse.to_dense(sparse_pattern))
tf.Tensor(
[[0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 0]
[0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0]
[0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0]
[0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]], shape=(8, 17), dtype=int32)
sparse_slice_A = tf.sparse.slice(sparse_pattern_A, start = [0,0], size = [8,5])
sparse_slice_B = tf.sparse.slice(sparse_pattern_B, start = [0,5], size = [8,6])
sparse_slice_C = tf.sparse.slice(sparse_pattern_C, start = [0,10], size = [8,6])
print(tf.sparse.to_dense(sparse_slice_A))
print(tf.sparse.to_dense(sparse_slice_B))
print(tf.sparse.to_dense(sparse_slice_C))
tf.Tensor(
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 1]
[0 0 0 1 1]
[0 0 0 1 1]
[0 0 0 0 1]
[0 0 0 0 0]
[0 0 0 0 0]], shape=(8, 5), dtype=int32)
tf.Tensor(
[[0]
[0]
[1]
[1]
[1]
[1]
[0]
[0]], shape=(8, 1), dtype=int32)
tf.Tensor([], shape=(8, 0), dtype=int32)
如果您使用的是 TensorFlow 2.4 或更高版本,请使用 tf.sparse.map_values 对稀疏张量中的非零值进行逐元素操作。
st2_plus_5 = tf.sparse.map_values(tf.add, st2, 5)
print(tf.sparse.to_dense(st2_plus_5))
tf.Tensor(
[[ 6 0 0 13]
[ 0 0 0 0]
[ 0 0 8 0]], shape=(3, 4), dtype=int32)
请注意,只有非零值被修改——零值保持为零。
或者,对于早期版本的 TensorFlow,您可以遵循以下设计模式:
st2_plus_5 = tf.sparse.SparseTensor(
st2.indices,
st2.values + 5,
st2.dense_shape)
print(tf.sparse.to_dense(st2_plus_5))
tf.Tensor(
[[ 6 0 0 13]
[ 0 0 0 0]
[ 0 0 8 0]], shape=(3, 4), dtype=int32)
使用 tf.sparse.SparseTensor 与其他 TensorFlow API
稀疏张量与以下 TensorFlow API 无缝配合使用:
- tf.keras
- tf.data
- tf.Train.Example protobuf
- tf.function
- tf.while_loop
- tf.cond
- tf.identity
- tf.cast
- tf.print
- tf.saved_model
- tf.io.serialize_sparse
- tf.io.serialize_many_sparse
- tf.io.deserialize_many_sparse
- tf.math.abs
- tf.math.negative
- tf.math.sign
- tf.math.square
- tf.math.sqrt
- tf.math.erf
- tf.math.tanh
- tf.math.bessel_i0e
- tf.math.bessel_i1e
下面展示了上述部分 API 的示例。
tf.keras
tf.keras API 的一个子集支持稀疏张量,且无需昂贵的类型转换或转换操作。Keras API 允许您将稀疏张量作为输入传递给 Keras 模型。在调用 tf.keras.Input 或 tf.keras.layers.InputLayer 时设置 sparse=True。您可以在 Keras 层之间传递稀疏张量,并且可以让 Keras 模型将它们作为输出返回。如果在模型中使用稀疏张量作为 tf.keras.layers.Dense 层的输入,它们将输出稠密张量。
下面的示例展示了如何在仅使用支持稀疏输入的层时,将稀疏张量作为输入传递给 Keras 模型。
x = tf.keras.Input(shape=(4,), sparse=True)
y = tf.keras.layers.Dense(4)(x)
model = tf.keras.Model(x, y)
sparse_data = tf.sparse.SparseTensor(
indices = [(0,0),(0,1),(0,2),
(4,3),(5,0),(5,1)],
values = [1,1,1,1,1,1],
dense_shape = (6,4)
)
model(sparse_data)
model.predict(sparse_data)
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 87ms/step
array([[ 1.8707037e-02, 7.7025330e-01, 2.2425324e-01, -1.9139588e+00],
[ 0.0000000e+00, 0.0000000e+00, 0.0000000e+00, 0.0000000e+00],
[ 0.0000000e+00, 0.0000000e+00, 0.0000000e+00, 0.0000000e+00],
[ 0.0000000e+00, 0.0000000e+00, 0.0000000e+00, 0.0000000e+00],
[-6.2435389e-02, -4.5783034e-01, 1.2970567e-03, -1.8046319e-01],
[-8.0019468e-01, 9.0452707e-01, 2.1884918e-02, -1.3622781e+00]],
dtype=float32)
tf.data
tf.data API 允许您使用简单、可重用的组件构建复杂的输入流水线。其核心数据结构是 tf.data.Dataset,它表示一个元素序列,其中每个元素由一个或多个组件组成。
使用稀疏张量构建数据集
使用与从 tf.Tensors 或 NumPy 数组构建数据集相同的方法,利用稀疏张量构建数据集,例如 tf.data.Dataset.from_tensor_slices。此操作保留数据的稀疏性。
dataset = tf.data.Dataset.from_tensor_slices(sparse_data)
for element in dataset:
print(pprint_sparse_tensor(element))
<SparseTensor shape=[4]
values={
[0]: 1
[1]: 1
[2]: 1}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
[3]: 1}>
<SparseTensor shape=[4]
values={
[0]: 1
[1]: 1}>
对包含稀疏张量的数据集进行批处理和非批处理
您可以分别使用 Dataset.batch 和 Dataset.unbatch 方法对包含稀疏张量的数据集进行批处理(将连续元素合并为单个元素)和非批处理。
batched_dataset = dataset.batch(2)
for element in batched_dataset:
print (pprint_sparse_tensor(element))
<SparseTensor shape=[2, 4]
values={
[0, 0]: 1
[0, 1]: 1
[0, 2]: 1}>
<SparseTensor shape=[2, 4]
values={
}>
<SparseTensor shape=[2, 4]
values={
[0, 3]: 1
[1, 0]: 1
[1, 1]: 1}>
unbatched_dataset = batched_dataset.unbatch()
for element in unbatched_dataset:
print (pprint_sparse_tensor(element))
<SparseTensor shape=[4]
values={
[0]: 1
[1]: 1
[2]: 1}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
[3]: 1}>
<SparseTensor shape=[4]
values={
[0]: 1
[1]: 1}>
您还可以使用 tf.data.experimental.dense_to_sparse_batch 将形状各异的数据集元素批处理为稀疏张量。
转换包含稀疏张量的数据集
使用 Dataset.map 在数据集中转换和创建稀疏张量。
transform_dataset = dataset.map(lambda x: x*2)
for i in transform_dataset:
print(pprint_sparse_tensor(i))
<SparseTensor shape=[4]
values={
[0]: 2
[1]: 2
[2]: 2}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
}>
<SparseTensor shape=[4]
values={
[3]: 2}>
<SparseTensor shape=[4]
values={
[0]: 2
[1]: 2}>
tf.train.Example
tf.train.Example 是 TensorFlow 数据的标准 protobuf 编码。使用 tf.train.Example 处理稀疏张量时,您可以:
- 使用 tf.io.VarLenFeature 将变长数据读取到 tf.sparse.SparseTensor 中。不过,您应考虑改用 tf.io.RaggedFeature。
- 使用 tf.io.SparseFeature 将任意稀疏数据读取到 tf.sparse.SparseTensor 中,它使用三个独立的特征键来存储 indices、values 和 dense_shape。
tf.function
tf.function 装饰器为 Python 函数预计算 TensorFlow 图,这可以显著提高 TensorFlow 代码的性能。稀疏张量与 tf.function 和具体函数均能透明配合使用。
@tf.function
def f(x,y):
return tf.sparse.sparse_dense_matmul(x,y)
a = tf.sparse.SparseTensor(indices=[[0, 3], [2, 4]],
values=[15, 25],
dense_shape=[3, 10])
b = tf.sparse.to_dense(tf.sparse.transpose(a))
c = f(a,b)
print(c)
tf.Tensor(
[[225 0 0]
[ 0 0 0]
[ 0 0 625]], shape=(3, 3), dtype=int32)
区分缺失值与零值
大多数 tf.sparse.SparseTensors 上的操作将缺失值和显式零值视为相同。这是设计使然——tf.sparse.SparseTensor 的行为应如同稠密张量一样。
然而,在某些情况下,区分零值和缺失值是有用的。特别是,这提供了一种在训练数据中编码缺失/未知数据的方法。例如,考虑这样一个用例:您有一个分数张量(可取 -Inf 到 +Inf 之间的任意浮点值),其中包含一些缺失的分数。您可以使用稀疏张量对此进行编码,其中显式零值代表已知的零分数,而隐式零值实际上代表缺失数据而非零值。
请注意,某些操作(如 tf.sparse.reduce_max)不会将缺失值视为零。例如,运行以下代码块时,预期输出为 0。但由于此例外情况,实际输出为 -3。
print(tf.sparse.reduce_max(tf.sparse.from_dense([-5, 0, -3])))
tf.Tensor(-3, shape=(), dtype=int32)
相比之下,当对稠密张量应用 tf.math.reduce_max 时,输出为预期的 0。
print(tf.math.reduce_max([-5, 0, -3]))
tf.Tensor(0, shape=(), dtype=int32)
延伸阅读和资源
- 参阅张量指南以了解张量。
- 阅读不规则张量指南以了解如何处理不规则张量,这是一种允许处理非均匀数据的张量类型。
- 查看 TensorFlow Model Garden 中使用稀疏张量在 tf.Example 数据解码器中的目标检测模型。