蓝色天空.知识 · 实践 · 创造
我的收藏
TensorFlow 教程目录 24章
TensorFlow / LEARN BY DOING

TensorFlow 数据处理与管道

用本地 JPEG 和 PNG 建立可复查的训练、验证与批处理管道。

学完这一章,你能够

  • 用本地 JPEG 和 PNG 建立可复查的训练、验证与批处理管道。

让数据进入管道

tf.data 将输入表示为按需读取的元素序列。列表适合小数据,TextLineDataset 逐行读取,TFRecordDataset 读取二进制记录;解析结构与存储格式分别处理。并行和预取可能降低等待,流式读取减少全部载入的需求。实际收益要测吞吐、内存和等待。

标准化以训练集均值和标准差缩放;最小最大归一化以训练范围缩放。常量列避免除以零。图像值可按 255 归一化,类别可用独热表示,序列明确填充位置和截断规则。

分开训练增强与验证读取

用已知类别目录生成局部 JPEG 和 PNG。先读取后按扩展名用对应解码器,再缩放尺寸并构造整数类别。map 保持图像与标签配对。训练路径可做水平翻转、亮度扰动与幅值裁剪,验证保持确定性。最后按批次送给模型并预取。

JPEG 与 PNG 经统一形状和归一化,再分别走训练增强或验证读取。
本站根据实测管道绘制。训练和验证使用相同的输入形状。

在相同输入上检查缓存与采样

并行 map 可同时处理多个样本;预取缓冲采用批次在前时保存批次;缓存只适合确定部分和可承受的体积。分片按索引交错选取记录。大文件优先流式读取,缓存文件和顺序版本需与预处理一致。

定位瓶颈时分别看主机、存储与设备等待,再调并行数、interleave、预取或批量。类别不平衡可用 Dataset.sample_from_datasets,并处理耗尽后的比例变化。旧 experimental 统计接口应迁移至 Profiler。确定性预处理和训练随机增强分开安排。旧示例的加速倍数需要可比测试支持。

三种性能设置的验证范围

设置做法实际观察
并行 map设置 num_parallel_calls;保留需要的输出顺序。实测并行处理与串行值等价。
预取缓冲在 batch 之后使用 prefetch。实测输出批和值一致。
缓存静态步骤在需要重复使用且可容纳时放置 cache。实测第二次读取复用缓存。

以本地合成文件检查训练和验证管道

含完整源码 · 149 行
展开查看收起
python
"""Build a fully local image input pipeline with testable transformations."""
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 opts():
    value=tf.data.Options()
    value.threading.private_threadpool_size=2
    value.deterministic=True
    return value


def numbers(ds):
    return [value.item() if isinstance(value,np.generic) else value
            for value in ds.with_options(opts()).as_numpy_iterator()]


def rgb_image(path):
    blob=tf.io.read_file(path)
    png=tf.strings.regex_full_match(path,".*[.]png")
    x=tf.cond(png,lambda:tf.io.decode_png(blob,channels=3),lambda:tf.io.decode_jpeg(blob,channels=3))
    return tf.image.resize(x,[4,4])/255.


def make_inputs(root):
    paths=[]
    for label in ("light","line"):
        directory=root/label
        directory.mkdir()
        data=tf.cast(tf.reshape(tf.range(36),(3,4,3))*6,tf.uint8)
        if label=="light":
            data=255-data
        for suffix in ("jpg","png"):
            path=directory/f"tile.{suffix}"
            writer=tf.io.encode_png if suffix=="png" else tf.io.encode_jpeg
            tf.io.write_file(str(path),writer(data))
            paths.append(path.as_posix())
    return sorted(paths)


def image_pipeline(paths,training):
    stream=tf.data.Dataset.from_tensor_slices(paths)
    def read(path):
        label=tf.strings.split(path,"/")[-2]
        return rgb_image(path),tf.cast(label=="line",tf.int32)
    stream=stream.map(read,num_parallel_calls=tf.data.AUTOTUNE,deterministic=True).cache()
    if training:
        def augment(index,item):
            x,y=item
            seed=tf.stack([tf.constant(13,tf.int32),tf.cast(index,tf.int32)])
            x=tf.image.stateless_random_flip_left_right(x,seed)
            x=tf.image.stateless_random_brightness(x,.2,seed+1)
            return tf.clip_by_value(x,0.,1.),y
        stream=stream.enumerate().map(augment,num_parallel_calls=tf.data.AUTOTUNE,deterministic=True)
    return stream.batch(3).prefetch(tf.data.AUTOTUNE).with_options(opts())


def main():
    cases=[]
    with TemporaryDirectory(prefix="mbsky-pipeline-inputs-") as local:
        root=Path(local)
        text=root/"first.txt"
        text.write_bytes(b"one\ntwo\n")
        frec=root/"raw.tfrecord"
        with tf.io.TFRecordWriter(str(frec)) as output:
            output.write(b"record-A")
            output.write(b"record-B")
        numeric=numbers(tf.data.Dataset.from_tensor_slices([1,2,3]))
        lines=[x.decode() for x in numbers(tf.data.TextLineDataset([str(text)]))]
        records=[x.decode() for x in numbers(tf.data.TFRecordDataset([str(frec)]))]
        observed(cases,"three_input_sources","read memory, line-oriented files and TFRecord bytes",
                 {"input_counts":[3,2,2]},[[1,2,3],["one","two"],["record-A","record-B"]],[numeric,lines,records])
        v=tf.constant([2.,4.,6.])
        standardized=(v-tf.reduce_mean(v))/tf.math.reduce_std(v)
        normal=tf.math.divide_no_nan(v-tf.reduce_min(v),tf.reduce_max(v)-tf.reduce_min(v))
        observed(cases,"standardize_and_minmax","apply training-derived statistics and bounded scaling",
            [2,4,6],[0.,1.,[0.,.5,1.]], [round(float(tf.reduce_mean(standardized)),6),
            round(float(tf.math.reduce_std(standardized)),6),normal.numpy().tolist()])
        flat=tf.one_hot([2,0],3)
        padded=keras.utils.pad_sequences([[1,2,3,4],[5]],maxlen=3,padding="post",truncating="pre")
        observed(cases,"labels_and_padding","encode class positions and pad or truncate explicit sequences",
            {"depth":3,"pad":"post","truncate":"pre"},[[[0.,0.,1.],[1.,0.,0.]],[[2,3,4],[5,0,0]]],
            [flat.numpy().tolist(),padded.tolist()])
        paths=make_inputs(root)
        images=[rgb_image(tf.constant(path)).numpy() for path in paths]
        observed(cases,"mixed_image_decoders","decode locally generated JPEG and PNG, then resize and scale",
            {"files":4},[[[4,4,3]]*4,True],
            [[list(x.shape) for x in images],all(np.isfinite(x).all() and x.min()>=0 and x.max()<=1 for x in images)])
        eval_data=image_pipeline(paths,False)
        train_data=image_pipeline(paths,True)
        ex,ey=next(iter(eval_data))
        plain,labels=next(iter(eval_data))
        tx,ty=next(iter(train_data))
        observed(cases,"pipeline_train_eval","compare repeated validation and augmented training on same ordered files",
            {"batch_size":3,"images":4},[True,True,True],
            [bool(np.array_equal(ex,plain)),bool(np.array_equal(ey,labels) and np.array_equal(ey,ty)),
             bool(np.any(np.abs(ex-tx)>1e-4))])
        batches=[list(x.shape) for x,_ in eval_data]
        observed(cases,"batched_prefetch_cardinality","read all prefetched batches, including the short final batch",
            [4,3],[[3,4,4,3],[1,4,4,3]],batches)
        values=tf.data.Dataset.range(5)
        comparison=values.map(lambda x:x*x,num_parallel_calls=tf.data.AUTOTUNE,deterministic=True)
        observed(cases,"optimized_map_matches_serial","retain output order in parallel mapping",
            {"values":5},[True,[0,1,4,9,16]],
            [numbers(comparison)==numbers(values.map(lambda x:x*x)),numbers(comparison)])
        cached=tf.data.TextLineDataset([str(text)]).cache().with_options(opts())
        before=[x.decode() for x in cached.as_numpy_iterator()]
        text.write_bytes(b"changed\n")
        after=[x.decode() for x in cached.as_numpy_iterator()]
        observed(cases,"cache_avoids_recomputing","read a fully cached dataset after changing the backing file",
            {"cache":"memory"},[["one","two"],["one","two"]],[before,after])
        text2=root/"second.txt"
        text2.write_bytes(b"other\nsecond\n")
        mixed=tf.data.Dataset.from_tensor_slices([str(text),str(text2)]).interleave(
            lambda file:tf.data.TextLineDataset(file),cycle_length=2,block_length=1)
        observed(cases,"replicable_sharding_and_interleave","compare selected modulo indices and deterministic interleaving",
            {"num_shards":2,"index":1},[[1,3],["changed","other","second"]],
            [numbers(values.shard(2,1)),[x.decode() for x in numbers(mixed)]])
        streams=[tf.data.Dataset.from_tensors(i).repeat() for i in (0,1)]
        chosen=tf.data.Dataset.sample_from_datasets(streams,weights=[.7,.3],seed=73).take(200)
        zero=numbers(chosen).count(0)
        observed(cases,"weighted_sampling","draw two non-exhausting class streams with approximate target weights",
            {"draws":200,"weights":[.7,.3],"seed":73},True,115<zero<165,{"class_zero":zero})
    emit(cases)


if __name__=="__main__":
    main()

同一批图像训练时发生增广,验证保持一致。JPEG 与 PNG 保留统一的 4×4×3 形状。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a363.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:TensorFlow

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

下载课程关联工程包:TensorFlow

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

缓存增强前的静态输出,能够在后续迭代重新抽取训练增强。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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