蓝色天空网mbsky.com · 知识 · 实践 · 创造TensorFlow · 本地阅读预览
教程 / AI / 智能开发 / TensorFlow

TensorFlow 实例 - 图像分类项目

用真实 CIFAR-10 图像核对 RGB 归一化、卷积形状、训练曲线与独立测试预测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

从单标签分类开始

分类把一张图映射到预先约定的类别。猫狗、花卉物种和医学影像分类使用不同标签与评估协议。本章使用 TensorFlow 的计算和 Keras 的分层训练接口,输出真实曲线数据供阅读页绘图。Matplotlib 也是绘制训练历史的常用工具。本实验在 Python 3.12 上用 requirements.txt 锁定训练依赖,输出实际版本。

核对输入图像、标签和三份数据

CIFAR-10 有 50,000 张官方训练图和 10,000 张官方测试图,均为 32×32 RGB。十类编号从 0 开始,依次是飞机、汽车、鸟、猫、鹿、狗、蛙、马、船、卡车。Keras 有内置数据加载器;本站同源二进制读取器校验摘要,按每行 1 字节标签与 3,072 字节平面 RGB 解析。

把三个通道转为 [样本,高,宽,通道],将 uint8 除以 255 得到 [0,1] 的 float32。取 1,536 个官方训练样本用于拟合,另取 384 个训练样本做验证,同时从官方测试批取 384 个最终样本。训练和验证位置互斥,测试独立。

卷积层输出 logits

三次卷积和两次池化抽取局部模式。卷积借助局部连接与权重共享,不需要为每个像素位置另建权重。展平特征后用全连接层输出十个 logits。层形状由本站运行结果核对。

RGB 输入经过三次卷积和两次池化,最终输出十类 logits。
本站按本章实际执行的分类网络绘制。

稀疏分类损失直接读取整数标签和十个 logits,因此设置 from_logits=True。评估用稀疏类别准确率;预测可在最后单独做 softmax,保留十个相加为 1 的概率。

训练十轮并保存训练与验证曲线

每轮从 24 个训练批次更新,并记录训练与验证准确率和损失。观察训练与验证走势,选轮数和超参数只用验证数据。图按十轮真实历史绘制,最终测试留到确定模型后。

CIFAR-10 训练及验证子集的十轮分类准确率。
本站根据十轮实际训练历史绘制,两条线来自独立的训练与验证子集。

评估测试并逐个解码预测

evaluate 统计独立测试子集的损失和准确率,并与逐样本预测的命中比例核对。对固定的前五个测试索引计算 softmax,取最大概率对应类号,再分别映射真实与预测标签。

一次改变一个条件后再比较

尝试增加卷积层、加入只在训练时启用的增广,或调整批归一化、优化器与学习率。本站还运行了增广、批归一化和 SGD 的小型变体,验证计算路径。显存不足时先减批量并重新测量,改变分辨率还要核对输入布局。医学、道路、工业和安防等用途应使用对应域的数据和评价协议。

训练 CIFAR-10 小型卷积网并输出五张测试图的分类结果

python · 阅读源码
"""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)
预期结果 · 待实际运行核验
  • 记录十轮训练与验证历史,测试准确率与直接统计一致,五个概率向量各有十项。
训练 CIFAR-10 小型卷积网并输出五张测试图的分类结果

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

当前源码 SHA256:9b2c133bf504bb802a379fb87be8ed24de9559c8d26003f36554c85461a67e71

下载本站示例源码

本地运行

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

下载TensorFlow 实例 - 图像分类项目实例

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

ZIP SHA256:ed0c847b4c42e6868c93881cf71ea84e2f0ad48a24ecd1606b01506a63f65455

常见错误与边界

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

练习与解答

如果最后一层已使用 softmax,损失配置要怎样改变?

展开参考解答

将 from_logits 设为 False,然后传递概率。

规范与官方依据