Resnet-50解决皮肤癌检测

1.导入必要的库

#Import some necessary Modules
import os
import cv2
import keras
import numpy as np
import pandas as pd
import random as rn
from PIL import Image
from tqdm import tqdm
import matplotlib.pyplot as plt
from IPython.display import SVG
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder

from tensorflow.python.keras import backend as K
from tensorflow.python.keras.optimizers import Adam
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.utils import to_categorical
from tensorflow.python.keras.callbacks import ReduceLROnPlateau
from tensorflow.python.keras.utils.vis_utils import model_to_dot
from tensorflow.python.keras.applications.vgg16 import VGG16
from tensorflow.python.keras.applications.resnet50 import ResNet50,preprocess_input
from sklearn.model_selection import train_test_split,KFold, cross_val_score, GridSearchCV
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator,load_img, img_to_array
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D,BatchNormalization,Dropout,Conv2D,MaxPool2D

#Resnet-50 has been pre_trained, weights have been saved in below path
resnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
vgg16_weights_path="../input/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5"

#Display the dir list
print(os.listdir("../input"))

2.输出结果:
Using TensorFlow backend.
['skin-cancer-malignant-vs-benign', 'vgg16', 'resnet50']

将JPG文件转化为数组

def Dataset_loader(DIR,RESIZE):
    IMG = []
    read = lambda imname: np.asarray(Image.open(imname).convert("RGB"))
    for IMAGE_NAME in tqdm(os.listdir(DIR)):
        PATH = os.path.join(DIR,IMAGE_NAME)
        _, ftype = os.path.splitext(PATH)
        if ftype == ".jpg":
            img = read(PATH)
            img = cv2.resize(img, (RESIZE,RESIZE))
            IMG.append(np.array(img)/255.)
    return IMG
benign_train = np.array(Dataset_loader('../input/skin-cancer-malignant-vs-benign/data/train/benign',224))
malign_train = np.array(Dataset_loader('../input/skin-cancer-malignant-vs-benign/data/train/malignant',224))
benign_test = np.array(Dataset_loader('../input/skin-cancer-malignant-vs-benign/data/test/benign',224))
malign_test = np.array(Dataset_loader('../input/skin-cancer-malignant-vs-benign/data/test/malignant',224))

输出结果:
100%|██████████| 1440/1440 [00:07<00:00, 202.51it/s]
100%|██████████| 1197/1197 [00:05<00:00, 228.46it/s]
100%|██████████| 360/360 [00:01<00:00, 202.07it/s]
100%|██████████| 300/300 [00:01<00:00, 226.01it/s]

3.数据预处理

# Create labels
# Merge data 
# Shuffle train data
# Split validation data from train data
# Shuffle test data

4.预览前12张图片

# Display first 15 images of moles, and how they are classified
w=60
h=40
fig=plt.figure(figsize=(15, 15))
columns = 4
rows = 3
for i in range(1, columns*rows +1):
    ax = fig.add_subplot(rows, columns, i)
    if Y_train[i] == 0:
        ax.title.set_text('Benign')
    else:
        ax.title.set_text('Malignant')
    plt.imshow(x_train[i], interpolation='nearest')
plt.show()
image.png

5.数据增强

# Data auguments
datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0

6.定义模型

# Define model with different applications
model = Sequential()
model.add(ResNet50(include_top=False,input_tensor=None,input_shape=(224,224,3),pooling='avg',classes=2,weights=resnet_weights_path))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
……
model.add(BatchNormalization())
model.add(Dense(1, activation='sigmoid'))

model.layers[0].trainable = False
model.summary()

输出结果:


Layer (type) Output Shape Param #

resnet50 (Model) (None, 2048) 23587712


flatten (Flatten) (None, 2048) 0


dense (Dense) (None, 512) 1049088


dropout (Dropout) (None, 512) 0


batch_normalization_v1 (Batc (None, 512) 2048


dense_1 (Dense) (None, 256) 131328


dropout_1 (Dropout) (None, 256) 0


batch_normalization_v1_1 (Ba (None, 256) 1024


dense_2 (Dense) (None, 1) 257

Total params: 24,771,457
Trainable params: 1,182,209
Non-trainable params: 23,589,248


7.编译模型

# Compile model
model.compile()

8.学习率衰减

#Learning rate decay with ReduceLROnPlateau
red_lr= 

9.训练模型

# Train model
batch_size=64
epochs=150
History = model.fit_generator( )

输出结果:
……
Epoch 00146: ReduceLROnPlateau reducing learning rate to 9.095435737904722e-10.
26/26 [==============================] - 18s 686ms/step - loss: 0.1139 - acc: 0.9566 - val_loss: 0.2779 - val_acc: 0.8890
Epoch 147/150
1000/1000 [==============================] - 3s 3ms/sample - loss: 0.2764 - acc: 0.8890
26/26 [==============================] - 18s 687ms/step - loss: 0.1370 - acc: 0.9469 - val_loss: 0.2784 - val_acc: 0.8890
Epoch 148/150
1000/1000 [==============================] - 3s 3ms/sample - loss: 0.2761 - acc: 0.8890
26/26 [==============================] - 18s 704ms/step - loss: 0.1363 - acc: 0.9469 - val_loss: 0.2782 - val_acc: 0.8890
Epoch 149/150
1000/1000 [==============================] - 3s 3ms/sample - loss: 0.2760 - acc: 0.8890

Epoch 00149: ReduceLROnPlateau reducing learning rate to 6.366804861102082e-10.
26/26 [==============================] - 18s 693ms/step - loss: 0.1273 - acc: 0.9462 - val_loss: 0.2780 - val_acc: 0.8890
Epoch 150/150
1000/1000 [==============================] - 3s 3ms/sample - loss: 0.2754 - acc: 0.8900
26/26 [==============================] - 18s 689ms/step - loss: 0.1414 - acc: 0.9462 - val_loss: 0.2774 - val_acc: 0.8900

10.测试模型

# Testing model on test data to evaluate
lists=[]
y_pred = model.predict(X_test)
for i in range(len(y_pred)):
    if y_pred[i][0]>0.5:
        lists.append(1)
    else:
        lists.append(0)

print(accuracy_score(Y_test, lists))

输出结果:
0.8787878787878788

11.画图

plt.plot(History.history['acc'])
plt.plot(History.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.legend(['train', 'test'])
plt.show()

输出结果:


image.png

12.显示前8个良性图片

 # Display first 8 images of benign
w=60
h=40
fig=plt.figure(figsize=(18, 10))
columns = 4
rows = 2

def Transfername(namecode):
    if namecode==0:
        return "Benign"
    else:
        return "Malignant"

for i in range(len(prop_class)):
    ax = fig.add_subplot(rows, columns, i+1)
    ax.set_title("Predicted result:"+ Transfername(lists[prop_class[i]])
                       +"\n"+"Actual result: "+ Transfername(Y_test[prop_class[i]]))
    plt.imshow(X_test[prop_class[i]], interpolation='nearest')
plt.show()

输出结果:


image.png

13.显示前8个恶性图片

 # Display first 8 images of benign
w=60
h=40
fig=plt.figure(figsize=(18, 10))
columns = 4
rows = 2
for i in range(len(mis_class)):
    ax = fig.add_subplot(rows, columns, i+1)
    ax.set_title("Predicted result:"+ Transfername(lists[mis_class[i]])
                   +"\n"+"  Actual result: "+ Transfername(Y_test[mis_class[i]]))
    plt.imshow(X_test[mis_class[i]], interpolation='nearest')
plt.show()</pre>

输出结果:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,098评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,213评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,960评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,519评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,512评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,533评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,914评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,804评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,563评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,644评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,350评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,933评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,908评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,146评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,847评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,361评论 2 342

推荐阅读更多精彩内容