-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathct_python.html
More file actions
864 lines (752 loc) · 42.6 KB
/
ct_python.html
File metadata and controls
864 lines (752 loc) · 42.6 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
<!DOCTYPE HTML>
<!--
Phantom by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>CT Python Tutorial</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<div class="inner">
<!-- Logo -->
<a href="index.html" class="logo">
<span class="symbol"><img src="images/NeuroNestLogo.png" alt="NeuroNest Logo" /></span><span class="title">NeuroNest</span>
</a>
<!-- Nav -->
<nav>
<ul>
<li><a href="#menu">Menu</a></li>
</ul>
</nav>
</div>
</header>
<!-- Menu -->
<nav id="menu">
<h2>Menu</h2>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="resource_menu.html">Resources</a></li>
<li><a href="https://sopkoc.wixsite.com/neuronest/forum">Ask a Question</a></li>
<li><a href="https://sopkoc.wixsite.com/neuronest/about">About NeuroNest</a></li>
<li><a href="https://sopkoc.wixsite.com/neuronest/contact">Contact</a></li>
</ul>
</nav>
<!-- Main -->
<div id="main">
<div class="inner">
<h1>Welcome to the NeuroNest Tutorial on CT Imaging Classification using Artificial Neural Networks!</h1>
<span class="image main"><img src="images/pic13.jpg" alt="" /></span>
<h2 id="tutorial-overview-">Tutorial Overview:</h2>
<p><em>Tutorial time</em>: approximately 70 min</p>
<p>In this tutorial, our objective is to build a neural network using PyTorch to classify CT brain images as either normal or having a hemorrhage. We will cover the entire process from data preprocessing to model evaluation.</p>
<p>If you prefer an interactive tutorial, please see our <a href="https://colab.research.google.com/drive/1YQe8rqhup-_ihQJeAmzNhdOqP6ZTHiya?usp=sharing#scrollTo=-fYsSG8v71NH">Google Colab version</a>.</p>
<h3 id="objectives-">Objectives:</h3>
<ol>
<li><strong>Introduction and Setup</strong></li>
<li><strong>Importing Required Libraries</strong></li>
<li><strong>Downloading the Data</strong></li>
<li><strong>Loading the Dataset</strong></li>
<li><strong>Exploratory Data Analysis (EDA)</strong></li>
<li><strong>Data Preprocessing</strong></li>
<li><strong>Splitting the Dataset</strong></li>
<li><strong>Building the Neural Network Model</strong></li>
<li><strong>Training and Evaluating the Model</strong></li>
<li><strong>Visualizing Model Performance</strong></li>
</ol>
<p><strong>Let's get started!</strong></p>
<h2 id="1-introduction-and-setup">1. Introduction and Setup</h2>
<p>CT imaging, or Computed Tomography imaging, uses X-rays to create detailed pictures of the inside of the body. It is crucial in medical diagnostics for detecting conditions such as tumors, fractures, and hemorrhages. <a href="ct_info.html">Read more about CT neuroimaging here.</a></p>
<p>In this tutorial, we will cover several fundamental concepts that are essential for processing and visualizing CT brain images in Python, as well as building a neural network. We will walk through each step to classify CT brain images as either normal (labeled 0) or having a hemorrhage (labeled 1). By the end of this tutorial, you should have a solid understanding of how to preprocess the data, build, and evaluate a neural network model using PyTorch.</p>
<p>For more information about how to install, access, or code in Python, visit <a href="python_data.html">NeuroNest's Python Tutorial</a>.</p>
<h2 id="2-importing-required-libraries">2. Importing Required Libraries</h3>
<p>To build our neural network, we'll need several Python and PyTorch libraries. These libraries will help with data manipulation, model building, and visualization.</p>
<pre><code><strong># Import essential libraries for building a Neural Network using Pytorch</strong>
<p>import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import shutil
import random
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix</p>
<p><strong># Additional libraries for data handling and visualization</strong>
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
from PIL import Image</p>
</code></pre>
<h2>3. Downloading the Data</h2>
<p>We will use a CT Brain Imaging dataset from Kaggle. Either download directly from Kaggle at <a href="https://www.kaggle.com/datasets/felipekitamura/head-ct-hemorrhage">https://www.kaggle.com/datasets/felipekitamura/head-ct-hemorrhage</a> or run the code below to use the Kaggle API to automatically download and extract the dataset.</p>
<pre><code><p>IMPORTANT: RUN THIS CELL IN ORDER TO IMPORT YOUR KAGGLE DATA SOURCES TO THE CORRECT LOCATION (/kaggle/input) IN YOUR NOTEBOOK.
NOTE: THIS NOTEBOOK ENVIRONMENT DIFFERS FROM KAGGLE'S PYTHON ENVIRONMENT SO THERE MAY BE MISSING LIBRARIES USED BY YOUR NOTEBOOK.</p>
<p>import os
import sys
from tempfile import NamedTemporaryFile
from urllib.request import urlopen
from urllib.parse import unquote, urlparse
from urllib.error import HTTPError
from zipfile import ZipFile
import tarfile
import shutil
CHUNK_SIZE = 40960
DATA_SOURCE_MAPPING = 'head-ct-hemorrhage:https%3A%2F%2Fstorage.googleapis.com%2Fkaggle-data-sets%2F71215%2F152137%2Fbundle%2Farchive.zip%3FX-Goog-Algorithm%3DGOOG4-RSA-SHA256%26X-Goog-Credential%3Dgcp-kaggle-com%2540kaggle-161607.iam.gserviceaccount.com%252F20240807%252Fauto%252Fstorage%252Fgoog4_request%26X-Goog-Date%3D20240807T171722Z%26X-Goog-Expires%3D259200%26X-Goog-SignedHeaders%3Dhost%26X-Goog-Signature%3D4cfcf43a51e3ca0216a816401c6a9ead19272a4e62a33ee3ae3d4315eb4f6eb1822cba8fc13ac00113bbc390a84a3cda5ce0b6faddb2740af90e5cb916dfc6fe81f546e55803c4f74b75d95db4b64a2e0cc77f6820c062c5ccfca7a8404cd851eb66a7c89fa26a97ebf23b82ce8c1141d9ee2b2f1e48f297d299efd306776e3fb6bb49381126c0f7c5a9c26f26c2020efcea9f05b4a5625d2bcbf1f2c54c542692184d2140118c7e988c0e18734f5a128891c2845aa2814067cb6253c95309bcfcc255dc0add78794f789ff063f7f46b291c48f3161789aea3de080cf09e2f54631cbc58d788711f19cb76dab1b9424d58b31825e7f4becac5ed4ed8e2ff389a'</p>
<p>KAGGLE_INPUT_PATH='/kaggle/input'
KAGGLE_WORKING_PATH='/kaggle/working'
KAGGLE_SYMLINK='kaggle'
!umount /kaggle/input/ 2> /dev/null
shutil.rmtree('/kaggle/input', ignore_errors=True)
os.makedirs(KAGGLE_INPUT_PATH, 0o777, exist_ok=True)
os.makedirs(KAGGLE_WORKING_PATH, 0o777, exist_ok=True)
try:
os.symlink(KAGGLE_INPUT_PATH, os.path.join("..", 'input'), target_is_directory=True)
except FileExistsError:
pass
try:
os.symlink(KAGGLE_WORKING_PATH, os.path.join("..", 'working'), target_is_directory=True)
except FileExistsError:
pass
for data_source_mapping in DATA_SOURCE_MAPPING.split(','):
directory, download_url_encoded = data_source_mapping.split(':')
download_url = unquote(download_url_encoded)
filename = urlparse(download_url).path
destination_path = os.path.join(KAGGLE_INPUT_PATH, directory)
try:
with urlopen(download_url) as fileres, NamedTemporaryFile() as tfile:
total_length = fileres.headers['content-length']
print(f'Downloading {directory}, {total_length} bytes compressed')
dl = 0
data = fileres.read(CHUNK_SIZE)
while len(data) > 0:
dl += len(data)
tfile.write(data)
done = int(50 <em> dl / int(total_length))
sys.stdout.write(f"\r[{'=' </em> done}{' ' * (50-done)}] {dl} bytes downloaded")
sys.stdout.flush()
data = fileres.read(CHUNK_SIZE)
if filename.endswith('.zip'):
with ZipFile(tfile) as zfile:
zfile.extractall(destination_path)
else:
with tarfile.open(tfile.name) as tarfile:
tarfile.extractall(destination_path)
print(f'\nDownloaded and uncompressed: {directory}')
except HTTPError as e:
print(f'Failed to load (likely expired) {download_url} to path {destination_path}')
continue
except OSError as e:
print(f'Failed to load {download_url} to path {destination_path}')
continue
print('Data source import complete.')
</code></pre>
<p><h2>4. Loading the Dataset</h2>
To begin analyzing our dataset, we need to load the images and their corresponding labels into Python. We can achieve this using libraries like Pandas for handling the labels and PIL (Python Imaging Library) for loading the images.</p>
<p><strong>4.1. Loading the Labels.</strong>
First, we’ll load the labels from a CSV file and apply necessary corrections.</p>
<pre><code># Load the labels
labels = pd.read_csv('/kaggle/input/head-ct-hemorrhage/labels.csv')
# Rename column if necessary (remove extra spaces)
labels.rename(columns={' hemorrhage': 'hemorrhage'}, inplace=True)
# Convert 'id' column to integer, then format as string with .png extension
labels['id'] = labels['id'].astype(int)
labels['id'] = labels['id'].apply(lambda x: str('%03d' % x) + ".png")
</code></pre>
<p>The <code>labels.head()</code>` function outputs the first few rows of the labels DataFrame, which looks like this:</p>
<pre><code>
# Display the first few rows to verify
print(labels.head())
# List unique classes in the 'hemorrhage' column
classes = list(labels['hemorrhage'].unique())
print("Classes:", classes)
</code></pre>
<p>This DataFrame has two columns:
id: A unique identifier for each image.
hemorrhage: The label indicating whether the image shows a hemorrhage (1) or is normal (0).</p>
<p><strong>4.2 Loading and Displaying Sample Images.</strong>
Next, we'll load some sample images using PIL and display them along with their labels.</p>
<pre><code>from PIL import Image
import matplotlib.pyplot as plt
# Function to display images in a grid
def display_images_grid(image_paths, labels):
num_images = len(image_paths)
fig, axes = plt.subplots(1, num_images, figsize=(15, 5))
if num_images == 1:
axes = [axes] # Ensure axes is iterable if there's only one image
for ax, image_path, label in zip(axes, image_paths, labels):
img = Image.open(image_path)
ax.imshow(img, cmap='gray')
ax.set_title(f'Label: {label}')
ax.axis('off')
plt.show()
# Ensure we include at least one image from each class
class_0_image = labels[labels['hemorrhage'] == 0].sample(1)
class_1_image = labels[labels['hemorrhage'] == 1].sample(1)
# Combine samples from both classes and a few additional random samples
additional_images = labels.sample(3) # Add more samples for variety
selected_images = pd.concat([class_0_image, class_1_image, additional_images])
# Construct image paths and labels
image_paths = [f'/kaggle/input/head-ct-hemorrhage/head_ct/head_ct/{row["id"]}' for _, row in selected_images.iterrows()]
image_labels = selected_images['hemorrhage'].tolist()
# Display the images side by side
display_images_grid(image_paths, image_labels)
</code></pre>
<img src="images/ct_python_1.png" alt="images output" style="width: 25%;">
<p>Did you notice that the images dont have the same size? We will get into that shortly.</p>
<h2>5. Exploratory Data Analysis (EDA)</h2>
<p>Before performing any kind of experimentation or analysis, it's crucial to understand the dataset. Exploratory Data Analysis (EDA) helps us get insights into the data, detect any anomalies, and understand its structure. In this step, we'll perform basic statistics, visualize the distribution of labels, and display some sample images to gain a better understanding of our dataset.</p>
<p><strong>Basic Statistics:</strong> Let's start by examining some basic statistics of our dataset, such as the number of samples and the distribution of labels.</p>
<pre><code>
# Basic statistics
num_samples = len(labels)
label_distribution = labels['hemorrhage'].value_counts()
print(f'Total number of samples: {num_samples}')
print('Distribution of labels:')
print(label_distribution)
</code></pre>
<p>Here we observe that our dataset is perfectly balanced, with an equal number of images for both classes: hemorrhage and normal. This balance is important for training our neural network, as it ensures that the model has an equal opportunity to learn from both types of images, which can help improve its performance and reduce bias.</p>
<p><strong>Checking Image Size:</strong>Since we will be dealing with image data, It's important to verify that all images in our dataset have the same dimensions. Inconsistent image sizes can cause issues when training a model. Let's check the sizes of all images.
The code below checks the width and height of each image and gives us a summary of these sizes. If the images vary too much, we may need to resize them to ensure consistency before training our model.</p>
<pre><code>
# Function to get image sizes
def get_image_sizes(image_folder):
sizes = []
for filename in os.listdir(image_folder):
if filename.endswith(".png"):
with Image.open(os.path.join(image_folder, filename)) as img:
sizes.append(img.size)
return sizes
# Get image sizes
image_folder = '/kaggle/input/head-ct-hemorrhage/head_ct/head_ct/'
sizes = get_image_sizes(image_folder)
size_df = pd.DataFrame(sizes, columns=['Width', 'Height'])
print(size_df.describe())
</code></pre>
<p>From the table, we observe the following about our image dimensions:</p>
<ul>
<li><strong>Width:</strong> The width of the images ranges from 134 pixels to 821 pixels, with an average width of approximately 355 pixels.</li>
<li><strong>Height:</strong> The height of the images ranges from 135 pixels to 957 pixels, with an average height of about 434 pixels.</li>
</ul>
<p>This indicates that our images vary significantly in size. Most images are around 345x435 pixels, but there is a wide range in dimensions. To ensure consistency and avoid problems during model training, we should resize all images to a standard size. This will help the neural network process the images more effectively and uniformly.</p>
<p>Before we move forward with resizing, let’s perform one last check to see if there are any corrupt images in our dataset.</p>
<p><strong>Checking for Corrupt or Empty Images:</strong></p>
<pre><code>
def check_image_integrity(image_folder):
corrupt_images = []
for filename in os.listdir(image_folder):
if filename.endswith(".png"):
try:
with Image.open(os.path.join(image_folder, filename)) as img:
img.verify() # Verify image integrity
except (IOError, SyntaxError) as e:
corrupt_images.append(filename)
return corrupt_images
# Check for corrupt images
corrupt_images = check_image_integrity(image_folder)
print(f'Number of corrupt images: {len(corrupt_images)}')
if corrupt_images:
print('Corrupt images found:', corrupt_images)
</code></pre>
<p>Fantastic! We have no corrupt images, let now proceed forward with resizing and other preprocessing steps</p>
<h2>6. Data Preprocessing</h2>
<p>Before feeding our images into a neural network, we need to preprocess them to ensure they are in the right format and size. Preprocessing helps improve model performance and training efficiency. Common preprocessing steps include resizing, normalization, and data augmentation.</p>
<p><strong>6.1 Resize Images:</strong>Previously, we observed that the sizes of images in our dataset vary widely. To ensure consistency, we resize all images to a standard size of 224x224 pixels. This size is commonly used in image processing and deep learning. We also chose 224x224 size because it offers a good balance between maintaining enough image detail and managing computational resources. Larger images would provide more detail but require more memory and processing power. On the other hand, smaller images would be easier to handle but might lose important details. By resizing our images to a uniform size, we make it easier for the neural network to process them consistently and effectively.</p>
<pre><code>
# Define the target size
target_size = (224, 224) # Example size
def resize_images(image_folder, target_size):
resized_folder = '/kaggle/input/head-ct-hemorrhage/resized_images/'
os.makedirs(resized_folder, exist_ok=True)
for filename in os.listdir(image_folder):
if filename.endswith(".png"):
img_path = os.path.join(image_folder, filename)
with Image.open(img_path) as img:
# Calculate the new size while preserving the aspect ratio
img.thumbnail(target_size, Image.ANTIALIAS)
# Create a new image with the target size and paste the resized image
img_resized = Image.new("RGB", target_size, (255, 255, 255))
img_resized.paste(img, ((target_size[0] - img.width) // 2, (target_size[1] - img.height) // 2))
# Save the resized image
img_resized.save(os.path.join(resized_folder, filename))
# Resize images
resize_images('/kaggle/input/head-ct-hemorrhage/head_ct/head_ct/', target_size)
</code></pre>
<p>Now that we resized all images to 224x224 pixels, and saved them into a folder named "resized_images". Let's normalize our images.</p>
<p><strong>6.2 Normalization:</strong> <p>You may wonder, Why do we need to normalize images? Well, Normalization scales pixel values to a standard range (typically 0 to 1). it is a crucial preprocessing step in image processing and deep learning. This process has several important benefits:</p>
<ul>
<li>mproves Model Training Efficiency:</li>
<ul>
<li>Convergence Speed: Neural networks learn more effectively when inputs are on a similar scale. Normalization helps the network converge faster during training by ensuring that all input features contribute equally to the learning process.</li>
<li>Stable Training: Scaling inputs to a consistent range helps in stabilizing the training process, reducing the risk of gradients becoming too large or too small.</li>
</ul>
<li>Enhances Model Performance:</li>
<ul>
<li>Consistent Input Values: Normalized images provide a consistent range of values, which helps the model generalize better and improves overall performance.</li>
<li>Prevents Bias: Without normalization, the network might learn biases based on the scale of input data, which can negatively impact the performance.</li>
</ul>
<li>Facilitates Use of Pretrained Models:</li>
<ul>
<li>Standard Practice: Many pretrained models (e.g., VGG16, ResNet) are trained with images normalized to specific mean and standard deviation values. Normalizing your images in the same way allows you to leverage these pretrained models effectively for transfer learning.</li>
</ul>
</ul>
<p>So, Does This Apply to Our Dataset?</p>
<p>Yes, normalization is particularly relevant for our dataset of CT brain images:</p>
<ul>
<li>Pixel Range Consistency: The pixel values of our CT images vary widely as we saw in section 5.2. Normalizing ensures that all images are on a similar scale, which is crucial for training a neural network.</li>
<li>Improved Training: By normalizing our images to the same scale, we help the neural network learn more effectively and make the training process more stable.</li>
</ul>
<pre><code>
# Define normalization transform
normalize_transform = transforms.Compose([
transforms.Resize(target_size),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# Define the paths
image_folder = '/kaggle/input/head-ct-hemorrhage/resized_images/'
normalized_folder = '/kaggle/input/head-ct-hemorrhage/normalized_images/'
os.makedirs(normalized_folder, exist_ok=True)
def normalize_images(image_folder, normalized_folder):
for filename in os.listdir(image_folder):
if filename.endswith(".png"):
img_path = os.path.join(image_folder, filename)
img = Image.open(img_path)
img_normalized = normalize_transform(img)
# Save the normalized image
img_normalized_pil = transforms.ToPILImage()(img_normalized)
img_normalized_pil.save(os.path.join(normalized_folder, filename))
# Normalize all images
normalize_images(image_folder, normalized_folder)
# Display a sample normalized image and its non-normalized version side by side
def display_comparison(image_path, normalized_path):
img = Image.open(image_path)
img_normalized = Image.open(normalized_path)
# Convert normalized image to tensor for display
img_normalized_tensor = transforms.ToTensor()(img_normalized)
# Plot the images side by side
plt.figure(figsize=(12, 6))
# Display non-normalized image
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Non-Normalized Image')
plt.axis('off')
# Display normalized image
plt.subplot(1, 2, 2)
plt.imshow(img_normalized_tensor.permute(1, 2, 0)) # Convert tensor to image for visualization
plt.title('Normalized Image')
plt.axis('off')
plt.show()
# Example paths for a sample image
sample_image_filename = '001.png'
display_comparison(
os.path.join(image_folder, sample_image_filename),
os.path.join(normalized_folder, sample_image_filename)
)
</code></pre>
<img src="images/ct_python_2.png" alt="images output" style="width: 25%;">
<p>Now, one last step remains, which is Data Augmentation.</p>
<p><strong>6.3 Data Augmentation:</strong> In general, data augmentation artificially increases the size of the training dataset by applying random transformations. Image augmentation involves creating additional random transformations to existing images. This technique helps to artificially increase the size of the training dataset and introduces variety, which is particularly useful when working with smaller datasets. This helps the model generalize better by exposing it to a variety of modified images especially in small dataset like ours and reduces the risk of the model overfitting to the training data. Image Augmentation techniques include flipping, rotation, and color adjustments, which we will apply to our images in our training set only, because we need real-world images to test our model and we need to avoid that the neural network creates preferences to flipped or transformed images. So let's split our data first </p>
<h2>7. Splitting the Dataset</h2>
<p>We split our data into Training, Validation and Test portions.
Note: In our training process, we'll use both types of images:
Non-Augmented Resized-Normalized Images: These provide the standard data our model needs to learn the core features of our images.
Augmented Resized-Normalized Images: These are modified versions with random transformations to increase data diversity, helping the model generalize better and avoid overfitting.</p>
<p><strong>7.1. Splitting into Training, Val and Test Sets:</strong> The dataset is strictly class 1 until index 100 and then strictly class 0 afterwards, this indicates that dataset is likely not shuffled and is sorted by class labels in a specific order. This ordering can lead to biased splits if not handled correctly. Therefore we must shuffle the data before splitting.</p>
<pre><code>
# Define paths
normalized_folder = '/kaggle/input/head-ct-hemorrhage/normalized_images/'
train_folder = '/kaggle/input/head-ct-hemorrhage/train_images/'
val_folder = '/kaggle/input/head-ct-hemorrhage/val_images/'
test_folder = '/kaggle/input/head-ct-hemorrhage/test_images/'
# Create directories
os.makedirs(train_folder, exist_ok=True)
os.makedirs(val_folder, exist_ok=True)
os.makedirs(test_folder, exist_ok=True)
# Shuffle the dataset
shuffled_labels = shuffle(labels, random_state=42) # The
# Split the dataset
train_df, temp_df = train_test_split(shuffled_labels, test_size=0.2, stratify=shuffled_labels['hemorrhage'])
val_df, test_df = train_test_split(temp_df, test_size=0.5, stratify=temp_df['hemorrhage'])
# Function to copy images to the new folders
def copy_images(df, src_folder, dest_folder):
for _, row in df.iterrows():
src_path = os.path.join(src_folder, row['id'])
dest_path = os.path.join(dest_folder, row['id'])
shutil.copy(src_path, dest_path)
# Copy images to their respective folders
copy_images(train_df, normalized_folder, train_folder)
copy_images(val_df, normalized_folder, val_folder)
copy_images(test_df, normalized_folder, test_folder)
# Print dataset split details
total_samples = len(labels)
train_samples = len(train_df)
val_samples = len(val_df)
test_samples = len(test_df)
print(f'Total images: {total_samples}')
print(f'Training set: {train_samples} images ({train_samples / total_samples * 100:.2f}%)')
print(f'Validation set: {val_samples} images ({val_samples / total_samples * 100:.2f}%)')
print(f'Test set: {test_samples} images ({test_samples / total_samples * 100:.2f}%)')
</code></pre>
<pre><code>
# Verify class distribution
print("Class distribution in train set:")
print(train_df['hemorrhage'].value_counts())
print("Class distribution in validation set:")
print(val_df['hemorrhage'].value_counts())
print("Class distribution in test set:")
print(test_df['hemorrhage'].value_counts())
</code></pre>
<p><strong>7.2. Organizing Images by Class</strong></p>
<pre><code>
def create_class_folders(src_folder, dest_folder, labels):
"""
Create class subdirectories in the destination folder and copy images.
"""
classes = labels['hemorrhage'].unique()
for cls in classes:
class_folder = os.path.join(dest_folder, str(cls))
os.makedirs(class_folder, exist_ok=True)
for _, row in labels.iterrows():
src_path = os.path.join(src_folder, row['id'])
dest_path = os.path.join(dest_folder, str(row['hemorrhage']), row['id'])
shutil.copy(src_path, dest_path)
# Create class folders for training images
create_class_folders('/kaggle/input/head-ct-hemorrhage/normalized_images/', train_folder, train_df)
create_class_folders('/kaggle/input/head-ct-hemorrhage/normalized_images/', val_folder, val_df)
create_class_folders('/kaggle/input/head-ct-hemorrhage/normalized_images/', test_folder, test_df)
</code></pre>
<p><strong>7.3.Apply Augmentation to Training and validation sets</strong></p>
<pre><code>
# Define augmentation transformations
augmentation_transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.RandomRotation(30),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),
transforms.ToTensor()
])
# Define the augmented images folder paths
augmented_train_folder = '/kaggle/input/head-ct-hemorrhage/augmented_train_images/'
augmented_val_folder = '/kaggle/input/head-ct-hemorrhage/augmented_val_images/'
# Ensure the augmented folders exist
os.makedirs(augmented_train_folder, exist_ok=True)
os.makedirs(augmented_val_folder, exist_ok=True)
# Function to augment images and save them in class-specific folders
def augment_images(image_folder, augmented_folder, labels):
for _, row in labels.iterrows():
img_name = row['id']
class_label = row['hemorrhage']
img_path = os.path.join(image_folder, img_name)
img = Image.open(img_path)
img_augmented = augmentation_transform(img)
# Create class-specific folder if it doesn't exist
class_folder = os.path.join(augmented_folder, str(class_label))
os.makedirs(class_folder, exist_ok=True)
# Convert tensor to PIL image and save
img_augmented_pil = transforms.ToPILImage()(img_augmented)
img_augmented_pil.save(os.path.join(class_folder, img_name))
# Apply augmentation to the training and validation sets
augment_images(train_folder, augmented_train_folder, train_df)
augment_images(val_folder, augmented_val_folder, val_df)
</code></pre>
<p>Now, lets's visualize a sample image and its augmented version.</p>
<pre><code>
def display_random_comparison(normalized_folder, augmented_folder, class_label):
"""
Display a random sample image from the normalized set and its augmented version side by side.
Args:
normalized_folder (str): Path to the folder with normalized images.
augmented_folder (str): Path to the folder with augmented images.
class_label (int): The class label (subfolder) for the augmented images.
"""
# Get a list of files in the normalized folder
image_filenames = [f for f in os.listdir(normalized_folder) if f.endswith('.png')]
# Filter to include only images that have an augmented version
valid_filenames = [
f for f in image_filenames
if os.path.exists(os.path.join(augmented_folder, str(class_label), f))
]
if not valid_filenames:
print(f"No images with augmented versions found in class {class_label}.")
return
# Choose a random valid image
sample_image_filename = random.choice(valid_filenames)
# Define paths to the sample images
normalized_image_path = os.path.join(normalized_folder, sample_image_filename)
augmented_image_path = os.path.join(augmented_folder, str(class_label), sample_image_filename)
# Load the images
img_normalized = Image.open(normalized_image_path)
img_augmented = Image.open(augmented_image_path)
# Convert the augmented image to a tensor for display
img_augmented_tensor = transforms.ToTensor()(img_augmented)
# Display the images side by side
plt.figure(figsize=(12, 6))
# Display the normalized image
plt.subplot(1, 2, 1)
plt.imshow(img_normalized)
plt.title('Normalized Image')
plt.axis('off')
# Display the augmented image
plt.subplot(1, 2, 2)
plt.imshow(img_augmented_tensor.permute(1, 2, 0)) # Convert tensor to image for visualization
plt.title('Augmented Image')
plt.axis('off')
plt.show()
# Example usage
display_random_comparison(
normalized_folder='/kaggle/input/head-ct-hemorrhage/normalized_images/', # Path to normalized images
augmented_folder='/kaggle/input/head-ct-hemorrhage/augmented_train_images/', # Path to augmented images (training set)
class_label=0 # Adjust based on the class label in the augmented folder
)
</code></pre>
<img src="images/ct_python_3.png" alt="images output" style="width: 25%;">
<p>Finally, we define the path to the Image Folders for later feed into the neural network.</p>
<pre><code>
# Define the paths to the datasets
test_folder = '/kaggle/input/head-ct-hemorrhage/test_images/' # Test data remains the same
# List contents of the directories
print("Augmented Training folder contents:", os.listdir(augmented_train_folder))
print("Augmented Validation folder contents:", os.listdir(augmented_val_folder))
print("Test folder contents:", os.listdir(test_folder))
</code></pre>
<pre><code>
# Confirm strucutre of our folders and data split
def print_folder_structure(folder_path):
for root, dirs, files in os.walk(folder_path):
print(f'Root: {root}')
print(f'Dirs: {dirs}')
print(f'Files: {files}')
print_folder_structure(augmented_train_folder)
print_folder_structure(augmented_val_folder)
</code></pre>
<h2>8. Building the Neural Network Model</h2>
<p>A CNN typically consists of:
Convolutional Layers: These layers apply convolutions to the input image to extract features.
Activation Functions: Functions like ReLU introduce non-linearity.
Pooling Layers: These layers down-sample the feature maps.
Fully Connected Layers: These layers classify the features extracted by the convolutional layers.</p>
<p><strong>8.2. Model Definition</strong></p>
<pre><code>
from torchsummary import summary
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
# Convolutional Layer 1
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1)
# Convolutional Layer 2
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)
# Fully Connected Layer 1
self.fc1 = nn.Linear(64 * 56 * 56, 128) # Ensure this matches the flattened size after convolutions
# Fully Connected Layer 2
self.fc2 = nn.Linear(128, 2) # Output layer for binary classification (e.g., hemorrhage vs. no hemorrhage)
def forward(self, x):
# Apply convolutional layers with ReLU activation and max pooling
x = torch.relu(self.conv1(x))
x = torch.max_pool2d(x, kernel_size=2, stride=2)
x = torch.relu(self.conv2(x))
x = torch.max_pool2d(x, kernel_size=2, stride=2)
# Flatten the tensor for the fully connected layer
x = x.view(-1, 64 * 56 * 56) # Flattening the tensor, ensure input size is consistent with conv output
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# Define device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Device detected: {device}")
# Instantiate your model and move it to the device
model = SimpleCNN().to(device)
# Print the model summary
summary(model, input_size=(3, 224, 224)) # Check that input size is correct
</code></pre>
<p><strong>8.2. Loaders:</strong>After we have built our CNN architecture, we’ll prepare the dataset by creating data loaders. Data loaders are essential for efficiently loading and processing batches of data during training, validation, and testing. They handle the details of batching, shuffling, and parallel data loading.</p>
<pre><code>
# Define transformations for preprocessing
transform = transforms.Compose([
transforms.ToTensor() # Only convert to tensor, as resizing, normalization, and augmentation are already done
])
# Load datasets from the augmented folders
train_dataset = datasets.ImageFolder(root=augmented_train_folder, transform=transform)
val_dataset = datasets.ImageFolder(root=augmented_val_folder, transform=transform)
test_dataset = datasets.ImageFolder(root=test_folder, transform=transform)
# Create DataLoader for batching
train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)
val_loader = DataLoader(dataset=val_dataset, batch_size=64, shuffle=False)
test_loader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=False)
</code></pre>
<p><strong>8.3. Set Up the Training Process</strong>:</p>
<pre><code>
# Initialize the network
model = SimpleCNN()
# Define loss function
criterion = nn.CrossEntropyLoss()
# Define optimizer
optimizer = optim.Adam(model.parameters(), lr=0.001)
</code></pre>
<h2>9. Train and Validate the Model</h2>
<p>We now Write the training loop to train the model with the training data.</p>
<pre><code>
# Lists to store loss values for plotting
train_losses = []
val_losses = []
all_preds = []
all_labels = []
all_images = [] # Assuming you have images for visualization
num_epochs = 50
for epoch in range(num_epochs):
model.train() # Set the model to training mode
running_loss = 0.0
correct_train = 0
total_train = 0
for images, labels in train_loader:
# Move data to device
images, labels = images.to(device), labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
# Calculate training accuracy
_, predicted = torch.max(outputs.data, 1)
total_train += labels.size(0)
correct_train += (predicted == labels).sum().item()
# Calculate average training loss and accuracy for this epoch
avg_train_loss = running_loss / len(train_loader)
train_accuracy = 100 * correct_train / total_train
# Validation loop
model.eval() # Set the model to evaluation mode
running_val_loss = 0.0
correct_val = 0
total_val = 0
with torch.no_grad(): # No need to calculate gradients during validation
for images, labels in val_loader:
# Move data to device
images, labels = images.to(device), labels.to(device)
outputs = model(images)
loss = criterion(outputs, labels)
running_val_loss += loss.item()
# Calculate validation accuracy
_, predicted = torch.max(outputs.data, 1)
total_val += labels.size(0)
correct_val += (predicted == labels).sum().item()
# Collect predictions and labels for confusion matrix
all_preds.extend(predicted.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
all_images.extend(images.cpu().numpy()) # Collect images for visualization
# Calculate average validation loss and accuracy
avg_val_loss = running_val_loss / len(val_loader)
val_accuracy = 100 * correct_val / total_val
# Append losses for plotting
train_losses.append(avg_train_loss)
val_losses.append(avg_val_loss)
# Print epoch results in one line
print(f'Epoch [{epoch+1}/{num_epochs}] | '
f'Training Loss: {avg_train_loss:.4f} | '
f'Training Accuracy: {train_accuracy:.2f}% | '
f'Validation Loss: {avg_val_loss:.4f} | '
f'Validation Accuracy: {val_accuracy:.2f}%')
</code></pre>
<h2>10. Visualize Model Performance</h2>
<p>Now let's see how well or bad our NN model is performing.</p>
<p><strong>10.1. Loss Plot:</strong> Plotting the Training and validation loss. Examining this plot will help us detect over- or underfitting.</p>
<pre><code>
# Plot training loss and validation loss
plt.figure(figsize=(12, 6))
plt.plot(range(1, num_epochs + 1), train_losses, label='Training Loss')
plt.plot(range(1, num_epochs + 1), val_losses, label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.grid(True)
plt.show()
</code></pre>
<img src="images/ct_python_4.png" alt="images output" style="width: 25%;">
<p>Here we notice that the model is overfitting. The model's overfitting, indicated by significantly higher validation loss compared to training loss, could stem from several factors: a small or imbalanced dataset that leads to memorization rather than generalization, an overly complex model architecture, inadequate regularization techniques, or insufficient data augmentation. Additionally, training for too many epochs or having noisy training data can exacerbate overfitting. To address this, we shall consider increasing the dataset size, applying regularization, simplifying the model, using early stopping, and enhancing data augmentation to improve the model's generalization capabilities. These would be subjects of a complementary tutorial.</p>
<p><strong>10.2.Sample Ground Truth Images and their Predicted Classes:</strong> Also let's visualize sample CT images and their predicted class as well as the confusion Martix.</p>
<pre><code>
# Determine the number of correct and incorrect images to display
num_images = 10 # Number of images to display
num_correct_images = num_images // 2
num_incorrect_images = num_images - num_correct_images
# Collecting correct and incorrect images
correct_images = [(img, pred, actual) for img, pred, actual in zip(all_images, all_preds, all_labels) if pred == actual]
incorrect_images = [(img, pred, actual) for img, pred, actual in zip(all_images, all_preds, all_labels) if pred != actual]
# Ensure there are enough images to display
correct_images = correct_images[:num_correct_images]
incorrect_images = incorrect_images[:num_incorrect_images]
# Combine and shuffle images
selected_images = correct_images + incorrect_images
np.random.shuffle(selected_images)
# Plot images
plt.figure(figsize=(20, 10))
for i, (img, pred, actual) in enumerate(selected_images):
plt.subplot(2, num_images // 2, i + 1)
img = img.transpose(1, 2, 0) # Convert from (C, H, W) to (H, W, C)
plt.imshow(img)
plt.axis('off')
title_color = 'red' if pred != actual else 'black'
plt.title(f"Actual: {actual}\nPred: {pred}", color=title_color)
plt.show()
</code></pre>
<img src="images/ct_python_5.png" alt="images output" style="width: 25%;">
<pre><code>
# Compute confusion matrix
conf_matrix = confusion_matrix(all_labels, all_preds)
# Plot confusion matrix
plt.figure(figsize=(8, 6))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues',
xticklabels=['Class 0', 'Class 1'], yticklabels=['Class 0', 'Class 1'])
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()
</code></pre>
<img src="images/ct_python_6.png" alt="images output" style="width: 25%;">
</div>
</div>
<!-- Footer -->
<footer id="footer">
<div class="inner">
<section>
<h2>Funding</h2>
<p> We would like to express our heartfelt gratitude to <strong>Neurohackademy</strong> at the <strong>University of Washington eScience Institute</strong> for providing invaluable training and support. This experience has significantly enriched our understanding of neuroimaging and data science. We also acknowledge the support of the National Institute of Mental Health (NIMH) grant number <strong>5R25MH112480-08</strong>, which made this opportunity possible.</p>
</section>
<section>
<h2>Follow</h2>
<ul class="icons">
<li><a href="https://x.com/Neuro_Nest" class="icon brands style2 fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="https://github.com/NeuroHackademy2024/NeuroNest" class="icon brands style2 fa-github"><span class="label">GitHub</span></a></li>
<li><a href="https://sopkoc.wixsite.com/neuronest/contact" class="icon solid style2 fa-envelope"><span class="label">Email</span></a></li>
</ul>
</section>
<ul class="copyright">
<li>© Untitled. All rights reserved</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</footer>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>