|
a |
|
b/Notebooks/Training the R-CNN.ipynb |
|
|
1 |
{ |
|
|
2 |
"nbformat": 4, |
|
|
3 |
"nbformat_minor": 0, |
|
|
4 |
"metadata": { |
|
|
5 |
"kernelspec": { |
|
|
6 |
"display_name": "Python [conda env:work] *", |
|
|
7 |
"language": "python", |
|
|
8 |
"name": "conda-env-work-py" |
|
|
9 |
}, |
|
|
10 |
"language_info": { |
|
|
11 |
"codemirror_mode": { |
|
|
12 |
"name": "ipython", |
|
|
13 |
"version": 3 |
|
|
14 |
}, |
|
|
15 |
"file_extension": ".py", |
|
|
16 |
"mimetype": "text/x-python", |
|
|
17 |
"name": "python", |
|
|
18 |
"nbconvert_exporter": "python", |
|
|
19 |
"pygments_lexer": "ipython3", |
|
|
20 |
"version": "3.7.3" |
|
|
21 |
}, |
|
|
22 |
"colab": { |
|
|
23 |
"name": "Training the R-CNN.ipynb", |
|
|
24 |
"provenance": [], |
|
|
25 |
"collapsed_sections": [] |
|
|
26 |
} |
|
|
27 |
}, |
|
|
28 |
"cells": [ |
|
|
29 |
{ |
|
|
30 |
"cell_type": "markdown", |
|
|
31 |
"metadata": { |
|
|
32 |
"id": "WemaJ8K34tFi", |
|
|
33 |
"colab_type": "text" |
|
|
34 |
}, |
|
|
35 |
"source": [ |
|
|
36 |
"# **Importing Dependencies**" |
|
|
37 |
] |
|
|
38 |
}, |
|
|
39 |
{ |
|
|
40 |
"cell_type": "code", |
|
|
41 |
"metadata": { |
|
|
42 |
"id": "xZM4YQYP2I_0", |
|
|
43 |
"colab_type": "code", |
|
|
44 |
"colab": {} |
|
|
45 |
}, |
|
|
46 |
"source": [ |
|
|
47 |
"import pickle\n", |
|
|
48 |
"import numpy as np\n", |
|
|
49 |
"import matplotlib.pyplot as plt\n", |
|
|
50 |
"\n", |
|
|
51 |
"import tensorflow as tf\n", |
|
|
52 |
"\n", |
|
|
53 |
"from tensorflow.keras import Sequential\n", |
|
|
54 |
"from tensorflow.keras.layers import LSTM, Bidirectional, TimeDistributed, Dense, Dropout, BatchNormalization, Activation\n", |
|
|
55 |
"from tensorflow.keras.optimizers import Adam\n", |
|
|
56 |
"from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n", |
|
|
57 |
"\n", |
|
|
58 |
"from tensorflow.python.client import device_lib\n", |
|
|
59 |
"from tensorflow.compat.v1 import ConfigProto\n", |
|
|
60 |
"from tensorflow.compat.v1 import InteractiveSession" |
|
|
61 |
], |
|
|
62 |
"execution_count": 0, |
|
|
63 |
"outputs": [] |
|
|
64 |
}, |
|
|
65 |
{ |
|
|
66 |
"cell_type": "markdown", |
|
|
67 |
"metadata": { |
|
|
68 |
"id": "AgpkgeGMxBXl", |
|
|
69 |
"colab_type": "text" |
|
|
70 |
}, |
|
|
71 |
"source": [ |
|
|
72 |
"# **Allowing for Parallelized Model Training**\n", |
|
|
73 |
"By default, TensorFlow allocates all available GPU memory to the current training process. By enabling memory growth, however, we can train multiple models in parallel." |
|
|
74 |
] |
|
|
75 |
}, |
|
|
76 |
{ |
|
|
77 |
"cell_type": "code", |
|
|
78 |
"metadata": { |
|
|
79 |
"id": "emimSYUx2JAK", |
|
|
80 |
"colab_type": "code", |
|
|
81 |
"colab": {} |
|
|
82 |
}, |
|
|
83 |
"source": [ |
|
|
84 |
"gpus = tf.config.experimental.list_physical_devices(\"GPU\")\n", |
|
|
85 |
"\n", |
|
|
86 |
"if gpus:\n", |
|
|
87 |
" try:\n", |
|
|
88 |
" for gpu in gpus:\n", |
|
|
89 |
" tf.config.experimental.set_memory_growth(gpu, True)\n", |
|
|
90 |
" except RuntimeError as e:\n", |
|
|
91 |
" print(e)\n", |
|
|
92 |
"\n", |
|
|
93 |
"config = ConfigProto()\n", |
|
|
94 |
"config.gpu_options.allow_growth = True\n", |
|
|
95 |
"session = InteractiveSession(config=config)" |
|
|
96 |
], |
|
|
97 |
"execution_count": 0, |
|
|
98 |
"outputs": [] |
|
|
99 |
}, |
|
|
100 |
{ |
|
|
101 |
"cell_type": "markdown", |
|
|
102 |
"metadata": { |
|
|
103 |
"id": "sh7VEM-qsYk3", |
|
|
104 |
"colab_type": "text" |
|
|
105 |
}, |
|
|
106 |
"source": [ |
|
|
107 |
"# **Loading Data & Labels**\n", |
|
|
108 |
"Here, we load the features previously extracted by the CNN and their corresponding labels." |
|
|
109 |
] |
|
|
110 |
}, |
|
|
111 |
{ |
|
|
112 |
"cell_type": "code", |
|
|
113 |
"metadata": { |
|
|
114 |
"id": "f_N4BDsb2JAO", |
|
|
115 |
"colab_type": "code", |
|
|
116 |
"colab": {} |
|
|
117 |
}, |
|
|
118 |
"source": [ |
|
|
119 |
"data_array = np.load(\"rcnn-data-array.npy\")\n", |
|
|
120 |
"label_array = np.load(\"rcnn-label-array.npy\")\n", |
|
|
121 |
"\n", |
|
|
122 |
"# Add a dummy dimension for label_array to be fed to our R-CNN\n", |
|
|
123 |
"label_array = np.expand_dims(label_array, axis=2)" |
|
|
124 |
], |
|
|
125 |
"execution_count": 0, |
|
|
126 |
"outputs": [] |
|
|
127 |
}, |
|
|
128 |
{ |
|
|
129 |
"cell_type": "code", |
|
|
130 |
"metadata": { |
|
|
131 |
"id": "W9hHmPG22JAd", |
|
|
132 |
"colab_type": "code", |
|
|
133 |
"colab": {}, |
|
|
134 |
"outputId": "c07217cd-f344-45c8-8764-5b47ca989cc6" |
|
|
135 |
}, |
|
|
136 |
"source": [ |
|
|
137 |
"# We check the percentage of hemorrhages present in the data: It is ~19%.\n", |
|
|
138 |
"np.average(label_array)" |
|
|
139 |
], |
|
|
140 |
"execution_count": 0, |
|
|
141 |
"outputs": [ |
|
|
142 |
{ |
|
|
143 |
"output_type": "execute_result", |
|
|
144 |
"data": { |
|
|
145 |
"text/plain": [ |
|
|
146 |
"0.1935311552247036" |
|
|
147 |
] |
|
|
148 |
}, |
|
|
149 |
"metadata": { |
|
|
150 |
"tags": [] |
|
|
151 |
}, |
|
|
152 |
"execution_count": 4 |
|
|
153 |
} |
|
|
154 |
] |
|
|
155 |
}, |
|
|
156 |
{ |
|
|
157 |
"cell_type": "markdown", |
|
|
158 |
"metadata": { |
|
|
159 |
"id": "ghsRNPHUu8sO", |
|
|
160 |
"colab_type": "text" |
|
|
161 |
}, |
|
|
162 |
"source": [ |
|
|
163 |
"## **Building the Model**" |
|
|
164 |
] |
|
|
165 |
}, |
|
|
166 |
{ |
|
|
167 |
"cell_type": "code", |
|
|
168 |
"metadata": { |
|
|
169 |
"id": "lV8VISV62JAs", |
|
|
170 |
"colab_type": "code", |
|
|
171 |
"colab": {} |
|
|
172 |
}, |
|
|
173 |
"source": [ |
|
|
174 |
"with tf.device(\"/GPU:1\"):\n", |
|
|
175 |
" model = Sequential()\n", |
|
|
176 |
"\n", |
|
|
177 |
" model.add(Bidirectional(LSTM(100, return_sequences=True), input_shape=(slices_per_patient, 8192)))\n", |
|
|
178 |
" model.add(TimeDistributed(Dropout(0.5)))\n", |
|
|
179 |
" model.add(TimeDistributed(Dense(100, use_bias=False)))\n", |
|
|
180 |
" model.add(TimeDistributed(BatchNormalization()))\n", |
|
|
181 |
" model.add(TimeDistributed(Activation(\"relu\")))\n", |
|
|
182 |
" model.add(TimeDistributed(Dropout(0.5)))\n", |
|
|
183 |
" model.add(TimeDistributed(Dense(100, use_bias=False)))\n", |
|
|
184 |
" model.add(TimeDistributed(BatchNormalization()))\n", |
|
|
185 |
" model.add(TimeDistributed(Activation(\"relu\")))\n", |
|
|
186 |
" model.add(TimeDistributed(Dense(1, activation=\"sigmoid\")))\n", |
|
|
187 |
" \n", |
|
|
188 |
" model.compile(loss=\"binary_crossentropy\", optimizer=Adam(lr=0.0001), metrics=model_metrics)" |
|
|
189 |
], |
|
|
190 |
"execution_count": 0, |
|
|
191 |
"outputs": [] |
|
|
192 |
}, |
|
|
193 |
{ |
|
|
194 |
"cell_type": "markdown", |
|
|
195 |
"metadata": { |
|
|
196 |
"id": "hq1J88JEvCfs", |
|
|
197 |
"colab_type": "text" |
|
|
198 |
}, |
|
|
199 |
"source": [ |
|
|
200 |
"## **Fitting the Model**" |
|
|
201 |
] |
|
|
202 |
}, |
|
|
203 |
{ |
|
|
204 |
"cell_type": "code", |
|
|
205 |
"metadata": { |
|
|
206 |
"id": "ZDdbBtY82JAq", |
|
|
207 |
"colab_type": "code", |
|
|
208 |
"colab": {} |
|
|
209 |
}, |
|
|
210 |
"source": [ |
|
|
211 |
"# Training setup\n", |
|
|
212 |
"model_metrics = [\"accuracy\",\n", |
|
|
213 |
" tensorflow.keras.metrics.Precision(),\n", |
|
|
214 |
" tensorflow.keras.metrics.Recall(),\n", |
|
|
215 |
" tensorflow.keras.metrics.AUC()]\n", |
|
|
216 |
"\n", |
|
|
217 |
"slices_per_patient = 24\n", |
|
|
218 |
"batch_size = 100\n", |
|
|
219 |
"epochs = 100\n", |
|
|
220 |
"model_name = \"bi-rcnn-model\"\n", |
|
|
221 |
"\n", |
|
|
222 |
"checkpoint = ModelCheckpoint(\"RCNN_models/bi-rcnn-model-{epoch:03d}-{val_recall:.2f}.hdf5\", \n", |
|
|
223 |
" \"val_accuracy\",\n", |
|
|
224 |
" save_best_only=False, verbose=2)\n", |
|
|
225 |
"\n", |
|
|
226 |
"stopping = EarlyStopping(\"val_accuracy\", patience = 10, verbose = 2, mode = \"max\")\n", |
|
|
227 |
"\n", |
|
|
228 |
"callbacks = [stopping, checkpoint]" |
|
|
229 |
], |
|
|
230 |
"execution_count": 0, |
|
|
231 |
"outputs": [] |
|
|
232 |
}, |
|
|
233 |
{ |
|
|
234 |
"cell_type": "code", |
|
|
235 |
"metadata": { |
|
|
236 |
"scrolled": true, |
|
|
237 |
"id": "dT5yePJZ2JAv", |
|
|
238 |
"colab_type": "code", |
|
|
239 |
"colab": {} |
|
|
240 |
}, |
|
|
241 |
"source": [ |
|
|
242 |
"# Model fitting\n", |
|
|
243 |
"history = model.fit(data_array, label_array,\n", |
|
|
244 |
" batch_size=batch_size,\n", |
|
|
245 |
" epochs=epochs,\n", |
|
|
246 |
" validation_split=0.2,\n", |
|
|
247 |
" callbacks=callbacks,\n", |
|
|
248 |
" verbose=2)" |
|
|
249 |
], |
|
|
250 |
"execution_count": 0, |
|
|
251 |
"outputs": [] |
|
|
252 |
}, |
|
|
253 |
{ |
|
|
254 |
"cell_type": "markdown", |
|
|
255 |
"metadata": { |
|
|
256 |
"id": "NDt7vp3sr9Lf", |
|
|
257 |
"colab_type": "text" |
|
|
258 |
}, |
|
|
259 |
"source": [ |
|
|
260 |
"# **Plotting Development of Loss, AUC, Recall**" |
|
|
261 |
] |
|
|
262 |
}, |
|
|
263 |
{ |
|
|
264 |
"cell_type": "code", |
|
|
265 |
"metadata": { |
|
|
266 |
"id": "5wubkccr2JAx", |
|
|
267 |
"colab_type": "code", |
|
|
268 |
"colab": {} |
|
|
269 |
}, |
|
|
270 |
"source": [ |
|
|
271 |
"with open(\"RNN_histories/bi-rcnn-{}.pkl\".format(model_name), \"wb\") as f:\n", |
|
|
272 |
" pickle.dump(history.history, f)" |
|
|
273 |
], |
|
|
274 |
"execution_count": 0, |
|
|
275 |
"outputs": [] |
|
|
276 |
}, |
|
|
277 |
{ |
|
|
278 |
"cell_type": "code", |
|
|
279 |
"metadata": { |
|
|
280 |
"id": "3ZZdmq0P0t5z", |
|
|
281 |
"colab_type": "code", |
|
|
282 |
"colab": {} |
|
|
283 |
}, |
|
|
284 |
"source": [ |
|
|
285 |
"# Takes in one of \"loss\", \"auc\", \"recall\"\n", |
|
|
286 |
"# Plots the development of the corresponding metric\n", |
|
|
287 |
"def plot_metric(metric):\n", |
|
|
288 |
" plt.figure(figsize=(10, 6))\n", |
|
|
289 |
" plt.plot(history.history[metric], label=metric)\n", |
|
|
290 |
" plt.plot(history.history[\"val_\" + metric], label=\"val_\" + metric)\n", |
|
|
291 |
" plt.xlabel(\"epoch\")\n", |
|
|
292 |
" plt.ylabel(metric)\n", |
|
|
293 |
" plt.title(model_name + metric)\n", |
|
|
294 |
" plt.legend()\n", |
|
|
295 |
" plt.tight_layout()\n", |
|
|
296 |
" plt.savefig(\"RNN_plots/bi-rcnn-{}_\".format(model_name) + metric + \".png\", dpi=300)\n", |
|
|
297 |
" plt.show()\n", |
|
|
298 |
"\n", |
|
|
299 |
" pass" |
|
|
300 |
], |
|
|
301 |
"execution_count": 0, |
|
|
302 |
"outputs": [] |
|
|
303 |
}, |
|
|
304 |
{ |
|
|
305 |
"cell_type": "code", |
|
|
306 |
"metadata": { |
|
|
307 |
"id": "-rLp37bE2JA7", |
|
|
308 |
"colab_type": "code", |
|
|
309 |
"colab": {} |
|
|
310 |
}, |
|
|
311 |
"source": [ |
|
|
312 |
"# Plot of train and test loss\n", |
|
|
313 |
"plot_metric(\"loss\")" |
|
|
314 |
], |
|
|
315 |
"execution_count": 0, |
|
|
316 |
"outputs": [] |
|
|
317 |
}, |
|
|
318 |
{ |
|
|
319 |
"cell_type": "code", |
|
|
320 |
"metadata": { |
|
|
321 |
"id": "VSr_TibG2JBA", |
|
|
322 |
"colab_type": "code", |
|
|
323 |
"colab": {} |
|
|
324 |
}, |
|
|
325 |
"source": [ |
|
|
326 |
"# Plot of train and test recall\n", |
|
|
327 |
"plot_metric(\"recall\")" |
|
|
328 |
], |
|
|
329 |
"execution_count": 0, |
|
|
330 |
"outputs": [] |
|
|
331 |
}, |
|
|
332 |
{ |
|
|
333 |
"cell_type": "code", |
|
|
334 |
"metadata": { |
|
|
335 |
"id": "K-4-XAxT2JBD", |
|
|
336 |
"colab_type": "code", |
|
|
337 |
"colab": {} |
|
|
338 |
}, |
|
|
339 |
"source": [ |
|
|
340 |
"# Plot of train and test AUC\n", |
|
|
341 |
"plot_metric(\"auc\")" |
|
|
342 |
], |
|
|
343 |
"execution_count": 0, |
|
|
344 |
"outputs": [] |
|
|
345 |
} |
|
|
346 |
] |
|
|
347 |
} |