"""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()
本例需在 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-data-processing-lab/build-image-input-pipeline.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
build-image-input-pipeline.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a363.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip