蓝色天空网mbsky.com · 知识 · 实践 · 创造TensorFlow · 本地阅读预览
教程 / AI / 智能开发 / TensorFlow

TensorFlow tf.data API

核对生成器签名、数据变换、缓存与有限步读取。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

识别数据集元素和输入边界

Dataset 由张量或嵌套张量元素组成,可串接变换。内存切片、文本逐行和 Python 生成器各有运行约束。生成器优先用 output_signature 描述形状与类型,让输出结构明确。速度取决于数据读取、计算和运行环境,不能从 API 推出固定倍数。

按元素、窗口或整条序列变换

map 和 filter 分别变换、筛选元素;batch 或 window 将多个元素分组。不同长度的序列可按显式类型与填充值 padded_batch。shuffle 的 buffer_size 限制随机池;当长度未知或无限时不能依赖 len(dataset) 取得完整大小。设定随机种子并观察保留的元素。repeat 后需要限制步数或 take。

保存静态结果并正确读取图像

prefetch 允许生产和消费重叠;并行 map 与 interleave 影响顺序与资源占用。cache 可在内存或指定文件中复用已经读取完整的数据。图像例先构造文件列表、解码并保留标签,训练才打乱、重复;验证遍历一次。

大数据可分文件交错读取,或采用 TFRecord 作为记录容器。snapshot 保存处理后的元素供后续读取。选择缓存位置时保证预处理版本一致。预取、批前变换和并行配置要结合实际内存、向量化机会与重复条件。

三类数据变换

粒度方法实测目标
单元素map 与 filter求平方,然后筛选偶数。
分组batch 与 window查看不同分组边界。
序列整理shuffle 与 repeat分别检查重排和重复后的元素。

复查有限与无限数据集的读取顺序

python · 阅读源码
"""Exercise tf.data traversal, transformations and cache reuse with local fixtures."""
from tempfile import TemporaryDirectory

import json
import platform
from pathlib import Path
import numpy as np
import tensorflow as tf
from tensorflow import keras


def emit(cases):
    print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
        system=platform.system(),devices=[d.name for d in tf.config.list_physical_devices()],cases=cases)))


def observed(cases,name,operation,inputs,expected,actual,measurement=None):
    assert expected==actual,(name,expected,actual)
    row=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
    if measurement is not None:
        row["measurements"]=measurement
    cases.append(row)


def options():
    result=tf.data.Options()
    result.threading.private_threadpool_size=2
    result.deterministic=True
    return result


def values(data):
    return list(data.with_options(options()).as_numpy_iterator())


def input_images(file_pattern,training):
    files=tf.data.Dataset.list_files(file_pattern,shuffle=False)
    if training:
        files=files.shuffle(4,seed=11)
    def parse(path):
        x=tf.io.decode_jpeg(tf.io.read_file(path),channels=3)
        return tf.image.resize(x,[5,5])/255.
    batches=files.map(parse,num_parallel_calls=tf.data.AUTOTUNE).batch(2)
    return (batches.repeat() if training else batches).prefetch(tf.data.AUTOTUNE)


def main():
    cases=[]
    numbers=tf.data.Dataset.from_tensor_slices([1,2,3,4,5])
    observed(cases,"memory_inputs","iterate exactly five in-memory examples",
        [1,2,3,4,5],[1,2,3,4,5],[int(x) for x in values(numbers)])
    def gen():
        yield from (2,5,8)
    generated=tf.data.Dataset.from_generator(gen,output_signature=tf.TensorSpec(shape=(),dtype=tf.int32))
    observed(cases,"generator_output_signature","consume typed scalar generator with unknown static cardinality",
        {"dtype":"int32","shape":[]},[[2,5,8],-2],[[int(x) for x in values(generated)],int(generated.cardinality())])
    square=numbers.map(lambda x:x*x).filter(lambda x:x%2==0)
    observed(cases,"square_and_filter","apply per-element map and filter in sequence",
        [1,2,3,4,5],[4,16],[int(x) for x in values(square)])
    windows=numbers.window(2,shift=1).flat_map(lambda window:window.batch(2))
    observed(cases,"batch_and_window","form finite batches and overlapping windows with explicit step",
        {"shape":2},[[[1,2],[3,4],[5]],[[1,2],[2,3],[3,4],[4,5],[5]]],
        [[row.tolist() for row in values(item)] for item in (numbers.batch(2),windows)])
    shuffled=numbers.shuffle(5,seed=7,reshuffle_each_iteration=False)
    loop=numbers.repeat(2)
    observed(cases,"shuffle_and_repeat","check finite repeat and permutation preservation",
        {"rounds":2},[[1,2,3,4,5],[1,2,3,4,5]*2],
        [sorted(int(x) for x in values(shuffled)),[int(x) for x in values(loop)]])
    parallel=numbers.map(lambda x:2*x,num_parallel_calls=tf.data.AUTOTUNE,deterministic=True).prefetch(tf.data.AUTOTUNE)
    observed(cases,"parallel_map_prefetch","check ordered outputs with parallel map and buffered read",
        {"AUTOTUNE":True},[2,4,6,8,10],[int(x) for x in values(parallel)])
    def tokens():
        yield [2,3],1
        yield [4],0
    token_ds=tf.data.Dataset.from_generator(tokens,output_signature=(
        tf.TensorSpec([None],tf.int32),tf.TensorSpec([],tf.int32)))
    token_batch=next(iter(token_ds.padded_batch(2,padded_shapes=([None],[]),padding_values=(-1,0)).with_options(options())))
    observed(cases,"padded_sequences","pad variable-length token sequences alongside scalar labels",
        {"padding_value":-1},[[[2,3],[4,-1]],[1,0]],[x.numpy().tolist() for x in token_batch])

    with TemporaryDirectory(prefix="mbsky-tf-data-") as location:
        root=Path(location)
        text1=root/"one.txt"
        text2=root/"two.txt"
        text1.write_bytes(b"first\nthird\n")
        text2.write_bytes(b"second\nfourth\n")
        names=[str(text1),str(text2)]
        interleaved=tf.data.Dataset.from_tensor_slices(names).interleave(lambda path:tf.data.TextLineDataset(path),
            block_length=1,cycle_length=2)
        observed(cases,"text_and_interleave","compare two-file sequential and alternating text reads",
            {"files":2},[["first","third","second","fourth"],["first","second","third","fourth"]],
            [[x.decode() for x in values(item)] for item in (tf.data.TextLineDataset(names),interleaved)])
        mem=tf.data.TextLineDataset([str(text1)]).cache().with_options(options())
        disk=tf.data.TextLineDataset([str(text1)]).cache(str(root/"cache")).with_options(options())
        first_values=[list(item.as_numpy_iterator()) for item in (mem,disk)]
        text1.unlink()
        reuse=[list(item.as_numpy_iterator()) for item in (mem,disk)]
        observed(cases,"cache_memory_and_file","fully populate both caches before removing the scratch input",
            {"modes":["memory","file"]},[True,True],[a==b for a,b in zip(first_values,reuse)])

        rec=root/"data.tfr"
        with tf.io.TFRecordWriter(str(rec)) as writer:
            writer.write(b"small local payload")
        observed(cases,"tf_record_local_round_trip","write a TFRecord record and read it using streaming API",
            {"records":1},["small local payload"],[x.decode() for x in values(tf.data.TFRecordDataset([str(rec)]))])
        for idx in range(3):
            tf.io.write_file(str(root/f"{idx}.jpg"),tf.io.encode_jpeg(tf.fill((3,4,3),tf.cast(30+idx*20,tf.uint8))))
        file_pattern=(root/"*.jpg").as_posix()
        valid=[list(batch.shape) for batch in input_images(file_pattern,False).with_options(options())]
        train=[list(batch.shape) for batch in input_images(file_pattern,True).take(3).with_options(options())]
        observed(cases,"image_pipeline_has_finite_eval","read all validation batches and bound repeated training",
            {"files":3},[[[2,5,5,3],[1,5,5,3]],[[2,5,5,3],[1,5,5,3],[2,5,5,3]]],[valid,train])
        snapshot=numbers.map(lambda x:x*x).snapshot(str(root/"snapshot"))
        original=[int(i) for i in values(snapshot)]
        repeated=[int(i) for i in values(snapshot)]
        observed(cases,"snapshot_recovers_values","materialize a finite snapshot and read it again",
            {"count":5},[True,True],[original==repeated,any((root/"snapshot").rglob("*.snapshot"))])
    emit(cases)


if __name__=="__main__":
    main()

预期结果 · 待实际运行核验
  • 验证 JPEG 管道只遍历一次,训练重复模式需用 take 或训练步数限制;缓存结果在原文件移走后仍可读取。
复查有限与无限数据集的读取顺序

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

当前源码 SHA256:a2ddbdb9a4dd1f9d2cd0d04e2566adffa5f5a184e809a43c5e34e9b112f783c3

下载本站示例源码

本地运行

解压后按 README 运行本站程序。

下载TensorFlow tf.data API实例

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

ZIP SHA256:ac5d17bc6a5d90c393a19497594eff8f5d92bbe3ad4231787b7c620d97e54649

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

生成器长度未知时,如何知道能否全量打乱?

展开参考解答

先确定有限基数或明确选择有界缓冲。无限数据只应选有限缓冲。

规范与官方依据