蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。transform-datasets-offline.py
transform-datasets-offline.py124 行
"""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()

本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

入口文件:projects/tensorflow-tf-data-lab/transform-datasets-offline.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 transform-datasets-offline.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a383.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习