进阶 tensorflow.org 2026-10-22 02:47:47 · 30 阅读
第14章 不规则张量(Ragged Tensor)
第14章 不规则张量
TensorFlow
TensorFlow 核心
指南
不规则张量
利用集合保持组织有序
根据你的偏好保存和分类内容。
在 TensorFlow.org 上查看
在 Google Colab 中运行
在 GitHub 上查看源码
下载 Notebook
API 文档:tf.RaggedTensor tf.ragged
设置
!pip install --pre -U tensorflow
import math
import tensorflow as tf
2024-08-27 01:20:40.536630: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2024-08-27 01:20:40.557820: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2024-08-27 01:20:40.563984: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
概述
数据有各种各样的形状,你的张量也应该如此。不规则张量(Ragged tensors)是 TensorFlow 中嵌套变长列表的等价物。它们使得存储和处理具有非均匀形状的数据变得容易,包括:
* 变长特征,例如电影中的演员列表。
* 变长序列输入的批次,例如句子或视频片段。
* 分层输入,例如划分为章节、段落、句子和单词的文本文档。
* 结构化输入中的独立字段,例如 protocol buffers。
你可以用不规则张量做什么
超过一百个 TensorFlow 操作支持不规则张量,包括数学操作(如 tf.add 和 tf.reduce_mean)、数组操作(如 tf.concat 和 tf.tile)、字符串操作(如 tf.strings.substr)、控制流操作(如 tf.while_loop 和 tf.map_fn)以及许多其他操作:
```python
digits = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
words = tf.ragged.constant([["So", "long"], ["thanks", "for", "all", "the", "fish"]])
print(tf.add(digits, 3))
print(tf.reduce_mean(digits, axis=1))
print(tf.concat([digits, [[5, 3]]], axis=0))
print(tf.tile(digits, [1, 2]))
print(tf.strings.substr(words, 0, 2))
print(tf.map_fn(tf.math.square, digits))
```
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
...(日志输出省略)...
tf.Tensor([2.25 nan 5.33333333 6. nan], shape=(5,), dtype=float64)
还有许多专用于不规则张量的方法和操作,包括工厂方法、转换方法和值映射操作。
支持操作列表请参见 tf.ragged 包文档。
许多 TensorFlow API 支持不规则张量,包括 Keras、Datasets、tf.function、SavedModels 和 tf.Example。更多详细信息,请查阅下文关于 TensorFlow API 的部分。
与普通张量一样,你可以使用 Python 风格的索引来访问不规则张量的特定切片。更多信息,请参考下文的“索引”部分。
```python
print(digits[0]) # 第一行
```
tf.Tensor([3 1 4 1], shape=(4,), dtype=int32)
```python
print(digits[:, :2]) # 每行的前两个值
```
```python
print(digits[:, -2:]) # 每行的最后两个值
```
就像普通张量一样,你可以使用 Python 算术和比较运算符来执行逐元素操作。更多信息,请查阅下文的“重载运算符”部分。
```python
print(digits + 3)
```
```python
print(digits + tf.ragged.constant([[1, 2, 3, 4], [], [5, 6, 7], [8], []]))
```
如果需要执行逐元素转换 RaggedTensor 的值,可以使用 tf.ragged.map_flat_values,它接受一个函数和一个或多个参数,并将该函数应用于转换 RaggedTensor 的值。
```python
times_two_plus_one = lambda x: x * 2 + 1
print(tf.ragged.map_flat_values(times_two_plus_one, digits))
```
不规则张量可以转换为嵌套 Python 列表和 NumPy 数组:
```python
digits.to_list()
```
[[3, 1, 4, 1], [], [5, 9, 2], [6], []]
```python
digits.numpy()
```
array([array([3, 1, 4, 1], dtype=int32), array([], dtype=int32),
array([5, 9, 2], dtype=int32), array([6], dtype=int32),
array([], dtype=int32)], dtype=object)
构建不规则张量
构建不规则张量最简单的方法是使用 tf.ragged.constant,它根据给定的嵌套 Python 列表或 NumPy 数组构建对应的 RaggedTensor:
```python
sentences = tf.ragged.constant([
["Let's", "build", "some", "ragged", "tensors", "!"],
["We", "can", "use", "tf.ragged.constant", "."]])
print(sentences)
```
```python
paragraphs = tf.ragged.constant([
[['I', 'have', 'a', 'cat'], ['His', 'name', 'is', 'Mat']],
[['Do', 'you', 'want', 'to', 'come', 'visit'], ["I'm", 'free', 'tomorrow']],
])
print(paragraphs)
```
也可以通过将扁平值张量(flat values tensors)与行划分张量(row-partitioning tensors)配对来构建不规则张量,这些划分张量指示这些值应如何划分为行。使用工厂类方法如 tf.RaggedTensor.from_value_rowids、tf.RaggedTensor.from_row_lengths 和 tf.RaggedTensor.from_row_splits。
tf.RaggedTensor.from_value_rowids
如果你知道每个值属于哪一行,可以使用 value_rowids 行划分张量来构建 RaggedTensor:
```python
print(tf.RaggedTensor.from_value_rowids(
values=[3, 1, 4, 1, 5, 9, 2],
value_rowids=[0, 0, 0, 0, 2, 2, 3]))
```
tf.RaggedTensor.from_row_lengths
如果你知道每行的长度,可以使用 row_lengths 行划分张量:
```python
print(tf.RaggedTensor.from_row_lengths(
values=[3, 1, 4, 1, 5, 9, 2],
row_lengths=[4, 0, 2, 1]))
```
tf.RaggedTensor.from_row_splits
如果你知道每行的起始和结束索引,可以使用 row_splits 行划分张量:
```python
print(tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2],
row_splits=[0, 4, 4, 6, 7]))
```
tf.RaggedTensor 类文档中列出了所有工厂方法。
在不规则张量中存储什么
与普通 Tensor 一样,RaggedTensor 中的值必须具有相同的
类型;且值必须具有相同的嵌套深度(即张量的 rank):
```python
print(tf.ragged.constant([["Hi"], ["How", "are", "you"]])) # ok: type=string, rank=2
```
```python
print(tf.ragged.constant([[[1, 2], [3]], [[4, 5]]])) # ok: type=int32, rank=3
```
```python
try:
tf.ragged.constant([["one", "two"], [3, 4]]) # bad: multiple types
except ValueError as exception:
print(exception)
```
Can't convert Python sequence with mixed types to Tensor.
```python
try:
tf.ragged.constant(["A", ["B", "C"]]) # bad: multiple nesting depths
except ValueError as exception:
print(exception)
```
all scalar values must have the same nesting depth
示例用例
以下示例演示了如何使用 RaggedTensors 构建和组合一批变长查询的单字(unigram)和双字(bigram)嵌入,并使用特殊标记来表示每个句子的开头和结尾。有关此示例中使用的操作的更多详细信息,请查看 tf.ragged 包文档。
```python
queries = tf.ragged.constant([['Who', 'is', 'Dan', 'Smith'],
['Pause'],
['Will', 'it', 'rain', 'later', 'today']])
# 创建嵌入表。
num_buckets = 1024
embedding_size = 4
embedding_table = tf.Variable(
tf.random.truncated_normal([num_buckets, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
# 查找每个单词的嵌入。
word_buckets = tf.strings.to_hash_bucket_fast(queries, num_buckets)
word_embeddings = tf.nn.embedding_lookup(embedding_table, word_buckets) # ①
# 在每个句子的开头和末尾添加标记。
marker = tf.fill([queries.nrows(), 1], '#')
padded = tf.concat([marker, queries, marker], axis=1) # ②
# 构建单词双字词并查找嵌入。
bigrams = tf.strings.join([padded[:, :-1], padded[:, 1:]], separator='+') # ③
bigram_buckets = tf.strings.to_hash_bucket_fast(bigrams, num_buckets)
bigram_embeddings = tf.nn.embedding_lookup(embedding_table, bigram_buckets) # ④
# 找出每个句子的平均嵌入
all_embeddings = tf.concat([word_embeddings, bigram_embeddings], axis=1) # ⑤
avg_embedding = tf.reduce_mean(all_embeddings, axis=1) # ⑥
print(avg_embedding)
```
tf.Tensor(
[[-0.07189021 0.23444025 -0.04020268 -0.27113184]
[ 0.10560822 0.00976487 -0.17885399 0.5371701 ]
[-0.23479678 -0.15996003 0.07078557 0.24388357]], shape=(3, 4), dtype=float32)
不规则维度与均匀维度
不规则维度(ragged dimension)是指切片可能具有不同长度的维度。例如,rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []] 的内层(列)维度是不规则的,因为列切片(rt[0, :], ..., rt[4, :])的长度不同。所有切片长度相同的维度称为均匀维度(uniform dimensions)。
不规则张量的最外层维度总是均匀的,因为它由单个切片组成(因此切片长度没有差异的可能性)。其余维度可能是不规则的,也可能是均匀的。例如,你可以使用形状为 [num_sentences, (num_words), embedding_size] 的不规则张量来存储句子批次中每个单词的词嵌入,其中 (num_words) 周围的括号表示该维度是不规则的。
不规则张量可以具有多个不规则维度。例如,你可以使用形状为 [num_documents, (num_paragraphs), (num_sentences), (num_words)] 的张量来存储一批结构化文本文档(再次使用括号表示不规则维度)。
与 tf.Tensor 一样,不规则张量的秩(rank)是其总维度数(包括不规则维度和均匀维度)。潜在的不规则张量是可能是 tf.Tensor 或 tf.RaggedTensor 的值。
在描述 RaggedTensor 的形状时,通常用括号包围不规则维度。例如,正如上文所见,存储句子批次中每个单词嵌入的 3D RaggedTensor 的形状可以写为 [num_sentences, (num_words), embedding_size]。
RaggedTensor.shape 属性返回一个 tf.TensorShape,其中不规则维度的大小为 None:
```python
tf.ragged.constant([["Hi"], ["How", "are", "you"]]).shape
```
TensorShape([2, None])
可以使用方法 tf.RaggedTensor.bounding_shape 来查找给定 RaggedTensor 的紧凑边界形状:
```python
print(tf.ragged.constant([["Hi"], ["How", "are", "you"]]).bounding_shape())
```
tf.Tensor([2 3], shape=(2,), dtype=int64)
不规则 vs 稀疏
不应将不规则张量视为一种稀疏张量。特别是,稀疏张量是对 tf.Tensor 的高效编码,以紧凑格式建模相同的数据;但不规则张量是 tf.Tensor 的扩展,建模了一类扩展的数据。这种区别在定义操作时至关重要:
* 对稀疏或稠密张量应用操作,结果总是相同的。
* 对不规则或稀疏张量应用操作,结果可能不同。
作为一个说明性示例,考虑 concat、stack 和 tile 等数组操作在不规则张量和稀疏张量中的定义。拼接不规则张量会将每一行连接起来,形成一个具有组合长度的单一行:
```python
ragged_x = tf.ragged.constant([["John"], ["a", "big", "dog"], ["my", "cat"]])
ragged_y = tf.ragged.constant([["fell", "asleep"], ["barked"], ["is", "fuzzy"]])
print(tf.concat([ragged_x, ragged_y], axis=1))
```
然而,拼接稀疏张量等同于拼接对应的稠密张量,如下例所示(其中 Ø 表示缺失值):
```python
sparse_x = ragged_x.to_sparse()
sparse_y = ragged_y.to_sparse()
sparse_result = tf.sparse.concat(sp_inputs=[sparse_x, sparse_y], axis=1)
print(tf.sparse.to_dense(sparse_result, ''))
```
tf.Tensor(
[[b'John' b'' b'' b'fell' b'asleep']
[b'a' b'big' b'dog' b'barked' b'']
[b'my' b'cat' b'' b'is' b'fuzzy']], shape=(3, 5), dtype=string)
另一个说明这种区别重要性的示例,考虑如 tf.reduce_mean 等操作中“每行平均值”的定义。
对于不规则张量,一行的平均值是该行值的总和除以该行的宽度。
但对于稀疏张量,一行的平均值是该行值的总和除以稀疏张量的整体宽度(该宽度大于或等于最长行的宽度)。
TensorFlow API
Keras
tf.keras 是 TensorFlow 用于构建和训练深度学习模型的高级 API。它不支持不规则张量。但它支持掩码张量(masked tensors)。因此在 Keras 模型中使用不规则张量的最简单方法是使用 .to_tensor() 将不规则张量转换为稠密张量,然后使用 Keras 的内置掩码功能:
```python
# 任务:预测每个句子是否是问句。
sentences = tf.constant(
['What makes you think she is a witch?',
'She turned me into a newt.',
'A newt?',
'Well, I got better.'])
is_question = tf.constant([True, False, True, False])
# 预处理输入字符串。
hash_buckets = 1000
words = tf.strings.split(sentences, ' ')
hashed_words = tf.strings.to_hash_bucket_fast(words, hash_buckets)
hashed_words.to_list()
```
[[940, 203, 668, 387, 790, 320, 939, 185],
[315, 515, 791, 181, 939, 787],
[564, 205],
[820, 180, 993, 739]]
```python
hashed_words.to_tensor()
```
```python
tf.keras.Input?
# 构建 Keras 模型。
keras_model = tf.keras.Sequential([
tf.keras.layers.Embedding(hash_buckets, 16, mask_zero=True),
tf.keras.layers.LSTM(32, return_sequences=True, use_bias=False),
tf.keras.layers.GlobalAveragePooling1D(),
tf.keras.layers.Dense(32),
tf.keras.layers.Activation(tf.nn.relu),
tf.keras.layers.Dense(1)
])
keras_model.compile(loss='binary_crossentropy', optimizer='rmsprop')
keras_model.fit(hashed_words.to_tensor(), is_question, epochs=5)
```
Epoch 1/5
...(日志输出省略)...
Epoch 5/5
...(日志输出省略)...
```python
print(keras_model.predict(hashed_words.to_tensor()))
```
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 407ms/step
[[-0.00517703]
[-0.00227403]
[-0.00706224]
[-0.00354813]]
tf.Example
tf.Example 是 TensorFlow 数据的标准 protobuf 编码。使用 tf.Examples 编码的数据通常包含变长特征。例如,以下代码定义了一个包含四个特征长度不同的 tf.Example 消息的批次:
```python
import google.protobuf.text_format as pbtext
def build_tf_example(s):
return pbtext.Merge(s, tf.train.Example()).SerializeToString()
example_batch = [
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["red", "blue"]} } }
feature {key: "lengths" value {int64_list {value: [7]} } } }'''),
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["orange"]} } }
feature {key: "lengths" value {int64_list {value: []} } } }'''),
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["black", "yellow"]} } }
feature {key: "lengths" value {int64_list {value: [1, 3]} } } }'''),
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["green"]} } }
feature {key: "lengths" value {int64_list {value: [3, 5, 2]} } } }''')]
```
你可以使用 tf.io.parse_example 解析这种编码数据,它接受一个序列化字符串张量和一个特征规范字典,并返回一个将特征名称映射到张量的字典。要将变长特征读取为不规则张量,只需在特征规范字典中使用 tf.io.RaggedFeature:
```python
feature_specification = {
'colors': tf.io.RaggedFeature(tf.string),
'lengths': tf.io.RaggedFeature(tf.int64),
}
feature_tensors = tf.io.parse_example(example_batch, feature_specification)
for name, value in feature_tensors.items():
print("{}={}".format(name, value))
```
colors=
lengths=
tf.io.RaggedFeature 还可以用于读取具有多个不规则维度的特征。详情请参阅 API 文档。
Datasets
tf.data 是一个 API,允许你从简单、可重用的组件构建复杂的输入管道。其核心数据结构是 tf.data.Dataset,它表示一个元素序列,其中每个元素由一个或多个组件组成。
```python
# 用于打印以下示例中数据集的辅助函数。
def print_dictionary_dataset(dataset):
for i, element in enumerate(dataset):
print("Element {}:".format(i))
for (feature_name, feature_value) in element.items():
print('{:>14} = {}'.format(feature_name, feature_value))
```
使用不规则张量构建 Datasets
可以使用从 tf.Tensors 或 NumPy 数组构建它们使用的相同方法(如 Dataset.from_tensor_slices)从不规则张量构建 Datasets:
```python
dataset = tf.data.Dataset.from_tensor_slices(feature_tensors)
print_dictionary_dataset(dataset)
```
Element 0:
colors = [b'red' b'blue']
lengths = [7]
Element 1:
colors = [b'orange']
lengths = []
Element 2:
colors = [b'black' b'yellow']
lengths = [1 3]
Element 3:
colors = [b'green']
lengths = [3 5 2]
对具有不规则张量的 Datasets 进行批量化和非批量化
具有不规则张量的 Datasets 可以使用 Dataset.batch 方法进行批量化(将 n 个连续元素组合成单个元素):
```python
batched_dataset = dataset.batch(2)
print_dictionary_dataset(batched_dataset)
```
Element 0:
colors =
lengths =
Element 1:
colors =
lengths =
相反,可以使用 Dataset.unbatch 将已批量化的数据集转换回扁平数据集。
```python
unbatched_dataset = batched_dataset.unbatch()
print_dictionary_dataset(unbatched_dataset)
```
Element 0:
colors = [b'red' b'blue']
lengths = [7]
Element 1:
colors = [b'orange']
lengths = []
Element 2:
colors = [b'black' b'yellow']
lengths = [1 3]
Element 3:
colors = [b'green']
lengths = [3 5 2]
对包含变长非不规则张量的 Datasets 进行批量化
如果你有一个包含非不规则张量的 Dataset,且张量长度在元素之间变化,则可以通过应用 dense_to_ragged_batch 转换将这些非不规则张量批量化为不规则张量:
```python
non_ragged_dataset = tf.data.Dataset.from_tensor_slices([1, 5, 3, 2, 8])
non_ragged_dataset = non_ragged_dataset.map(tf.range)
batched_non_ragged_dataset = non_ragged_dataset.apply(
tf.data.experimental.dense_to_ragged_batch(2))
for element in batched_non_ragged_dataset:
print(element)
```
WARNING:tensorflow:From /tmpfs/tmp/ipykernel_10064/1427668168.py:4: dense_to_ragged_batch (from tensorflow.python.data.experimental.ops.batching) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.Dataset.ragged_batch` instead.
转换具有不规则张量的 Datasets
你也可以使用 Dataset.map 在 Datasets 中创建或转换不规则张量:
```python
def transform_lengths(features):
return {
'mean_length': tf.math.reduce_mean(features['lengths']),
'length_ranges': tf.ragged.range(features['lengths'])}
transformed_dataset = dataset.map(transform_lengths)
print_dictionary_dataset(transformed_dataset)
```
Element 0:
mean_length = 7
length_ranges =
Element 1:
mean_length = 0
length_ranges =
Element 2:
mean_length = 2
length_ranges =
Element 3:
mean_length = 3
length_ranges =
tf.function
tf.function 是一个装饰器,用于预计算 Python 函数的 TensorFlow 图,这可以显著提高你的 TensorFlow 代码的性能。不规则张量可以与使用 @tf.function 装饰的函数透明配合使用。例如,以下函数可以同时处理不规则和非不规则张量:
```python
@tf.function
def make_palindrome(x, axis):
return tf.concat([x, tf.reverse(x, [axis])], axis)
make_palindrome(tf.constant([[1, 2], [3, 4], [5, 6]]), axis=1)
```
```python
make_palindrome(tf.ragged.constant([[1, 2], [3], [4, 5, 6]]), axis=1)
```
2024-08-27 01:20:51.662289: W tensorflow/core/grappler/optimizers/loop_optimizer.cc:933] Skipping loop optimization for Merge node with control input: RaggedConcat/assert_equal_1/Assert/AssertGuard/branch_executed/_9
如果你希望显式为 tf.function 指定 input_signature,可以使用 tf.RaggedTensorSpec 来实现:
```python
@tf.function(
input_signature=[tf.RaggedTensorSpec(shape=[None, None], dtype=tf.int32)])
def max_and_min(rt):
return (tf.math.reduce_max(rt, axis=-1), tf.math.reduce_min(rt, axis=-1))
max_and_min(tf.ragged.constant([[1, 2], [3], [4, 5, 6]]))
```
(,
)
具体函数
具体函数(Concrete functions)封装了由 tf.function 构建的单个追踪图。不规则张量可以与具体函数透明配合使用。
```python
@tf.function
def increment(x):
return x + 1
rt = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
cf = increment.get_concrete_function(rt)
print(cf(rt))
```
SavedModels
SavedModel 是序列化的 TensorFlow 程序,包含权重和计算。它可以从 Keras 模型或自定义模型构建。无论哪种情况,不规则张量都可以与 SavedModel 定义的函数和方法透明配合使用。
示例:保存 Keras 模型
```python
import tempfile
keras_module_path = tempfile.mkdtemp()
keras_model.save(keras_module_path+"/my_model.keras")
imported_model = tf.keras.models.load_model(keras_module_path+"/my_model.keras")
imported_model(hashed_words.to_tensor())
```
示例:保存自定义模型
```python
class CustomModule(tf.Module):
def __init__(self, variable_value):
super(CustomModule, self).__init__()
self.v = tf.Variable(variable_value)
@tf.function
def grow(self, x):
return x * self.v
module = CustomModule(100.0)
# 在保存自定义模型之前,必须确保为你需要的每个输入签名构建具体函数。
module.grow.get_concrete_function(tf.RaggedTensorSpec(shape=[None, None],
dtype=tf.float32))
custom_module_path = tempfile.mkdtemp()
tf.saved_model.save(module, custom_module_path)
imported_model = tf.saved_model.load(custom_module_path)
imported_model.grow(tf.ragged.constant([[1.0, 4.0, 3.0], [2.0]]))
```
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpkmr703wo/assets
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpkmr703wo/assets
重载运算符
RaggedTensor 类重载了标准的 Python 算术和比较运算符,使得执行基本逐元素数学运算变得容易:
```python
x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
y = tf.ragged.constant([[1, 1], [2], [3, 3, 3]])
print(x + y)
```
由于重载运算符执行逐元素计算,所有二元运算的输入必须具有相同的形状,或者可以广播到相同的形状。在最简单的广播情况下,单个标量与不规则张量中的每个值进行逐元素组合:
```python
x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
print(x + 3)
```
有关更高级情况的讨论,请查看关于“广播”的部分。
不规则张量重载了与普通 Tensor 相同的运算符集合:一元运算符 -, ~, 和 abs();以及二元运算符 +, -, *, /, //, %, , &, |, ^, ==, <, <=, >, 和 >=。
索引
不规则张量支持 Python 风格的索引,包括多维索引和切片。以下示例演示了 2D 和 3D 不规则张量的索引。
索引示例:2D 不规则张量
```python
queries = tf.ragged.constant(
[['Who', 'is', 'George', 'Washington'],
['What', 'is', 'the', 'weather