"""Train and check a dense handwritten-digit classifier on verified local data."""
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)
from hashlib import file_digest
DIGEST="731c5ac602752760c8e48fbffcf8c3b850d9dc2a2aedcf2cc48468fc17b673d1"
def partitions(layout,num_train,with_labels):
path=Path(__file__).resolve().parent/"datasets/mnist.npz"
with path.open("rb") as stream:
assert file_digest(stream,"sha256").hexdigest()==DIGEST
with np.load(path,allow_pickle=False) as data:
assert data["x_train"].shape==(60000,28,28) and data["x_test"].shape==(10000,28,28)
assert data["y_train"].shape==(60000,) and data["y_test"].shape==(10000,)
def images(name,span):
return data[name][span].astype("float32").reshape((-1,*layout))/255
def labels(name,span):
y=data[name][span]
return keras.utils.to_categorical(y,10) if with_labels else y
tr=slice(0,num_train)
vl=slice(num_train,num_train+512)
te=slice(0,1024)
return [(images("x_train",tr),labels("y_train",tr)),(images("x_train",vl),labels("y_train",vl)),
(images("x_test",te),labels("y_test",te))]
def dataset(x,y,batch=128):
data=tf.data.Dataset.from_tensor_slices((x,y)).batch(batch)
options=tf.data.Options()
options.threading.private_threadpool_size=1
return data.with_options(options)
class BatchCount(keras.callbacks.Callback):
def __init__(self):
super().__init__()
self.total=0
def on_train_batch_end(self,batch,logs=None):
self.total+=1
def main():
cases=[]
keras.utils.set_random_seed(2718)
train,val,test=partitions((784,),4096,True)
observed(cases,"backend_and_dataset","read Keras backend and three independent array layouts",
{"dataset_sha256":DIGEST},["tensorflow",[4096,784],[512,784],[1024,784],True],
[keras.backend.backend(),list(train[0].shape),list(val[0].shape),list(test[0].shape),
bool(np.all(train[1].sum(axis=1)==1) and train[0].max()<=1)])
net=keras.Sequential([keras.Input((784,)),keras.layers.Dense(512,activation="relu"),
keras.layers.Dense(10,activation="softmax")])
shape=net(train[0][:3]).shape
observed(cases,"model_shape","run the pinned dense architecture on three examples",
{"layers":[784,512,10]},[[3,10],512],[list(shape),net.layers[0].units])
net.compile(keras.optimizers.RMSprop(.001),loss="categorical_crossentropy",metrics=["accuracy"])
observed(cases,"compile_for_one_hot","compare one-hot ground truth widths and the loss convention",
{"labels":10},["categorical_crossentropy",10],[net.loss,train[1].shape[1]])
count=BatchCount()
hist=net.fit(dataset(*train),validation_data=dataset(*val),epochs=4,callbacks=[count],verbose=0)
observed(cases,"fit_and_count_batches","run four passes of 32 batches each",
{"batch_size":128,"train":4096},[4,128,True],
[len(hist.history["loss"]),count.total,"val_accuracy" in hist.history])
outcome=net.evaluate(dataset(*test),return_dict=True,verbose=0)
observed(cases,"evaluate_unseen_test","evaluate held-out data from official test split",
{"held_out":1024},[True,True],[outcome["accuracy"]>.85,bool(np.isfinite(outcome["loss"]))],outcome)
probability=net.predict(test[0][:16],batch_size=16,verbose=0)
observed(cases,"probabilities_are_not_labels","derive labels from predicted probability vectors",
{"batch":16},[[16,10],[16],True],
[list(probability.shape),list(probability.argmax(axis=1).shape),bool(np.allclose(probability.sum(axis=1),1.))])
modified=keras.Sequential([keras.Input((28,28,1)),keras.layers.Conv2D(6,3,activation="relu"),
keras.layers.Flatten(),keras.layers.Dense(64,activation="relu"),keras.layers.Dropout(.5),keras.layers.Dense(10)])
shape=modified(tf.reshape(test[0][:2],(2,28,28,1)),training=False).shape
observed(cases,"optional_layers","build spatial convolution before flattening and place dropout upstream of the head",
{"examples":2},[[2,10],.5],[list(shape),modified.layers[3].rate])
adam=keras.optimizers.Adam(.001)
modified.compile(adam,loss=keras.losses.CategoricalCrossentropy(from_logits=True))
before=int(adam.iterations)
value=modified.train_on_batch(tf.reshape(train[0][:8],(8,28,28,1)),train[1][:8])
observed(cases,"optimizer_variants","run a real batch with a separately configured Adam optimizer",
{"batch":8},[True,1],[bool(np.isfinite(value)),int(adam.iterations)-before])
probe=keras.Sequential([keras.Input((1,)),keras.layers.Dense(1,kernel_initializer="zeros",bias_initializer="zeros")])
probe.compile(keras.optimizers.SGD(0.),loss="mse")
tiny_x=np.arange(8,dtype="float32").reshape(-1,1)
tiny_y=np.array([0,0,0,0,0,0,3,3],dtype="float32")
split=probe.fit(tiny_x,tiny_y,validation_split=.25,batch_size=4,shuffle=False,epochs=1,verbose=0)
observed(cases,"validation_split_tail_observed","isolate the final quarter of a NumPy dataset for validation",
{"size":8,"fraction":.25},[0.,9.],
[float(split.history["loss"][0]),float(split.history["val_loss"][0])])
with TemporaryDirectory(prefix="blue-sky-mnist-dense-") as tmp:
path=Path(tmp)/"dense-mnist.keras"
net.save(path)
restored=keras.models.load_model(path,compile=False)
after=restored(test[0][:16]).numpy()
observed(cases,"keras_round_trip","save and load an owned .keras classifier and compare probabilities",
{"prediction_rows":16},True,bool(np.allclose(after,probability)))
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-keras-neural-network-lab/first-mnist-network.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
first-mnist-network.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a371.zip