Keras 第一个神经网络
用 Keras 训练 784→512→10 网络,验证分割、配置、预测和保存。
学完这一章,你能够
- 用 Keras 训练 784→512→10 网络,验证分割、配置、预测和保存。
固定可复现的输入与标签
在同一独立 Python 环境内使用 TensorFlow 2.21 和 Keras 3。Theano 与 CNTK 是早版历史。MNIST 官方训练、测试分别为 60000 和 10000 张 28×28 灰度图。将图像展平为 784 个浮点值,并按 255 缩放。将类索引转为宽度 10 的 one-hot 向量。本站例固定抽取各数据组,记录规模与拆分。
明确网络结构和优化条件
使用 784 维输入、512 个 ReLU 隐藏单元和 10 个 softmax 输出。编译时指定优化器、one-hot 损失和准确率。训练轮数表示遍历训练样本的次数。验证集来自训练资源内保留的区间,测试集只用于结束后的 evaluate。若对 NumPy 数组设置 validation_split,Keras 先取尾部作为验证,之后才打乱剩余训练数据。
按目标调整结构并保存验证结果
Dropout 和附加 Dense 层放在分类头前面,卷积需要保留图像的空间轴,不能直接追加到已输出类别向量的模型。可比较 Adam 与 RMSprop、数据缩放、学习率和网络宽度。冻结训练选择后读取独立测试集分数。保存 .keras 后重载比较预测,已有 .h5 可按对应 Keras 版本检查兼容。
编译参数
| 参数 | 用途 | 选值说明 |
|---|---|---|
| optimizer | 按梯度更新参数。 | 实验 RMSprop,独立变体 Adam。 |
| loss | 生成供反向传播的训练目标。 | one-hot 使用 categorical_crossentropy;MSE 常用于回归。 |
| metrics | 衡量训练与评估表现。 | 以 accuracy 观察分类。 |
训练参数
| 参数 | 用途 | 本地实验条件 |
|---|---|---|
| batch_size | 单次更新的样本上限。 | 用 128,最后一个批次可少于该值。 |
| epochs | 完整遍历训练集若干轮。 | 固定 4 轮,观察训练及验证日志。 |
| validation_split | NumPy 数据的末尾可保留验证。 | 独立例显式提供验证集,并实测尾部拆分等价。 |
训练全连接 MNIST 分类器并复跑保存模型
"""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()
- 测试集概率每行加总为 1,重载模型保留相同预测。
所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
当前源码 SHA256:33471fb254dc9366fab7244d9835d9297b7771e671c47436961cdc20c68d8375
本地运行
解压后按 README 运行本站程序。
所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
ZIP SHA256:cc375d24be22b7b58587a60bd4f44dc1994d10b51d520fc0861624ac0af52453
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
原始标签是整数,是否必须做 one-hot?
展开参考解答
不必。可保留整数并使用 sparse_categorical_crossentropy。