65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ResNet50 迁移学习进行 COVID-19 诊断:从头开始构建 DL 网络

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2021 年 2 月 22 日

CPOL

4分钟阅读

viewsIcon

8529

downloadIcon

124

在本文中,我们将向您展示如何从头开始构建一个用于 Covid-19 检测的网络。

在本系列文章中,我们将应用一个深度学习(DL)网络ResNet50,用于诊断胸部X光图像中的Covid-19。我们将使用Python的TensorFlow库在Jupyter Notebook上训练神经网络。

您需要用于此项目的工具和库是

IDE

我们假设您熟悉使用 Python 和 Jupyter Notebook 进行深度学习。如果您是 Python 新手,请从本教程开始。如果您还不熟悉 Jupyter,请从这里开始

在本系列的前几篇文章中,我们使用了基于迁移学习的方法来微调现有的 ResNet50 模型以诊断 COVID-19。在本文中,我们将向您展示如何从头开始构建一个网络,然后对其进行训练,以将胸部 X 射线图像分类为 COVID-19 和正常。

安装库并加载数据集

我们将仅使用 TensorFlow、Keras 和 OS,以及一些基本的附加库来构建我们的 COVID-19 诊断网络。

# Import required libraries
import tensorflow as tf
from keras import optimizers
import os, shutil
import matplotlib.pyplot as plt

首先,让我们加载将用于训练和测试网络的the data。在这种情况下,我们将使用一种不同于用于基于迁移学习的网络the loading technique。尽管如此,我们仍将使用the same dataset。

base_dir = r'C:\Users\abdul\Desktop\ContentLab\P1\archive\COVID-19 Radiography Database’
train_dir = os.path.join(base_dir, 'train')
test_dir = os.path.join(base_dir, 'test')
train_COV19_dir = os.path.join(train_dir, 'COV19')
train_Normal_dir = os.path.join(train_dir, 'Normal')
test_VOV19_dir = os.path.join(test_dir, 'COV19')
test_Normal_dir = os.path.join(test_dir, 'Normal')

现在,让我们打印我们训练集和测试集中的 COVID-19 和正常图像的数量。

print('total training COV19 images:', len(os.listdir(train_COV19_dir)))
print('total training Normal images:', len(os.listdir(train_Normal_dir)))

print('total test COV19 images:', len(os.listdir(test_VOV19_dir)))
print('total test Normal images:', len(os.listdir(test_Normal_dir)))

输出将如下所示

预处理数据

在将数据输入网络之前,必须对图像进行预处理。对于我们将要构建的网络,我们将选择输入格式为 128x128x3。所有图像都将被缩放到此大小,这相对较小 — 计算成本更低。现在需要为 ImageDataGenerator 设置批次大小和类别模式。

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_dir, target_size=(128, 128), batch_size=5, class_mode='categorical')
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(128, 128), batch_size=5, class_mode='categorical')

为了检查数据和标签的批次形状,我们将使用

for data_batch, labels_batch in train_generator:
    print('data batch shape:', data_batch.shape)
    print('labels batch shape:', labels_batch.shape)
    break

请注意,顺序模型需要 4 维输入(批次大小、X、Y、通道)。这就是为什么在构建网络之前必须设置批次;否则,将发生错误。

构建深度学习网络

Keras 模型使用顺序类来创建层。这是一个函数式模型类,表示层的堆叠。它可以轻松地从 Keras 导入。

对于我们的模型,我们将使用两个卷积层、两个最大池化层、三个 ReLU 层、一个展平层和两个密集层(全连接)。我们需要从 Keras 模型导入所有必需的层,例如 Conv2DMaxPoolingDense

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras import backend as k
input_shape=(128, 128, 3)
model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),
                 activation='relu',
                 input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.summary()

如上所示,卷积层使用 Conv2D 函数调用,该函数有三个主要参数

  • Filters(滤波器):设置在卷积层中生成的滤波器数量
  • Kernel size(卷积核大小):卷积中使用的滤波器或卷积核的大小(必须是奇数)
  • Strides(步幅):一个整数元组,定义卷积沿输入图像的 X 和 Y 轴的移动方式

池化层也定义了 stride(遍历所有图像)和 pool _size,即用于对输入图像应用池化的池化滤波器或卷积核的大小。

最后,我们可以可视化我们的网络

model.summary()

训练网络

为了训练我们新构建的网络,我们需要指定损失函数和优化器。对于此网络,我们将使用二元交叉熵,因为我们的目标是将胸部 X 射线分类为两个类别:Covid-19 和正常。我们将使用随机梯度下降作为优化器。

在优化函数中,我们需要设置学习率。这是一个重要参数。如果设置得太低,学习过程可能会更长,因为权重会遇到小的更新。相反,如果设置得太高,网络可能会过拟合。最好在设置较低的学习率值开始训练我们的网络,然后通过监控网络性能逐渐增加它。

在此,我们选择学习率为 0.001。

from keras import optimizers
model.compile(loss='categorical_crossentropy',
optimizer=optimizers.adam(lr=1e-4),
metrics=['acc'])

然后,我们可以用 10 个 epoch 开始训练(图 11)

history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=10)

图 11:训练过程快照

然后可以使用以下命令绘制训练期间的网络准确率和损失

acc = history.history['acc']
loss = history.history['loss']
plt.figure()
plt.plot(acc, label='Training Accuracy')
plt.ylabel('Accuracy')
plt.title('Training Accuracy')
plt.figure()
plt.plot(loss, label='Training Loss')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.xlabel('epoch')
plt.show()

图 12:准确率与 epoch 数

评估网络

如前一篇文章所述,可以对新的、未见过的新冠肺炎和正常类图像测试模型的准确率。在本节中,我们在 895 张新冠肺炎和正常胸部 X 射线图像上测试了网络。我们使用了与在先前预训练网络测试中使用的相同的测试命令“model.evaluate”。如图 10 所示,该网络在测试中达到了 98.8% 的准确率(图 13)。

Testresults = model.evaluate(test_generator)
print("test loss, test acc:", Testresults)

图 13:测试准确率快照

下一步?

我们已经到达了本系列的结尾。我们已经实现了我们的既定目标,即将胸部 X 射线图像分类为 COVID-19 或正常。我们采用的模型在诊断 COVID-19 方面表现良好,因为它们在基于迁移学习的模型和新构建的模型上的测试准确率分别达到了 95% 和 98.8%。

尽管我们的 COVID-19 分类器效果很好,但仍有改进的空间。一个关键的补充是进行额外的训练,以帮助网络更好地区分 COVID-19 与其他胸部疾病,如病毒性肺炎、细菌性肺炎、肿块等。

使用 ResNet50 迁移学习进行 COVID-19 诊断:从头开始构建深度学习网络 - CodeProject - 代码之家
© . All rights reserved.