"""Train a small color image classifier from the official CIFAR-10 binary data."""
from argparse import ArgumentParser
from hashlib import file_digest
import json
import platform
import tarfile
import numpy as np
import tensorflow as tf
from tensorflow import keras
ARCHIVE_SHA256 = "c4a38c50a1bc5f3a1c5537f2155ab9d68f9f25eb1ed8d9ddda3db29a59bca1dd"
CLASSES = ("airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck")
def read_split(archive, train_indices, test_indices):
with open(archive,"rb") as source:
actual_sha = file_digest(source,"sha256").hexdigest()
if actual_sha != ARCHIVE_SHA256:
raise ValueError("The file does not match the official binary release used in this exercise.")
images = np.empty((len(train_indices),32,32,3),dtype=np.uint8)
labels = np.empty(len(train_indices),dtype=np.uint8)
test_images = np.empty((len(test_indices),32,32,3),dtype=np.uint8)
test_labels = np.empty(len(test_indices),dtype=np.uint8)
processed = []
train_tally = np.zeros(10,dtype=np.int64)
test_tally = np.zeros(10,dtype=np.int64)
prefix = "cifar-10-batches-bin/"
training = {f"{prefix}data_batch_{i+1}.bin":i*10000 for i in range(5)}
test_name = prefix+"test_batch.bin"
with tarfile.open(archive,mode="r|gz") as package:
for member in package:
if member.name not in training and member.name != test_name:
continue
if member.name in processed or not member.isfile() or member.size!=30730000:
raise ValueError("A binary batch has an unexpected name, type or length.")
with package.extractfile(member) as stream:
data = np.frombuffer(stream.read(),dtype=np.uint8).reshape(10000,3073)
if np.max(data[:,0])>9:
raise ValueError("A batch contains an unknown class index.")
if member.name==test_name:
records = data[test_indices]
test_images[:]=records[:,1:].reshape(-1,3,32,32).transpose(0,2,3,1)
test_labels[:]=records[:,0]
test_tally+=np.bincount(data[:,0],minlength=10)
else:
start = training[member.name]
positions = np.flatnonzero((start<=train_indices)&(train_indices<start+10000))
records = data[train_indices[positions]-start]
images[positions]=records[:,1:].reshape(-1,3,32,32).transpose(0,2,3,1)
labels[positions]=records[:,0]
train_tally+=np.bincount(data[:,0],minlength=10)
processed.append(member.name)
if len(processed)!=6:
raise ValueError("Expected five training batches and one test batch.")
return images,labels,test_images,test_labels,train_tally.tolist(),test_tally.tolist()
def prepared(images,labels,train=False,batch_size=64):
x=images.astype(np.float32)/255
dataset=tf.data.Dataset.from_tensor_slices((x,labels.astype(np.int32)))
options=tf.data.Options()
options.threading.private_threadpool_size=1
dataset=dataset.with_options(options)
if train:
dataset=dataset.shuffle(len(labels),seed=1601)
return dataset.batch(batch_size).prefetch(1)
def cnn():
return keras.Sequential([
keras.Input((32,32,3)),
keras.layers.Conv2D(12,3,activation="relu"),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(20,3,activation="relu"),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(24,3,activation="relu"),
keras.layers.Flatten(),
keras.layers.Dense(32,activation="relu"),
keras.layers.Dense(10),
])
def observe(cases,name,operation,inputs,expected,actual,measurements=None):
assert actual==expected,(name,actual,expected)
row=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
if measurements is not None:
row["measurements"]=measurements
cases.append(row)
def main(archive):
keras.utils.set_random_seed(1630)
cases=[]
observe(cases,"runtime_versions","Record the interpreter and library versions that execute the walkthrough",
{"expected_dependencies":["TensorFlow","Keras","NumPy"]},[True,True,True],
[bool(tf.__version__),bool(keras.__version__),bool(np.__version__)],
{"python":platform.python_version(),"tensorflow":tf.__version__,"keras":keras.__version__,"numpy":np.__version__})
train_count,val_count,test_count=1536,384,384
selector=np.random.default_rng(1610).permutation(50000)[:train_count+val_count]
test_indices=np.random.default_rng(1611).permutation(10000)[:test_count]
x,y,tx,ty,train_tally,test_tally=read_split(archive,selector,test_indices)
observe(cases,"cifar_verified_batches","Verify the official archive, five train batches and one test batch",
{"archive_sha256":ARCHIVE_SHA256,"record_bytes":3073},[50000,10000,[5000]*10,[1000]*10],
[sum(train_tally),sum(test_tally),train_tally,test_tally],{"classes":list(CLASSES)})
observe(cases,"rgb_normalization","Compare source channels, normalized endpoints and sparse label shape",
{"training":train_count,"validation":val_count,"test":test_count},
[[1920,32,32,3],[1920],[384,32,32,3],[384],[0.,1.],True],
[list(x.shape),list(y.shape),list(tx.shape),list(ty.shape),
[float(np.min(x.astype(np.float32)/255)),float(np.max(x.astype(np.float32)/255))],
len(set(selector.tolist()))==train_count+val_count],{"test_partition":"official test batch; independent from train/validation"})
training=prepared(x[:train_count],y[:train_count],train=True)
validation=prepared(x[train_count:],y[train_count:])
test=prepared(tx,ty)
model=cnn()
logits=model(x[:2].astype(np.float32)/255)
observe(cases,"cnn_shape_and_logits","Check three convolution stages, two pooling layers, and ten unconstrained output scores",
{"input":[2,32,32,3]},[3,2,[2,10],"linear"],
[sum(isinstance(layer,keras.layers.Conv2D) for layer in model.layers),
sum(isinstance(layer,keras.layers.MaxPooling2D) for layer in model.layers),
list(logits.shape),model.layers[-1].get_config()["activation"]],
{"parameters":model.count_params(),"layers":[[layer.__class__.__name__,list(layer.output.shape)] for layer in model.layers]})
model.compile(optimizer=keras.optimizers.Adam(.002),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[keras.metrics.SparseCategoricalAccuracy(name="accuracy")])
values=model.loss(tf.constant(y[:2],dtype=tf.int32),logits)
reference=tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.constant(y[:2],dtype=tf.int32),logits=logits))
observe(cases,"sparse_loss_contract","Compare the configured sparse loss with TensorFlow's logits loss",
{"labels":y[:2].tolist(),"from_logits":True},[True,True],
[model.loss.from_logits,abs(float(values)-float(reference))<1e-6])
history=model.fit(training,validation_data=validation,epochs=10,verbose=0,shuffle=False).history
observe(cases,"cifar_training_history","Run ten epochs and compare validation and train metrics at fixed sample counts",
{"epochs":10,"batch_size":64,"train":train_count,"validation":val_count},[240,10,10,True,True],
[int(model.optimizer.iterations),len(history["loss"]),len(history["val_accuracy"]),
history["loss"][-1]<history["loss"][0],
all(np.isfinite(series).all() for series in history.values())],{"history":history})
metrics=model.evaluate(test,verbose=0,return_dict=True)
all_test_scores=model(tx.astype(np.float32)/255,training=False)
computed=float(np.mean(np.argmax(all_test_scores.numpy(),axis=1)==ty))
observe(cases,"independent_test_evaluation","Evaluate the untouched test subset and compare categorical accuracy with direct predictions",
{"test_rows":test_count},[["accuracy","loss"],True,True],
[sorted(metrics),bool(np.isfinite(list(metrics.values())).all()),abs(computed-metrics["accuracy"])<1e-6],metrics)
probabilities=tf.nn.softmax(all_test_scores[:5],axis=-1).numpy()
predicted=np.argmax(probabilities,axis=1)
observe(cases,"five_probability_predictions","Softmax five logits and decode both predicted and actual class indices",
{"source_test_indices":test_indices[:5].tolist()},[[5,10],True,True],
[list(probabilities.shape),bool(np.allclose(probabilities.sum(axis=1),1)),bool(np.all((probabilities>=0)&(probabilities<=1)))],
{"actual":[CLASSES[value] for value in ty[:5]],"predicted":[CLASSES[value] for value in predicted],
"scores":probabilities.tolist()})
sample=x[:8].astype(np.float32)/255
augmentation=keras.layers.RandomFlip("horizontal",seed=12)
changed=augmentation(sample,training=True)
same=augmentation(sample,training=False)
adjusted=keras.Sequential([keras.Input((32,32,3)),keras.layers.Conv2D(8,3,use_bias=False),
keras.layers.BatchNormalization(),keras.layers.Activation("relu"),keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(10)])
adjusted.compile(optimizer=keras.optimizers.SGD(.01),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True))
updated=adjusted.train_on_batch(changed,y[:8])
observe(cases,"augmentation_bn_variant","Run one variant update with horizontal augmentation, batch normalization, and SGD",
{"sample_count":8,"learning_rate":.01},[True,True,1,True],
[bool(tf.reduce_any(changed!=sample)),bool(tf.reduce_all(same==sample)),
int(adjusted.optimizer.iterations),bool(np.isfinite(updated))],
{"parameters":adjusted.count_params(),"batch_loss":float(updated)})
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
system=platform.system(),devices=[device.name for device in tf.config.list_physical_devices()],cases=cases)))
if __name__=="__main__":
parser=ArgumentParser()
parser.add_argument("archive",help="Path to the official cifar-10-binary.tar.gz")
main(parser.parse_args().archive)
本例需在 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-image-classification-lab/train-cifar10-classifier.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
train-cifar10-classifier.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a366.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip