图像分类-flower_photos 实验研究

简介: 数据集: flower_photosdaisy: 633张图片 雏菊dandelion: 898张图片 蒲公英roses: 641张图片 玫瑰sunflowers: 699张图片 向日葵tulips: 799张图片 郁金香数据存储在本地磁盘,读取用的是 tf.keras.preprocessing.image_dataset_from_directory(),其中的 image_size 用作 image resize,batch_size 用作 batch

数据集: flower_photos

  1. daisy: 633张图片 雏菊
  2. dandelion: 898张图片 蒲公英
  3. roses: 641张图片 玫瑰
  4. sunflowers: 699张图片 向日葵
  5. tulips: 799张图片 郁金香

数据存储在本地磁盘,读取用的是 tf.keras.preprocessing.image_dataset_from_directory(),其中的 image_size 用作 image resize,batch_size 用作 batch

最后的 train_ds = train_ds.shuffle().cache().prefetch(),这样做的目的是减少 IO blocking

下面是模型搭建的代码:

model = tf.keras.Sequential([
    tf.keras.layers.experimental.preprocessing.Rescaling(1. / 255),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(num_classes)
])

此处把 pixel 的 rescale 放进了 Sequential,当做模型搭建的一部分,有利于模型部署

callbacks 里面用到了 ReduceLROnPlateau,Tensorboard,EarlyStopping

上图是训练模型四次的 log 记录图,其中 val_acc 的区间在 [0.6499, 0.6785],这个是正常现象,所以训练出来的模型准确率是会存在波动的

代码地址: https://github.com/MaoXianXin/Tensorflow_tutorial,但是需要在如上图的地方 flower dataset 这个 commit 处开一个新分支,然后找到 3.py 这个脚本,就能重复上图的实验了

因为上面的实验,准确率才 [0.6499, 0.6785],我们需要进行优化,第一个改进是添加 data augmentation,此处我们直接在模型搭建环节添加,代码如下所示

model = tf.keras.Sequential([
    tf.keras.layers.experimental.preprocessing.Rescaling(1. / 255),
    augmentation_dict[args.key],
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Conv2D(32, 3, activation='relu'),
    tf.keras.layers.MaxPooling2D(),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(num_classes)
])

augmentation_dict[args.key],这个就是添加的 data augmentation,此处我们只添加单种,具体 data augmentation 种类如下所示

augmentation_dict = {
    'RandomFlip': tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
    'RandomRotation': tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),
    'RandomContrast': tf.keras.layers.experimental.preprocessing.RandomContrast(0.2),
    'RandomZoom': tf.keras.layers.experimental.preprocessing.RandomZoom(height_factor=0.1, width_factor=0.1),
    'RandomTranslation': tf.keras.layers.experimental.preprocessing.RandomTranslation(height_factor=0.1, width_factor=0.1),
    'RandomCrop': tf.keras.layers.experimental.preprocessing.RandomCrop(img_height, img_width),
    'RandomFlip_prob': RandomFlip_prob("horizontal_and_vertical"),
    'RandomRotation_prob': RandomRotation_prob(0.2),
    'RandomTranslation_prob': RandomTranslation_prob(height_factor=0.1, width_factor=0.1),
}

接下来我们看下实验结果的 log 记录图

可以看到,val_acc 大于 0.6785 (未添加数据增强) 的有 RandomTranslation > RandomRotation_prob > RandomRotation > RandomFlip_prob = RandomFlip > RandomZoom > RandomTranslation_prob

从结果看来,数据增强是有效的,接下来我们进行第二个改进,更换更强的网络模型,我们这里选择 MobileNetV2

这里我们分两种情况进行实验,第一种是把 MobileNetV2 当做 feature extraction 来使用,这个要求我们 freeze 模型的 卷积部分,只训练添加进去的 top-classifier 部分,下面上代码

data_augmentation = tf.keras.Sequential([
    augmentation_dict[args.key],
])

preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input
base_model = tf.keras.applications.MobileNetV2(input_shape=img_size,
                                               include_top=False,
                                               weights='imagenet')
base_model.trainable = False

inputs = tf.keras.Input(shape=img_size)
x = data_augmentation(inputs)
x = preprocess_input(x)
x = base_model(x, training=False)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = tf.keras.layers.Dense(num_classes)(x)
model = tf.keras.Model(inputs, outputs)
print(model.summary())

实验结果如下图所示

可以看到,准确率提升很显著,从数据增强的 0.7316 提升到了 0.8937,这主要得益于 pre-trained model 是在 ImageNet 大数据集上做过训练,提取到的特征泛化性更好

为了进一步提升模型的准确率,我们采用第二种方式,对 pre-trained model 做 fine-tune,就是在第一种方式的基础上,我们 unfreeze 部分卷积层,因为浅层的卷积提取的特征都是很基础的特征,意味着很通用,但是深层的卷积提取的特征都是和数据集高度相关的,这里我们要解决的是 flower_photos,所以可以对深层的一部分卷积做训练,以进一步提高模型的准确率

下面上代码

data_augmentation = tf.keras.Sequential([
    augmentation_dict[args.key],
])

preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input
base_model = tf.keras.applications.MobileNetV2(input_shape=img_size,
                                               include_top=False,
                                               weights='imagenet')
base_model.trainable = True
# Let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(base_model.layers))

# Fine-tune from this layer onwards
fine_tune_at = 100

# Freeze all the layers before the `fine_tune_at` layer
for layer in base_model.layers[:fine_tune_at]:
    layer.trainable = False

inputs = tf.keras.Input(shape=img_size)
x = data_augmentation(inputs)
x = preprocess_input(x)
x = base_model(x, training=False)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = tf.keras.layers.Dense(num_classes)(x)
model = tf.keras.Model(inputs, outputs)
model.load_weights('./save_models')
print(model.summary())

optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4)
model.compile(
    optimizer=optimizer,
    loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'])
K.set_value(model.optimizer.learning_rate, 1e-4)

这里有个特别需要注意的地方是 learning_rate 的设置,K.set_value(model.optimizer.learning_rate, 1e-4),这个地方还是我特地查看了下 learning_rate 的 log 记录图才发现的不对劲

可以看到,进行 fine-tune 的话,模型准确率进一步提升,从 0.8937 ---> 0.9482

到此为止,我们实现了在 flower_photos 数据集上 val_acc = 0.9482,下一步可能会用 RandAugment 或者 Semi-supervised 来提升模型的泛化能力

代码地址: https://github.com/MaoXianXin/Tensorflow_tutorial

目录
相关文章
|
11月前
|
机器学习/深度学习 监控 数据可视化
基于YOLOv8的停车场空车位目标检测项目|完整源码数据集+PyQt5界面+完整训练流程+开箱即用!
本项目基于YOLOv8实现停车场空车位智能检测,支持Occupied/Vacant双类别识别,集成PyQt5图形界面,兼容图片、视频、摄像头等多源输入。提供完整源码、标注数据集、预训练权重及详细教程,开箱即用,适用于毕设、科研与智慧停车原型开发。
基于YOLOv8的停车场空车位目标检测项目|完整源码数据集+PyQt5界面+完整训练流程+开箱即用!
|
人工智能 运维 安全
2025年企业级智能体开发平台应用报告:从工具到生产力的重塑
AI Agent正从“聊天助手”进化为“数字员工”,成为企业数字化转型的核心引擎。甲子光年智库《企业级AI Agent价值及应用报告》指出,2025年技术成熟与需求爆发将推动AI Agent在金融、制造、医疗等领域深度落地,实现自主决策与跨系统协同,重塑生产力格局。
2005 2
|
虚拟化 数据安全/隐私保护
VMware Workstation Pro - 最新版
VMware是一款强大的虚拟机软件,可在单台计算机上模拟完整硬件系统,实现多系统运行。2024年5月推出最新版Workstation Pro 17.5.2,个人用户可免费使用。用户可通过官网下载并注册账户,按指引完成安装,适用于开发、测试及部署应用,具备高效灵活的虚拟化技术。
47526 1
【Latex 格式】Markdown或者LaTeX在单个字母上加一横、一点、两点、三角
Markdown或者LaTeX在单个字母上加一横、一点、两点、三角
2553 8
|
机器学习/深度学习 算法 PyTorch
从零开始深度学习:全连接层、损失函数与梯度下降的详尽指南
在深度学习的领域,全连接层、损失函数与梯度下降是三块重要的基石。如果你正在踏上深度学习的旅程,理解它们是迈向成功的第一步。这篇文章将从概念到代码、从基础到进阶,详细剖析这三个主题,帮助你从小白成长为能够解决实际问题的开发者。
1000 0
|
自然语言处理 Python
【Python自然语言处理】文本向量化的六种常见模型讲解(独热编码、词袋模型、词频-逆文档频率模型、N元模型、单词-向量模型、文档-向量模型)
【Python自然语言处理】文本向量化的六种常见模型讲解(独热编码、词袋模型、词频-逆文档频率模型、N元模型、单词-向量模型、文档-向量模型)
5137 0
|
编解码 人工智能 算法
【AI系统】EfficientNet 系列
本文介绍了EfficientNet系列模型,特别是EfficientNet V1和V2。EfficientNet V1通过NAS技术同时探索网络的宽度、深度和分辨率对模型性能的影响,提出了复合模型缩放方法,以平衡三者关系,实现高效模型扩展。EfficientNet V2在此基础上,引入Fused-MBConv模块,采用渐进式学习策略和自适应正则化技术,进一步提升了模型的训练速度和推理效率。
1733 6
【AI系统】EfficientNet 系列
|
传感器 算法 定位技术
技术心得记录:常用的滤波算法
技术心得记录:常用的滤波算法
1260 0
|
BI 索引
HID 入门学习:标准请求和类请求
HID 入门学习:标准请求和类请求
1546 0