-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathtrain_cnn.py
162 lines (150 loc) · 7.17 KB
/
train_cnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Reshape
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras import regularizers
from keras.losses import mean_squared_error
import glob
import matplotlib.patches as patches
import json
import numpy as np
from matplotlib.path import Path
import dicom
import cv2
from utils import *
def create_model(activation, input_shape=(64, 64)):
"""
Simple convnet model : one convolution, one average pooling and one fully connected layer
:param activation: None if nothing passed, e.g : ReLu, tanh, etc.
:return: Keras model
"""
model = Sequential()
model.add(Conv2D(100, (11,11), activation=activation, padding='valid', strides=(1, 1), input_shape=(input_shape[0], input_shape[1], 1)))
model.add(AveragePooling2D((6,6)))
model.add(Reshape([-1, 8100]))
model.add(Dense(1024, activation='sigmoid', kernel_regularizer=regularizers.l2(0.0001)))
model.add(Reshape([-1, 32, 32]))
return model
def create_model_maxpooling(activation, input_shape=(64, 64)):
"""
Simple convnet model with max pooling: one convolution, one max pooling and one fully connected layer
:param activation: None if nothing passed, e.g : ReLu, tanh, etc.
:return: Keras model
"""
model = Sequential()
model.add(Conv2D(100, (11,11), activation=activation, padding='valid', strides=(1, 1), input_shape=(input_shape[0], input_shape[1], 1)))
model.add(MaxPooling2D((6,6)))
model.add(Reshape([-1, 8100]))
model.add(Dense(1024, activation='sigmoid', kernel_regularizer=regularizers.l2(0.0001)))
model.add(Reshape([-1, 32, 32]))
return model
def create_model_larger(activation, input_shape=(64, 64)):
"""
Larger (more filters) convnet model : one convolution, one average pooling and one fully connected layer:
:param activation: None if nothing passed, e.g : ReLu, tanh, etc.
:return: Keras model
"""
model = Sequential()
model.add(Conv2D(200, (11,11), activation=activation, padding='valid', strides=(1, 1), input_shape=(input_shape[0], input_shape[1], 1)))
model.add(AveragePooling2D((6,6)))
model.add(Reshape([-1, 16200]))
model.add(Dense(1024, activation='sigmoid', kernel_regularizer=regularizers.l2(0.0001)))
model.add(Reshape([-1, 32, 32]))
return model
def create_model_deeper(activation, input_shape=(64, 64)):
"""
Deeper convnet model : two convolutions, two average pooling and one fully connected layer:
:param activation: None if nothing passed, e.g : ReLu, tanh, etc.
:return: Keras model
"""
model = Sequential()
model.add(Conv2D(64, (11,11), activation=activation, padding='valid', strides=(1, 1), input_shape=(input_shape[0], input_shape[1], 1)))
model.add(AveragePooling2D((2,2)))
model.add(Conv2D(128, (10, 10), activation=activation, padding='valid', strides=(1, 1)))
model.add(AveragePooling2D((2,2)))
model.add(Reshape([-1, 128*9*9]))
model.add(Dense(1024, activation='sigmoid', kernel_regularizer=regularizers.l2(0.0001)))
model.add(Reshape([-1, 32, 32]))
return model
def create_model_full(activation, input_shape=(64, 64)):
model = Sequential()
model.add(Conv2D(64, (11,11), activation=activation, padding='valid', strides=(1, 1), input_shape=(input_shape[0], input_shape[1], 1)))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(128, (10, 10), activation=activation, padding='valid', strides=(1, 1)))
model.add(MaxPooling2D((2,2)))
model.add(Reshape([-1, 128*9*9]))
model.add(Dense(1024, activation='sigmoid', kernel_regularizer=regularizers.l2(0.0001)))
model.add(Reshape([-1, 32, 32]))
return model
def training(m, X, Y, verbose, batch_size=16, epochs=20, data_augm=False):
"""
Training CNN with the possibility to use data augmentation
:param m: Keras model
:param epochs: number of epochs
:param X: training pictures
:param Y: training binary ROI mask
:return: history
"""
if data_augm:
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=50, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False)
datagen.fit(X)
history = m.fit_generator(datagen.flow(X, Y,
batch_size=batch_size),
steps_per_epoch=X.shape[0] // batch_size,
epochs=epochs,
verbose=verbose)
else:
history = m.fit(X, Y, batch_size=batch_size, epochs=epochs, verbose=verbose)
return history, m
def run(model='simple', X_to_pred=None, history=False, verbose=0, activation=None, epochs=20, data_augm=False):
"""
Full pipeline for CNN: load the dataset, train the model and predict ROIs
:param model: choice between different models e.g simple, larger, deeper, maxpooling
:param activation: None if nothing passed, e.g : ReLu, tanh, etc.
:param epochs: number of epochs
:param X_to_pred: input for predictions after training (X_train if not specified)
:param verbose: int for verbose
:return: X, X_fullsize, Y, y_pred, h (if history boolean passed)
"""
X, X_fullsize, Y, contour_mask = create_dataset()
if model == 'simple':
m = create_model(activation=activation)
elif model == 'larger':
m = create_model_larger(activation=activation)
elif model == 'deeper':
m = create_model_deeper(activation=activation)
elif model == 'maxpooling':
m = create_model_maxpooling(activation=activation)
elif model =='full':
m = create_model_full(activation=activation)
m.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['accuracy'])
if verbose > 0:
print('Size for each layer :\nLayer, Input Size, Output Size')
for p in m.layers:
print(p.name.title(), p.input_shape, p.output_shape)
h, m = training(m, X, Y, verbose=verbose, batch_size=16, epochs=epochs, data_augm=data_augm)
if not X_to_pred:
X_to_pred = X
y_pred = m.predict(X_to_pred, batch_size=16)
if history:
return X, X_fullsize, Y, contour_mask, y_pred, h, m
else:
return X, X_fullsize, Y, contour_mask, y_pred, m
def inference(model):
X_test, X_fullsize_test, Y_test, contour_mask_test = create_dataset(n_set='test')
y_pred = model.predict(X_test, batch_size=16)
return X_test, X_fullsize_test, Y_test, contour_mask_test, y_pred