工信部网站域名备案,自助网址搭建源码,10m网站并发量,如何建设企业网站零基础吃透#xff1a;tf.data中RaggedTensor的核心用法#xff08;数据集流水线#xff09;
这份内容会拆解 tf.data.Dataset 与 RaggedTensor 结合的四大核心场景——构建数据集、批处理/取消批处理、非规则张量转Ragged批处理、数据集转换#xff0c;全程用「通俗解释代…零基础吃透tf.data中RaggedTensor的核心用法数据集流水线这份内容会拆解tf.data.Dataset与 RaggedTensor 结合的四大核心场景——构建数据集、批处理/取消批处理、非规则张量转Ragged批处理、数据集转换全程用「通俗解释代码拆解原理结果解读」帮你理解“可变长度数据”在TF输入流水线中的最优处理方式。核心背景先理清tf.data.Dataset是TensorFlow的输入流水线核心工具负责数据加载、预处理、批处理、迭代等全流程RaggedTensor 则是处理“可变长度数据”的原生类型两者结合能完美解决“可变长度数据”在流水线中的处理问题无需补0保留原生结构。先补全示例依赖确保代码可运行importtensorflowastfimportgoogle.protobuf.text_formataspbtext# 先重建之前的feature_tensorstf.Example解析后的RaggedTensor字典defbuild_tf_example(s):returnpbtext.Merge(s,tf.train.Example()).SerializeToString()example_batch[build_tf_example(rfeatures {feature {key: colors value {bytes_list {value: [red, blue]} } } feature {key: lengths value {int64_list {value: [7]} } } }),build_tf_example(rfeatures {feature {key: colors value {bytes_list {value: [orange]} } } feature {key: lengths value {int64_list {value: []} } } }),build_tf_example(rfeatures {feature {key: colors value {bytes_list {value: [black, yellow]} } } feature {key: lengths value {int64_list {value: [1, 3]} } } }),build_tf_example(rfeatures {feature {key: colors value {bytes_list {value: [green]} } } feature {key: lengths value {int64_list {value: [3, 5, 2]} } } })]feature_specification{colors:tf.io.RaggedFeature(tf.string),lengths:tf.io.RaggedFeature(tf.int64),}feature_tensorstf.io.parse_example(example_batch,feature_specification)# 文档中的辅助打印函数defprint_dictionary_dataset(dataset):fori,elementinenumerate(dataset):print(Element {}:.format(i))for(feature_name,feature_value)inelement.items():print({:14} {}.format(feature_name,feature_value))场景1使用RaggedTensor构建数据集核心逻辑tf.data.Dataset.from_tensor_slices是构建数据集的核心方法对RaggedTensor的支持和普通张量完全一致——按“第一个维度样本维度”切分每个元素对应一个样本的RaggedTensor保留原始可变长度。代码解析# 从RaggedTensor字典构建数据集feature_tensors是{colors: RaggedTensor, lengths: RaggedTensor}datasettf.data.Dataset.from_tensor_slices(feature_tensors)# 打印数据集元素print( 构建的RaggedTensor数据集 )print_dictionary_dataset(dataset)运行结果解读Element 0: colors [bred bblue] lengths [7] Element 1: colors [borange] lengths [] Element 2: colors [bblack byellow] lengths [1 3] Element 3: colors [bgreen] lengths [3 5 2]每个Element对应一个样本colors/lengths保留该样本的原始长度比如样本1的lengths为空列表样本3的lengths有3个元素对比普通张量如果是补0的密集张量样本1的lengths会是[0,0,0]补到最长长度而RaggedTensor无冗余。关键原理from_tensor_slices对RaggedTensor的切分规则只切分最外层的均匀维度样本维度内层的不规则维度保持不变比如feature_tensors[lengths]是形状[4, None]的RaggedTensor切分后每个元素是形状[None]的RaggedTensor单个样本的长度列表。场景2批处理/取消批处理RaggedTensor数据集2.1 批处理Dataset.batch核心逻辑Dataset.batch(n)把n个连续样本合并成一个批次批次内的RaggedTensor会自动合并为更高维的RaggedTensor批次维度是均匀的内部维度仍不规则。代码解析# 按2个样本为一批进行批处理batched_datasetdataset.batch(2)print(\n 批处理后的RaggedTensor数据集batch2 )print_dictionary_dataset(batched_dataset)运行结果解读Element 0: colors tf.RaggedTensor [[bred, bblue], [borange]] lengths tf.RaggedTensor [[7], []] Element 1: colors tf.RaggedTensor [[bblack, byellow], [bgreen]] lengths tf.RaggedTensor [[1, 3], [3, 5, 2]]每个Element是一个批次2个样本colors/lengths变成二维RaggedTensor第一维是批次内的样本索引第二维是样本内的元素对比密集张量批处理无需补0到“批次内最长长度”比如批次0的colors中第一个样本2个元素、第二个样本1个元素直接保留原始长度。2.2 取消批处理Dataset.unbatch核心逻辑Dataset.unbatch()把批处理后的数据集拆回“单个样本”的形式完全恢复批处理前的结构。代码解析# 取消批处理unbatched_datasetbatched_dataset.unbatch()print(\n 取消批处理后的数据集 )print_dictionary_dataset(unbatched_dataset)运行结果和场景1的原始数据集完全一致4个单个样本保留原始长度。关键对比Ragged批处理 vs 密集张量批处理方式特点冗余性RaggedTensor.batch合并为高维RaggedTensor保留原始长度无冗余密集张量.batch补0到批次内最长长度生成固定形状张量有冗余场景3非Ragged张量可变长度转Ragged批处理核心场景如果数据集的元素是长度不同的密集张量不是RaggedTensor直接用batch会报错长度不匹配此时用dense_to_ragged_batch把每个批次转成RaggedTensor避免补0。代码解析# 步骤1构建“长度不同的密集张量”数据集# 原始数据[1,5,3,2,8] → 每个元素用tf.range生成长度不同的密集张量non_ragged_datasettf.data.Dataset.from_tensor_slices([1,5,3,2,8])non_ragged_datasetnon_ragged_dataset.map(tf.range)# 映射后[0], [0,1,2,3,4], [0,1,2], [0,1], [0-7]# 步骤2用dense_to_ragged_batch批处理每2个样本为一批转成RaggedTensorbatched_non_ragged_datasetnon_ragged_dataset.apply(tf.data.experimental.dense_to_ragged_batch(2))# 打印结果print(\n 非Ragged张量转Ragged批处理 )forelementinbatched_non_ragged_dataset:print(element)运行结果解读tf.RaggedTensor [[0], [0, 1, 2, 3, 4]] tf.RaggedTensor [[0, 1, 2], [0, 1]] tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6, 7]]第一批2个样本[0]和[0,1,2,3,4]→ 合并为二维RaggedTensor第二批2个样本[0,1,2]和[0,1]→ 合并为二维RaggedTensor第三批只剩1个样本[0-7]→ 一维RaggedTensor核心价值不用补0直接按原始长度合并为RaggedTensor解决“长度不同的密集张量无法直接batch”的问题。关键原理tf.data.experimental.dense_to_ragged_batch(n)每次取n个长度不同的密集张量自动将其转换为一个n行的RaggedTensor每行对应一个样本的原始长度替代方案如果不用这个方法需要先把每个元素转成RaggedTensor再batch步骤更繁琐。场景4转换RaggedTensor数据集Dataset.map核心逻辑Dataset.map可以对数据集中的每个元素RaggedTensor进行任意转换比如计算均值、生成新的RaggedTensorTF原生支持RaggedTensor的运算。代码解析# 定义转换函数处理每个样本的features字典deftransform_lengths(features):return{# 计算lengths的均值空列表的均值为0mean_length:tf.math.reduce_mean(features[lengths]),# 对lengths中的每个值生成0到该值-1的序列返回RaggedTensorlength_ranges:tf.ragged.range(features[lengths])}# 应用转换transformed_datasetdataset.map(transform_lengths)# 打印结果print(\n 转换后的RaggedTensor数据集 )print_dictionary_dataset(transformed_dataset)运行结果解读Element 0: mean_length 7 length_ranges tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6]] Element 1: mean_length 0 length_ranges tf.RaggedTensor [] Element 2: mean_length 2 length_ranges tf.RaggedTensor [[0], [0, 1, 2]] Element 3: mean_length 3 length_ranges tf.RaggedTensor [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]]关键转换逻辑解读tf.math.reduce_mean(features[lengths])样本0的lengths[7] → 均值7样本1的lengths[] → 均值0TF对空RaggedTensor的reduce_mean默认返回0样本2的lengths[1,3] → 均值(13)/22样本3的lengths[3,5,2] → 均值(352)/33。tf.ragged.range(features[lengths])对lengths中的每个数值L生成[0,1,...,L-1]的序列样本0的lengths[7] → 生成[0-6]→ RaggedTensor[[0,1,2,3,4,5,6]]样本2的lengths[1,3] → 生成[0]和[0,1,2]→ RaggedTensor[[0], [0,1,2]]。关键优势Dataset.map处理RaggedTensor时无需转换为密集张量直接运算所有TF内置运算reduce_mean/range/concat等都原生支持RaggedTensor转换后的结果仍可保留RaggedTensor结构无缝接入后续流水线。核心总结tf.dataRaggedTensor关键要点操作核心价值关键API构建数据集直接切分RaggedTensor保留样本原始长度tf.data.Dataset.from_tensor_slices批处理合并为高维RaggedTensor无冗余补0Dataset.batch(n)取消批处理恢复单个样本的RaggedTensor结构Dataset.unbatch()非Ragged批处理解决长度不同的密集张量无法batch的问题tf.data.experimental.dense_to_ragged_batch数据集转换原生支持RaggedTensor运算无需转密集张量Dataset.map(转换函数)避坑关键Dataset.from_generator暂不支持RaggedTensor文档提示后续会支持如需生成器构建需先将RaggedTensor转成密集张量Mask批处理后的RaggedTensor可直接传入Keras模型需Input层设置raggedTrue所有RaggedTensor的运算都遵循“只处理有效元素”的规则无冗余计算。这套组合是TF处理“可变长度数据”文本、序列特征等的最优流水线方案既保证数据结构的原生性又兼顾流水线的高效性。