基于 MobileNetV2 脑肿瘤图片识别 项目详解
目录
项目介绍:
设置GPU
导入数据:
数据预处理:
数据可视化:
构建模型:
训练模型:
混淆矩阵:
指标评估:
AUC 评价:
项目介绍:
脑肿瘤亦称颅内肿瘤,在占位性病变中占据重要地位。就我国儿童恶性病变而言,在发病率上仅次于白血病排名第二。据调查数据显示:我国每年新增脑瘤患儿数量约为7000至8000名患者当中约70%至80%的病例呈现恶性特征。因儿童患者的平均发病年龄较小且病情发展迅速,在诊断时往往已处于晚期阶段因此早期发现对于改善预后至关重要其重要性体现在早期干预能够显著提升患者的生存率及生活质量。
这次我们一共收集了253张 brain imaging data, 其中当中患有 brain tumors 的病人有 155 张, 健康个体共有 98 例. 所采用的算法是 MobileNetV2, 经过该算法处理后得到识别准确率为 90.0%, 同时其 AUC 值达到了 0.869.
在本次研究中,我们计划引入AUC作为评价指标来评估脑肿瘤识别的效果。其中,AUC值代表ROC曲线下所包围区域的面积度量,可作为衡量二分类预测模型性能的重要指标。
设置GPU
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPU
tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
tf.config.set_visible_devices([gpu0],"GPU")
import matplotlib.pyplot as plt
import os,PIL,pathlib
import numpy as np
import pandas as pd
import warnings
from tensorflow import keras
warnings.filterwarnings("ignore") #忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
代码解读
导入数据:
import pathlib
data_dir = "./35-day-brain_tumor_dataset"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)
batch_size = 16
img_height = 224
img_width = 224
代码解读
"""
关于image_dataset_from_directory()的详细介绍可以参考文章:
"""
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=12,
image_size=(img_height, img_width),
batch_size=batch_size)
代码解读
"""
关于image_dataset_from_directory()的详细介绍可以参考文章:
"""
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=12,
image_size=(img_height, img_width),
batch_size=batch_size)
代码解读
class_names = train_ds.class_names
print(class_names)
代码解读
['no', 'yes']
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
代码解读
(16, 224, 224, 3)
(16,)
数据预处理:
AUTOTUNE = tf.data.AUTOTUNE
def train_preprocessing(image,label):
return (image/255.0,label)
train_ds = (
train_ds.cache()
.shuffle(1000)
.map(train_preprocessing) # 这里可以设置预处理函数
# .batch(batch_size) # 在image_dataset_from_directory处已经设置了batch_size
.prefetch(buffer_size=AUTOTUNE)
)
val_ds = (
val_ds.cache()
.shuffle(1000)
.map(train_preprocessing) # 这里可以设置预处理函数
# .batch(batch_size) # 在image_dataset_from_directory处已经设置了batch_size
.prefetch(buffer_size=AUTOTUNE)
)
代码解读
shuffle() : 随机打乱顺序 ,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456
prefetch() : 提前加载数据 ,加速运行过程,并且在前面两篇论文中都有详细说明。
cache() : 将数据集存储到内存中 ,以加快运行速度。
数据可视化:
plt.figure(figsize=(10, 8)) # 图形的宽为10高为5
plt.suptitle("公众号(K同学啊)回复:DL+35,获取数据")
class_names = ["脑肿瘤患者","正常人"]
for images, labels in train_ds.take(1):
for i in range(15):
plt.subplot(4, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
# 显示图片
plt.imshow(images[i])
# 显示标签
plt.xlabel(class_names[labels[i]-1])
plt.show()
代码解读

构建模型:
from tensorflow.keras import layers, models, Input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout,BatchNormalization,Activation
# 加载预训练模型
base_model = tf.keras.applications.mobilenet_v2.MobileNetV2(weights='imagenet',
include_top=False,
input_shape=(img_width,img_height,3),
pooling='max')
for layer in base_model.layers:
layer.trainable = True
X = base_model.output
"""
注意到原模型(MobileNetV2)会发生过拟合现象,这里加上一个Dropout层
加上后,过拟合现象得到了明显的改善。
大家可以试着通过调整代码,观察一下注释Dropout层与不注释之间的差别
"""
X = Dropout(0.4)(X)
output = Dense(len(class_names), activation='softmax')(X)
model = Model(inputs=base_model.input, outputs=output)
# model.summary()
model.compile(optimizer="adam",
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
代码解读
训练模型:
from tensorflow.keras.callbacks import ModelCheckpoint, Callback, EarlyStopping, ReduceLROnPlateau, LearningRateScheduler
NO_EPOCHS = 50
PATIENCE = 10
VERBOSE = 1
# 设置动态学习率
annealer = LearningRateScheduler(lambda x: 1e-3 * 0.99 ** (x+NO_EPOCHS))
# 设置早停
earlystopper = EarlyStopping(monitor='val_acc', patience=PATIENCE, verbose=VERBOSE)
#
checkpointer = ModelCheckpoint('best_model.h5',
monitor='val_accuracy',
verbose=VERBOSE
save_best_only=True,
save_weights_only=True)
代码解读
train_model = model.fit(train_ds,
epochs=NO_EPOCHS,
verbose=1,
validation_data=val_ds,
callbacks=[earlystopper, checkpointer, annealer])
代码解读
当前轮次为第1轮(共50轮)
完成全部样本的训练进度
耗时:每一步的平均时间为7秒(约)
损失值为3.1(损失函数值),准确率为67%
注意:早停条件基于不可用的val_acc指标
......
Epoch 49/50
13/13 [==============================] - 1s 60ms/step - loss: 3.0536e-08 - accuracy: 1.0000 - val_loss: 2.6647 - val_accuracy: 0.8800
WARNING:tensorflow:Early stopping conditioned on metric val_acc which is not available. Available metrics are: loss,accuracy,val_loss,val_accuracy
Epoch 00049: val_accuracy did not improve from 0.90000
Epoch 50/50
13/13 [==============================] - 1s 60ms/step - loss: 1.4094e-08 - accuracy: 1.0000 - val_loss: 2.6689 - val_accuracy: 0.8800
WARNING:tensorflow:Early stopping conditioned on metric val_acc which is not available. Available metrics are: loss,accuracy,val_loss,val_accuracy
Epoch 00050: val_accuracy did not improve from 0.90000
混淆矩阵:
from sklearn.metrics import confusion_matrix
import seaborn as sns
import pandas as pd
# 定义一个绘制混淆矩阵图的函数
def plot_cm(labels, predictions):
# 生成混淆矩阵
conf_numpy = confusion_matrix(labels, predictions)
# 将矩阵转化为 DataFrame
conf_df = pd.DataFrame(conf_numpy, index=class_names ,columns=class_names)
plt.figure(figsize=(8,7))
sns.heatmap(conf_df, annot=True, fmt="d", cmap="BuPu")
plt.title('混淆矩阵',fontsize=15)
plt.ylabel('真实值',fontsize=14)
plt.xlabel('预测值',fontsize=14)
代码解读
val_pre = []
val_label = []
for images, labels in val_ds:#这里可以取部分验证数据(.take(1))生成混淆矩阵
for image, label in zip(images, labels):
# 需要给图片增加一个维度
img_array = tf.expand_dims(image, 0)
# 使用模型预测图片中的人物
prediction = model.predict(img_array)
val_pre.append(class_names[np.argmax(prediction)])
val_label.append(class_names[label])
plot_cm(val_label, val_pre)
代码解读

指标评估:
from sklearn import metrics
def test_accuracy_report(model):
print(metrics.classification_report(val_label, val_pre, target_names=class_names))
score = model.evaluate(val_ds, verbose=0)
print('Loss function: %s, accuracy:' % score[0], score[1])
test_accuracy_report(model)
代码解读
precision recall f1-score support
脑肿瘤患者 0.94 0.89 0.92 37
正常人 0.73 0.85 0.79 13
accuracy 0.88 50
macro avg 0.84 0.87 0.85 50
weighted avg 0.89 0.88 0.88 50
Loss function: 2.668877601623535, accuracy: 0.8799999952316284
代码解读
AUC 评价:
AUC(Area under the Curve of ROC)是指ROC曲线下方区域所对应的数值,在评价二分类预测模型性能时起到关键作用。
AUC = 1:是完美分类器,绝大多数预测的场合,不存在完美分类器。
0.5 < AUC < 1:优于随机猜测。
AUC = 0.5:跟随机猜测一样(例:丢硬币),模型没有预测价值。
AUC < 0.5:比随机猜测还差。
ROC曲线的横坐标是伪阳性率(也叫假正类率,False Positive Rate),纵坐标是真阳性率(真正类率,True Positive Rate),相应的还有真阴性率(真负类率,True Negative Rate)和伪阴性率(假负类率,False Negative Rate)。这四类的计算方法如下:
伪阳性率(FPR):指真实结果为阴性但被模型误判为阳性的比例。
真阳性率(TPR):即灵敏度(Sensitivity),表示真实结果阳性和模型预测一致的概率。
伪阴性率(FNR):指真实结果呈阳性但模型误判其为阴性的比例。
真阴性率(TNR):即特异性(Specificity),表示真实结果和预测结果均为负的概率。
val_pre = []
val_label = []
for images, labels in val_ds:#这里可以取部分验证数据(.take(1))生成混淆矩阵
for image, label in zip(images, labels):
# 需要给图片增加一个维度
img_array = tf.expand_dims(image, 0)
# 使用模型预测图片中的人物
prediction = model.predict(img_array)
val_pre.append(np.argmax(prediction))
val_label.append(label)
train_pre = []
train_label = []
for images, labels in train_ds:#这里可以取部分验证数据(.take(1))生成混淆矩阵
for image, label in zip(images, labels):
# 需要给图片增加一个维度
img_array = tf.expand_dims(image, 0)
# 使用模型预测图片中的人物
prediction = model.predict(img_array)
train_pre.append(np.argmax(prediction))
train_label.append(label)
代码解读
sklearn.metrics.roc_curve():用于绘制ROC曲线
主要参数:
y_true:真实的目标标签,默认取值范围是{0, 1}或{-1, 1}。若需设置其他取值范围,则应明确指定pos_label参数的具体数值。例如将目标标签设定为{1, 2}(其中2代表正类),则pos_label应设为2。
y_score:对每个样本进行预测的结果。
pos_label:指定正类的目标标签编号。
返回值:
fpr:False positive rate。
tpr:True positive rate。
thresholds
def plot_roc(name, labels, predictions, **kwargs):
fp, tp, _ = metrics.roc_curve(labels, predictions)
plt.plot(fp, tp, label=name, linewidth=2, **kwargs)
plt.plot([0, 1], [0, 1], color='gray', linestyle='--')
plt.xlabel('False positives rate')
plt.ylabel('True positives rate')
ax = plt.gca()
ax.set_aspect('equal')
plot_roc("Train Baseline", train_label, train_pre, color="green", linestyle=':')
plot_roc("val Baseline", val_label, val_pre, color="red", linestyle='--')
plt.legend(loc='lower right')
代码解读

auc_score = metrics.roc_auc_score(val_label, val_pre)
print("AUC值为:",auc_score)
代码解读
AUC值为: 0.869022869022869
