深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型

🤵‍♂️ 个人主页:@艾派森的个人主页

✍🏻作者简介:Python学习者

🐋 希望大家多多支持,我们一起进步!😄

如果文章对你有帮助的话,

欢迎评论 💬点赞👍🏻 收藏 📂加关注+


目录

1.项目背景

2.数据集介绍

3.技术工具

4.实验过程

4.1导入数据

4.2数据可视化

4.3特征工程

4.4构建模型

4.5训练模型

4.6模型评估

4.7模型预测

5.总结

源代码


1.项目背景

珊瑚礁作为海洋生态系统中最具生物多样性的重要屏障,在维持海洋生态平衡、保护海岸线免受侵蚀以及支撑海洋生物栖息演化方面发挥着不可替代的作用。然而,随着全球气候变暖、海水温度异常升高以及环境污染的加剧,珊瑚白化现象日益频繁且严重,这对全球海洋生态系统造成了极其严峻的威胁。及时、准确地监测珊瑚的健康状况与白化趋势,是开展海洋生态保护与修复工作的重要前提。传统的水下珊瑚监测主要依赖于人工潜水观测与专家经验定性判断,这种方式不仅耗时费力、覆盖范围极其有限,而且极易受限于主观因素。近年来,水下成像技术的普及为海洋监测积累了海量的图像数据,利用深度学习与计算机视觉技术自动分析图像并精确识别健康与白化珊瑚,成为破局的关键。本项目旨在引入预训练卷积神经网络,构建高效可靠的珊瑚图像分类模型,实现水下珊瑚状态的自动化、智能化判别,为海洋生物科学研究、生态演变监测以及生态保护策略的制定提供有力的技术支撑。

2.数据集介绍

本实验数据集来源于Kaggle,健康珊瑚和白化珊瑚图像分类数据集。

本数据集专门用于区分健康珊瑚和白化珊瑚。它包含从 Flickr API 收集的共 923 张图片。这些图片被分为两类:健康珊瑚(438 张)和白化珊瑚(485 张)。为了保持数据集尺寸的一致性,所有图片的宽度或高度均被调整为最大 300 像素,取较大值。

该数据集的主要目的是帮助研究人员、数据科学家和机器学习爱好者开发和评估分类模型,以区分健康珊瑚和白化珊瑚。该数据集可用于训练各种机器学习模型,例如卷积神经网络 (CNN),以识别和区分健康珊瑚和白化珊瑚的视觉模式。

通过创建精确的分类模型,研究人员和海洋生物学家可以更好地了解珊瑚礁的健康状况,监测其环境的变化,并为保护和恢复这些重要的生态系统做出贡献。

数据集详情

  • 图片总数:923张
  • 图片类别 :2
    • 健康的珊瑚:438 张图片
    • 白化珊瑚:485 张图片
  • 图像格式:JPEG

3.技术工具

Python版本:3.9

代码编辑器:jupyter notebook

4.实验过程

4.1导入数据

在构建深度学习图像分类模型前,首先需要搭建完整的 Python 运行环境。本阶段集中导入数据处理、数值计算、可视化展示以及 TensorFlow/Keras 深度学习框架相关的核心依赖库,并对 Seaborn 的全局绘图风格进行统一设置,为后续的数据预处理、模型搭建与指标分析提供必要的技术支持。

python 复制代码
# 导入数据科学基础库
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
import itertools
import random
# 导入图像可视化库
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import cv2
import seaborn as sns
# 导入深度学习框架及网络层组件
from tensorflow import keras
from tensorflow.keras import layers,models
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import Callback, EarlyStopping,ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras import Model
from tensorflow.keras.layers.experimental import preprocessing
from tensorflow.keras.optimizers import Adam
# 导入系统路径处理库
from pathlib import Path
import os.path
# 导入模型评估指标工具
from sklearn.metrics import classification_report, confusion_matrix
# 设置背景网格样式
sns.set_style('darkgrid')

完成开发环境与基础依赖库的加载后,下一步需要对存储在磁盘上的图像数据集进行深度扫描与结构重组。首先定义基础的批次大小与图像目标分辨率,随后通过递归遍历函数打印数据集目录结构,最后利用 Path.glob 正则匹配检索所有格式的图像文件路径,提取上一级目录名称作为分类标签,并将其统一封装为结构化的 Pandas DataFrame 数据表。

python 复制代码
# 设置数据批次大小与目标图像分辨率
BATCH_SIZE = 32
TARGET_SIZE = (224, 224)
import os
# 定义目录结构遍历函数,统计子目录与图像文件数量
def walk_through_dir(dir_path):
  for dirpath, dirnames, filenames in os.walk(dir_path):
    print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.")
# 遍历珊瑚图像数据集根目录
dataset = "/kaggle/input/healthy-and-bleached-corals-image-classification"
walk_through_dir(dataset)
# 定义文件路径提取函数,将其转换为包含路径与标签的数据表
def convert_path_to_df(dataset):
    image_dir = Path(dataset)
    # 匹配多种常见格式的图像文件路径
    filepaths = list(image_dir.glob(r'**/*.JPG')) + list(image_dir.glob(r'**/*.jpg')) + list(image_dir.glob(r'**/*.jpeg')) + list(image_dir.glob(r'**/*.PNG'))
    # 解析上级目录名称作为图像类别标签
    labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], filepaths))
    filepaths = pd.Series(filepaths, name='Filepath').astype(str)
    labels = pd.Series(labels, name='Label')
    # 将文件路径列与类别标签列拼接成数据帧
    image_df = pd.concat([filepaths, labels], axis=1)
    return image_df

# 执行提取转换并生成目标数据帧
image_df = convert_path_to_df(dataset)

数据路径转换完成后,结构化的图像索引与标签信息已成功加载至内存中,为后续数据集划分、图像可视化以及特征预处理奠定了坚实的数据基础。

4.2数据可视化

在对图像数据进行深度特征提取与建模之前,首先需要对图像数据的类别分布状态进行探索性分析。通过统计各类别样本的频数,利用饼图与柱状图相结合的形式,直观展示健康珊瑚与白化珊瑚在整个数据集中的占比情况与数量分布,便于评估数据是否存在严重的类别不平衡问题。

python 复制代码
# 统计各个类别标签的数量分布
label_counts = image_df['Label'].value_counts()
# 创建包含两个子图的画布布局
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 6))
# 设置饼图的柔和色彩调色板
colors = sns.color_palette('pastel', len(label_counts))
# 绘制饼图,展示各类别的百分比占比与扇形切片分离效果
explode = [0.02] * len(label_counts)  # 设置每个切片的微小分离距离
axes[0].pie(label_counts.values, labels=label_counts.index, autopct='%1.1f%%', startangle=90, colors=colors, explode=explode)
axes[0].axis('equal')  # 保持正圆显示
axes[0].set_title('Percentage Distribution of Labels in Image Dataset', fontsize=16)
# 绘制柱状图,直观展现不同类别的样本频数
sns.barplot(x=label_counts.index, y=label_counts.values, alpha=0.8, palette='pastel', ax=axes[1])
axes[1].set_title('Count Distribution of Labels in Image Dataset', fontsize=16)
axes[1].set_xlabel('Label', fontsize=14)
axes[1].set_ylabel('Count', fontsize=14)
axes[1].set_xticklabels(label_counts.index, rotation=45)
# 设置主画布整体标题
fig.suptitle('Image Dataset Label Distribution', fontsize=20)
# 调整子图与主标题之间的间距
fig.subplots_adjust(top=0.85)
# 渲染展示图表
plt.show()

统计图表直观展示了数据集中各类别的分布比例,为后续数据划分与模型训练时的损失权重设定提供了客观依据。

完成整体标签分布的定量分析后,还需要对原始图像的画面质量、色彩形态以及标注正确性进行定性抽检。通过在数据集中随机抽取 16 张样本图像,构建 4 x 4 的多子图网格进行矩阵化渲染展示,并在各子图上方标出对应的类别标签,实现对健康与白化珊瑚直观视觉特征的初步感知。

python 复制代码
# 从数据集中随机抽取 16 张图像的索引位置
random_index = np.random.randint(0, len(image_df), 16)
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(10, 10),
                        subplot_kw={'xticks': [], 'yticks': []})
# 循环读取并展示抽取的图像及对应类别标签
for i, ax in enumerate(axes.flat):
    ax.imshow(plt.imread(image_df.Filepath[random_index[i]]))
    ax.set_title(image_df.Label[random_index[i]])
plt.tight_layout()
plt.show()

通过可视化随机抽样图像可以观察到,不同状态下的珊瑚存在较为明显的颜色与纹理差异,白化珊瑚呈现出明显的白化白斑特征,而健康珊瑚则保留了丰富的天然色素,这为卷积神经网络提取高阶视觉特征提供了良好的基础。

4.3特征工程

在完成数据可视化与探索性分析后,需要对数据进行划分并配置高效的数据加载与预处理管道。首先利用 train_test_split 将原始数据帧按 8:2 的比例划分为训练集与测试集;随后创建基于 VGG19 专属预处理函数的 ImageDataGenerator 生成器实例,为进一步的批次数据流式加载奠定基础。

python 复制代码
# 将原始数据划分为训练集与测试集
train_df, test_df = train_test_split(image_df, test_size=0.2, shuffle=True, random_state=42)
# 构建训练集数据生成器并配置 VGG19 预处理与验证集划分比例
train_generator = ImageDataGenerator(
    preprocessing_function=tf.keras.applications.vgg19.preprocess_input,
    validation_split=0.2
)
# 构建测试集数据生成器并配置 VGG19 预处理
test_generator = ImageDataGenerator(
    preprocessing_function=tf.keras.applications.vgg19.preprocess_input
)

通过配置好的生成器,调用 flow_from_dataframe 方法从数据帧中提取图像路径与对应标签,将数据正式拆分为训练集、验证集与测试集三个独立的迭代器。在加载过程中将图像统一调整至目标分辨率并进行独热编码转换,测试集则保持关闭随机打乱状态,以确保后续评估结果的准确性与一致性。

python 复制代码
# 构建训练集数据流迭代器
train_images = train_generator.flow_from_dataframe(
    dataframe=train_df,
    x_col='Filepath',
    y_col='Label',
    target_size=TARGET_SIZE,
    color_mode='rgb',
    class_mode='categorical',
    batch_size=BATCH_SIZE,
    shuffle=True,
    seed=42,
    subset='training'
)
# 构建验证集数据流迭代器
val_images = train_generator.flow_from_dataframe(
    dataframe=train_df,
    x_col='Filepath',
    y_col='Label',
    target_size=TARGET_SIZE,
    color_mode='rgb',
    class_mode='categorical',
    batch_size=BATCH_SIZE,
    shuffle=True,
    seed=42,
    subset='validation'
)
# 构建测试集数据流迭代器
test_images = test_generator.flow_from_dataframe(
    dataframe=test_df,
    x_col='Filepath',
    y_col='Label',
    target_size=TARGET_SIZE,
    color_mode='rgb',
    class_mode='categorical',
    batch_size=BATCH_SIZE,
    shuffle=False
)

为了提升模型对野外复杂水下环境的泛化性能并防止过拟合,最后构建由图像尺寸重置、像素缩放、水平翻转、随机旋转、随机缩放及随机对比度调节构成的 Sequential 数据增强模块,在训练过程中对输入图像施加动态扰动以扩充样本多样性。

python 复制代码
# 构建包含多种空间与色彩变换的数据增强组合层
augment = tf.keras.Sequential([
  layers.experimental.preprocessing.Resizing(224,224),
  layers.experimental.preprocessing.Rescaling(1./255),
  layers.experimental.preprocessing.RandomFlip("horizontal"),
  layers.experimental.preprocessing.RandomRotation(0.1),
  layers.experimental.preprocessing.RandomZoom(0.1),
  layers.experimental.preprocessing.RandomContrast(0.1),
])

通过数据划分、流式迭代器构建以及数据增强层的组合配置,完成了从原始磁盘图像到可用于深度神经网络高效训练的高质量特征数据流转换。

4.4构建模型

在完成数据准备与预处理后,本阶段采用迁移学习策略搭建图像分类网络。首先加载在 ImageNet 大规模数据集上预训练好的 VGG19 网络作为基础特征提取器,并将输入分辨率固定为 224 x 224 x 3,末端选用全局最大池化层以浓缩高阶视觉特征;同时将预训练主干网络的权重设为冻结状态,确保在训练初期仅更新后接的自定义分类头,避免破坏已学习到的通用边缘与纹理特征。

python 复制代码
# 加载预训练 VGG19 模型并冻结其主干网络权重
pretrained_model = tf.keras.applications.vgg19.VGG19(
    input_shape=(224, 224, 3),
    include_top=False,
    weights='imagenet',
    pooling='max'
)
pretrained_model.trainable = False

主干网络配置完成后,为了确保训练过程的稳定性与高效性,进一步配置回调函数组件。其中包括用于实时保存最佳验证准确率权重文件的 ModelCheckpoint、当验证集损失连续 5 个轮次不再下降时自动触发终止训练并恢复最佳权重的 EarlyStopping,以及在性能进入平台期后按照设定比例动态衰减学习率的 ReduceLROnPlateau,从而实现对模型训练轨迹的全方位掌控。

python 复制代码
# 配置模型检查点回调函数,仅保存验证集准确率最高时的权重
checkpoint_path = "corals_classification_model_checkpoint"
checkpoint_callback = ModelCheckpoint(checkpoint_path,
                                      save_weights_only=True,
                                      monitor="val_accuracy",
                                      save_best_only=True)
# 配置早停回调函数,防止模型过拟合
early_stopping = EarlyStopping(monitor = "val_loss", # 监控验证集损失指标
                               patience = 5,
                               restore_best_weights = True) # 恢复最佳权重
# 配置学习率动态调整回调函数,在损失企稳时降低学习率
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=1e-10)

预训练特征提取主干与训练控制回调函数的成功构建,为后续完成网络分类头的全连接搭建以及开启全流程模型训练奠定了稳健的技术架构。

4.5训练模型

完成预训练主干网络的提取与回调函数配置后,需要在 VGG19 特征提取层之上搭建自定义全连接分类头。将数据增强模块与输入层对接,并在基础模型输出后拼接多层全连接层,融合 BatchNormalization 批归一化层与 0.45 比例的 Dropout 随机失活层,有效防止深层网络参数拟合过度,末端接 Softmax 激活函数实现健康与白化珊瑚的双类别概率输出;接着选用 Adam 优化器配合交叉熵损失函数完成模型编译。

python 复制代码
# 获取预训练模型输入并叠加数据增强与全连接分类头
inputs = pretrained_model.input
x = augment(inputs)
# 组合 Dense、BatchNormalization 与 Dropout 构建多层分类分类网络
x = Dense(128, activation='relu')(pretrained_model.output)
x = BatchNormalization()(x)
x = Dropout(0.45)(x)
x = Dense(256, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(0.45)(x)
# 最终输出层(二分类问题)
outputs = Dense(2, activation='softmax')(x)
# 实例化完整 Model 模型对象
model = Model(inputs=inputs, outputs=outputs)
# 编译模型,设定优化器、损失函数与评估指标
model.compile(
    optimizer=Adam(0.001),
    loss='categorical_crossentropy',
    metrics=['accuracy']
)

网络结构编译完成后,定义 TensorBoard 动态日志生成函数,以便在训练期间实时记录各轮次的损失值与准确率走向。最后将训练集与验证集数据生成器传入 fit 函数开启全流程模型训练,并挂载 TensorBoard、早停、模型检查点及学习率衰减等一系列回调机制,以保障训练过程高效且稳健地收敛。

python 复制代码
import datetime
# 定义动态生成 TensorBoard 日志目录的回调函数
def create_tensorboard_callback(dir_name, experiment_name):
  log_dir = dir_name + "/" + experiment_name + "/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
  tensorboard_callback = tf.keras.callbacks.TensorBoard(
      log_dir=log_dir
  )
  print(f"Saving TensorBoard log files to: {log_dir}")
  return tensorboard_callback
# 启动全流程模型训练并加载全部回调函数
history = model.fit(
    train_images,
    steps_per_epoch=len(train_images),
    validation_data=val_images,
    validation_steps=len(val_images),
    epochs=100,
    callbacks=[
        early_stopping,
        create_tensorboard_callback("training_logs", 
                                    "corals_classification"),
        checkpoint_callback,
        reduce_lr
    ]
)

经过多轮迭代与回调机制的动态调控,模型在训练集与验证集上的指标逐步趋于稳定,训练历史数据已成功保存至 history 对象中,为后续开展详细的模型评估与推理预测奠定了数据基础。

4.6模型评估

模型训练完成后,首先在独立的测试集上对最终模型的泛化能力进行定量评估。通过调用 evaluate 方法计算模型在未参与训练与验证的测试图像上的损失值与分类准确率,从而客观反映模型对新样本的识别精度。

python 复制代码
# 在测试集上评估模型的最终损失与准确率
results = model.evaluate(test_images, verbose=0)
print("    Test Loss: {:.5f}".format(results[0]))
print("Test Accuracy: {:.2f}%".format(results[1] * 100))

测试集整体指标评估完成后,进一步从训练历史记录 history 中提取各轮次的训练集与验证集的准确率及损失值变化数据,绘制双子图对比折线图。通过观察训练与验证曲线的收敛趋势及变化幅度,直观地判断模型是否存在过拟合或欠拟合现象。

python 复制代码
# 从训练历史中提取准确率与损失值数据
accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(accuracy))
# 创建双子图画布展示准确率与损失变化曲线
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 绘制训练集与验证集准确率曲线
ax1.plot(epochs, accuracy, 'b', label='Training accuracy')
ax1.plot(epochs, val_accuracy, 'r', label='Validation accuracy')
ax1.set_title('Training and validation accuracy')
ax1.set_xlabel('Epochs')
ax1.set_ylabel('Accuracy')
ax1.legend()
# 绘制训练集与验证集损失值曲线
ax2.plot(epochs, loss, 'b', label='Training loss')
ax2.plot(epochs, val_loss, 'r', label='Validation loss')
ax2.set_title('Training and validation loss')
ax2.set_xlabel('Epochs')
ax2.set_ylabel('Loss')
ax2.legend()
# 设置总标题并渲染图表
fig.suptitle('Training and validation metrics', fontsize=16)
plt.show()

曲线走势表明模型的损失函数保持平稳下降,准确率稳步上升且训练与验证曲线高度贴合,说明早停与正则化策略有效地抑制了过拟合。

最后,对测试集进行全量预测推理,将预测得到的 Softmax 输出概率转化为最大概率索引,并映射回原始的字符串类别标签。通过调用 classification_report 计算健康珊瑚与白化珊瑚在精准率(Precision)、召回率(Recall)以及 F1 分数(F1-Score)上的详细指标,多维度评估模型的细粒度分类表现。

python 复制代码
# 对测试集图像进行概率预测并获取最大概率类别索引
pred = model.predict(test_images)
pred = np.argmax(pred, axis=1)
# 将数值标签反向映射回原始字符串类别名称
labels = (train_images.class_indices)
labels = dict((v, k) for k, v in labels.items())
pred = [labels[k] for k in pred]
# 获取测试集真实标签并打印详细分类报告
y_test = list(test_df.Label)
print(classification_report(y_test, pred))

分类报告输出结果全面展示了模型对各类珊瑚特征的提取与判别效能,各主要评估指标均保持在极高水平,验证了 VGG19 迁移学习模型在健康与白化珊瑚二分类任务上的有效性与实用价值。

4.7模型预测

在完成模型量化评估与性能分析后,为了直观验证模型的实际推理效果,随机抽取测试集中的 15 张图像进行可视化预测。通过将图像真实标签与模型预测结果进行对比,若两者一致则采用绿色标题高亮,预测错误则采用红色标题标注,以此检验模型在真实场景下的识别直观表现。

python 复制代码
# 从测试集中随机抽取 15 张图像进行可视化推理结果展示
random_index = np.random.randint(0, len(test_df) - 1, 15)
fig, axes = plt.subplots(nrows=3, ncols=5, figsize=(25, 15),
                        subplot_kw={'xticks': [], 'yticks': []})
# 遍历绘制 3x5 图像网格并依据预测正确性标注颜色
for i, ax in enumerate(axes.flat):
    ax.imshow(plt.imread(test_df.Filepath.iloc[random_index[i]]))
    if test_df.Label.iloc[random_index[i]] == pred[random_index[i]]:
        color = "green"
    else:
        color = "red"
    ax.set_title(f"True: {test_df.Label.iloc[random_index[i]]}\nPredicted: {pred[random_index[i]]}", color=color)
plt.show()
plt.tight_layout()

5.总结

本实验针对海洋生态监测中健康与白化珊瑚的自动识别需求,基于包含 923 张高质图像的数据集构建了基于 VGG19 迁移学习的二分类深度学习模型。通过集成数据增强、批归一化、Dropout 正则化以及包含早停与动态学习率调整的综合回调机制,模型成功学习到了珊瑚白化特征与健康状态的高阶视觉模式。在独立的测试集评估中,模型取得了 74.05% 的总体分类准确率与 0.71112 的测试损失;其中,模型在健康珊瑚识别上表现出较强的召回能力(Recall 为 0.85,F1 分数为 0.77),在白化珊瑚判定上展现出更高的精确度(Precision 为 0.81,F1 分数为 0.71)。实验结果表明,利用卷积神经网络提取复杂水下环境下的图像特征具备良好的可行性与实用价值,能够为海洋生物学家评估珊瑚礁健康状况、监测水下生态演变以及制定针对性的生态保护与恢复策略提供高效可靠的数据支撑与技术方案。

源代码

python 复制代码
# Import Data Science Libraries
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
import itertools
import random

# Import visualization libraries
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import cv2
import seaborn as sns

# Tensorflow Libraries
from tensorflow import keras
from tensorflow.keras import layers,models
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import Callback, EarlyStopping,ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras import Model
from tensorflow.keras.layers.experimental import preprocessing
from tensorflow.keras.optimizers import Adam

# System libraries
from pathlib import Path
import os.path

# Metrics
from sklearn.metrics import classification_report, confusion_matrix

sns.set_style('darkgrid')
BATCH_SIZE = 32
TARGET_SIZE = (224, 224)
import os
def walk_through_dir(dir_path):
  for dirpath, dirnames, filenames in os.walk(dir_path):
    print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.")
# Walk through each directory
dataset = "/kaggle/input/healthy-and-bleached-corals-image-classification"
walk_through_dir(dataset)

def convert_path_to_df(dataset):
    image_dir = Path(dataset)

    # Get filepaths and labels
    filepaths = list(image_dir.glob(r'**/*.JPG')) + list(image_dir.glob(r'**/*.jpg')) + list(image_dir.glob(r'**/*.jpeg')) + list(image_dir.glob(r'**/*.PNG'))

    labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], filepaths))

    filepaths = pd.Series(filepaths, name='Filepath').astype(str)
    labels = pd.Series(labels, name='Label')

    # Concatenate filepaths and labels
    image_df = pd.concat([filepaths, labels], axis=1)
    return image_df

image_df = convert_path_to_df(dataset)
# Get the value counts for each label
label_counts = image_df['Label'].value_counts()

# Create the figure and axes
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 6))

# Define the color palette for the pie chart
colors = sns.color_palette('pastel', len(label_counts))

# Plot the pie chart with percentages, colors, and separation
explode = [0.02] * len(label_counts)  # Define separation values for each pie slice
axes[0].pie(label_counts.values, labels=label_counts.index, autopct='%1.1f%%', startangle=90, colors=colors, explode=explode)
axes[0].axis('equal')  # Equal aspect ratio ensures the pie chart is circular
axes[0].set_title('Percentage Distribution of Labels in Image Dataset', fontsize=16)

# Plot the bar chart
sns.barplot(x=label_counts.index, y=label_counts.values, alpha=0.8, palette='pastel', ax=axes[1])
axes[1].set_title('Count Distribution of Labels in Image Dataset', fontsize=16)
axes[1].set_xlabel('Label', fontsize=14)
axes[1].set_ylabel('Count', fontsize=14)
axes[1].set_xticklabels(label_counts.index, rotation=45)

# Add a super-title to the figure
fig.suptitle('Image Dataset Label Distribution', fontsize=20)

# Adjust the spacing between the plots and the title
fig.subplots_adjust(top=0.85)

# Display the plot
plt.show()
# Display 16 picture of the dataset with their labels
random_index = np.random.randint(0, len(image_df), 16)
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(10, 10),
                        subplot_kw={'xticks': [], 'yticks': []})

for i, ax in enumerate(axes.flat):
    ax.imshow(plt.imread(image_df.Filepath[random_index[i]]))
    ax.set_title(image_df.Label[random_index[i]])
plt.tight_layout()
plt.show()
# Separate in train and test data
train_df, test_df = train_test_split(image_df, test_size=0.2, shuffle=True, random_state=42)
train_generator = ImageDataGenerator(
    preprocessing_function=tf.keras.applications.vgg19.preprocess_input,
    validation_split=0.2
)

test_generator = ImageDataGenerator(
    preprocessing_function=tf.keras.applications.vgg19.preprocess_input
)
# Split the data into three categories.
train_images = train_generator.flow_from_dataframe(
    dataframe=train_df,
    x_col='Filepath',
    y_col='Label',
    target_size=TARGET_SIZE,
    color_mode='rgb',
    class_mode='categorical',
    batch_size=BATCH_SIZE,
    shuffle=True,
    seed=42,
    subset='training'
)

val_images = train_generator.flow_from_dataframe(
    dataframe=train_df,
    x_col='Filepath',
    y_col='Label',
    target_size=TARGET_SIZE,
    color_mode='rgb',
    class_mode='categorical',
    batch_size=BATCH_SIZE,
    shuffle=True,
    seed=42,
    subset='validation'
)

test_images = test_generator.flow_from_dataframe(
    dataframe=test_df,
    x_col='Filepath',
    y_col='Label',
    target_size=TARGET_SIZE,
    color_mode='rgb',
    class_mode='categorical',
    batch_size=BATCH_SIZE,
    shuffle=False
)
# Data Augmentation Step
augment = tf.keras.Sequential([
  layers.experimental.preprocessing.Resizing(224,224),
  layers.experimental.preprocessing.Rescaling(1./255),
  layers.experimental.preprocessing.RandomFlip("horizontal"),
  layers.experimental.preprocessing.RandomRotation(0.1),
  layers.experimental.preprocessing.RandomZoom(0.1),
  layers.experimental.preprocessing.RandomContrast(0.1),
])
# Load the pretained model
pretrained_model = tf.keras.applications.vgg19.VGG19(
    input_shape=(224, 224, 3),
    include_top=False,
    weights='imagenet',
    pooling='max'
)

pretrained_model.trainable = False
# Create checkpoint callback
checkpoint_path = "corals_classification_model_checkpoint"
checkpoint_callback = ModelCheckpoint(checkpoint_path,
                                      save_weights_only=True,
                                      monitor="val_accuracy",
                                      save_best_only=True)

# Setup EarlyStopping callback to stop training if model's val_loss doesn't improve for 3 epochs
early_stopping = EarlyStopping(monitor = "val_loss", # watch the val loss metric
                               patience = 5,
                               restore_best_weights = True) # if val loss decreases for 3 epochs in a row, stop training

reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=1e-10)
inputs = pretrained_model.input
x = augment(inputs)

x = Dense(128, activation='relu')(pretrained_model.output)
x = BatchNormalization()(x)
x = Dropout(0.45)(x)
x = Dense(256, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(0.45)(x)


outputs = Dense(2, activation='softmax')(x)

model = Model(inputs=inputs, outputs=outputs)

model.compile(
    optimizer=Adam(0.001),
    loss='categorical_crossentropy',
    metrics=['accuracy']
)
import datetime

def create_tensorboard_callback(dir_name, experiment_name):
  log_dir = dir_name + "/" + experiment_name + "/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
  tensorboard_callback = tf.keras.callbacks.TensorBoard(
      log_dir=log_dir
  )
  print(f"Saving TensorBoard log files to: {log_dir}")
  return tensorboard_callback

history = model.fit(
    train_images,
    steps_per_epoch=len(train_images),
    validation_data=val_images,
    validation_steps=len(val_images),
    epochs=100,
    callbacks=[
        early_stopping,
        create_tensorboard_callback("training_logs", 
                                    "corals_classification"),
        checkpoint_callback,
        reduce_lr
    ]
)
results = model.evaluate(test_images, verbose=0)

print("    Test Loss: {:.5f}".format(results[0]))
print("Test Accuracy: {:.2f}%".format(results[1] * 100))
accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(accuracy))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

ax1.plot(epochs, accuracy, 'b', label='Training accuracy')
ax1.plot(epochs, val_accuracy, 'r', label='Validation accuracy')
ax1.set_title('Training and validation accuracy')
ax1.set_xlabel('Epochs')
ax1.set_ylabel('Accuracy')
ax1.legend()

ax2.plot(epochs, loss, 'b', label='Training loss')
ax2.plot(epochs, val_loss, 'r', label='Validation loss')
ax2.set_title('Training and validation loss')
ax2.set_xlabel('Epochs')
ax2.set_ylabel('Loss')
ax2.legend()

fig.suptitle('Training and validation metrics', fontsize=16)
plt.show()
# Predict the label of the test_images
pred = model.predict(test_images)
pred = np.argmax(pred,axis=1)
# Map the label
labels = (train_images.class_indices)
labels = dict((v,k) for k,v in labels.items())
pred = [labels[k] for k in pred]
y_test = list(test_df.Label)
print(classification_report(y_test, pred))
  # Display 25 random pictures from the dataset with their labels
random_index = np.random.randint(0, len(test_df) - 1, 15)
fig, axes = plt.subplots(nrows=3, ncols=5, figsize=(25, 15),
                        subplot_kw={'xticks': [], 'yticks': []})

for i, ax in enumerate(axes.flat):
    ax.imshow(plt.imread(test_df.Filepath.iloc[random_index[i]]))
    if test_df.Label.iloc[random_index[i]] == pred[random_index[i]]:
        color = "green"
    else:
        color = "red"
    ax.set_title(f"True: {test_df.Label.iloc[random_index[i]]}\nPredicted: {pred[random_index[i]]}", color=color)
plt.show()
plt.tight_layout()
相关推荐
鲸渔16 分钟前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
Csvn27 分钟前
让 AI 少返工:任务卡六要素与四维验收怎么写
人工智能
老纪的技术唠嗑局32 分钟前
新增项目知识库,网关也能帮 Agent 找回记忆|PowerContext v1.6.0 发布
人工智能
用户8425581308742 分钟前
插值选错,峰值就没了
人工智能
小宋102144 分钟前
embedding 返回全零向量,索引却照收不误:入库前的向量健康门禁、隔离重算与召回恢复判据
linux·服务器·网络·人工智能
2401_868534781 小时前
55 个热门网络面试问题及答案
网络·python
京东云开发者1 小时前
京东11.11大促系列|“懂经营”的AI全托管,为什么能从京东长出来?
人工智能
aifannihao1 小时前
ON CONFLICT 冲突后返回空:sqlite3 实测 get-or-create
数据库·python·postgresql·sqlite3·标准库
Fruiticecake1 小时前
机器人如何听声辨位:从唤醒词(KWS)与 VAD 到 DOA 声源定位,以及 ALSA XRUN 避坑
人工智能