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
library_name: keras
|
7 |
+
tags:
|
8 |
+
- medical
|
9 |
+
---
|
10 |
+
# ryefoxlime/PneumoniaDetection
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
I have developed a robust model that utilizes transfer learning and the powerful ResNet50V2 architecture to effectively classify chest X-ray images into two categories: pneumonia and normal. This model demonstrates high accuracy and generalizability, making it a promising tool for assisting in pneumonia diagnosis.
|
14 |
+
|
15 |
+
### Model Description
|
16 |
+
The ResNet50V2:
|
17 |
+
ResNet50V2 is a deep convolutional neural network (CNN) architecture, part of the ResNet (Residual Networks) family. It's known for its depth, utilizing residual blocks that help address the vanishing gradient problem during training. The "V2" signifies an improvement over the original ResNet50, incorporating tweaks to enhance performance.
|
18 |
+
|
19 |
+
Transfer Learning:
|
20 |
+
Transfer learning involves leveraging a pre-trained model's knowledge on a large dataset and applying it to a different but related task. For our use case, ResNet50V2, which has been trained on a diverse dataset, is adapted to classify pneumonia-related images.
|
21 |
+
|
22 |
+
Image Classification:
|
23 |
+
The core task of the model is to categorize images into two classes: "affected by pneumonia" and "normal." This binary classification is crucial for diagnosing medical conditions based on visual information in images.
|
24 |
+
|
25 |
+
Model Training:
|
26 |
+
During training, the pre-trained ResNet50V2 model is used as a feature extractor. The existing weights are frozen, preventing further training on the original dataset, and a new classifier tailored to this specific task is added. This new classifier is trained using the labeled dataset of pneumonia and normal images.
|
27 |
+
|
28 |
+
Loss Function and Optimization:
|
29 |
+
To guide the training process, a loss function is employed to measure the difference between predicted and actual labels. Common choices for image classification tasks include categorical cross-entropy. An optimizer, such as stochastic gradient descent (SGD) or Adam. In our case we have used Adam as our optimier of choice, which is used to adjust the model's weights based on the calculated loss.
|
30 |
+
|
31 |
+
Evaluation:
|
32 |
+
The model's performance is assessed using a separate dataset not seen during training. Metrics like accuracy, precision, recall, and F1-score are often used to gauge how well the model generalizes to new, unseen data.
|
33 |
+
|
34 |
+
Deployment:
|
35 |
+
Once the model demonstrates satisfactory performance, it can be deployed for real-world use. This involves integrating it into a system or application where it can receive new images, make predictions, and aid in the diagnosis of pneumonia.
|
36 |
+
|
37 |
+
|
38 |
+
|
39 |
+
- **Developed by:** [Nitin Kausik Remella](https://github.com/OkabeRintaro10)
|
40 |
+
- **Model type:** Sequential
|
41 |
+
- **Language(s):** Python
|
42 |
+
- **Finetuned from model:** ResNet50V2
|
43 |
+
|
44 |
+
### Model Sources [optional]
|
45 |
+
|
46 |
+
|
47 |
+
- **Repository:** [More Information Needed]
|
48 |
+
- **Paper [optional]:** [A modified deep convolutional neural network for detecting COVID-19 and pneumonia from chest X-ray images based on the concatenation of Xception and ResNet50V2
|
49 |
+
](https://pubmed.ncbi.nlm.nih.gov/32501424/)
|
50 |
+
- **Demo [optional]:** [More Information Needed]
|
51 |
+
|
52 |
+
## Uses
|
53 |
+
This tool is used to assist medical professional in cross-validation of the diagnosis
|
54 |
+
|
55 |
+
### Out-of-Scope Use
|
56 |
+
|
57 |
+
This model is in no form or way to replace an actual medical professional but only in assist them
|
58 |
+
|
59 |
+
|
60 |
+
## Bias, Risks, and Limitations
|
61 |
+
|
62 |
+
The model cant handle 4d images such as CT scans
|
63 |
+
|
64 |
+
## How to Get Started with the Model
|
65 |
+
|
66 |
+
```
|
67 |
+
import tensorflow as tf
|
68 |
+
from tensorflow import keras
|
69 |
+
from keras import models
|
70 |
+
model = load_model('/path/to/model')
|
71 |
+
model.evaluate('/path/to/image')
|
72 |
+
```
|
73 |
+
|
74 |
+
## Training Details
|
75 |
+
|
76 |
+
### Training Data
|
77 |
+
|
78 |
+
Downloading the dataset from [kaggle](https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia)
|
79 |
+
split the data into 3 parts
|
80 |
+
- train
|
81 |
+
- test
|
82 |
+
- val
|
83 |
+
|
84 |
+
code to split into 25% 75% split of training data
|
85 |
+
```
|
86 |
+
# Creating Val folder
|
87 |
+
os.chdir('datasets/chest_xray/chest_xray/')
|
88 |
+
if os.path.isdir('val/NORMAL') is False:
|
89 |
+
os.makedirs('val/NORMAL')
|
90 |
+
os.makedirs('val/PNEUMONIA')
|
91 |
+
|
92 |
+
# Moving Images from train folder to val folder
|
93 |
+
source = 'chest_xray/train/PNEUMONIA/'
|
94 |
+
dest = 'datasets/chest_xray/chest_xray/val/PNEUMONIA'
|
95 |
+
files = os.listdir(source)
|
96 |
+
np_of_files = len(files) // 25
|
97 |
+
for file_name in random.sample(files, np_of_files):
|
98 |
+
shutil.move(os.path.join(source, file_name), dest)
|
99 |
+
|
100 |
+
# Moving Normal Images from train folder to val folder
|
101 |
+
source = 'datasets/chest_xray/chest_xray/train/NORMAL/'
|
102 |
+
dest = 'datasets/chest_xray/chest_xray/val/NORMAL'
|
103 |
+
files = os.listdir(source)
|
104 |
+
np_of_files = len(files) // 25
|
105 |
+
for file_name in random.sample(files, np_of_files):
|
106 |
+
shutil.move(os.path.join(source, file_name), dest)
|
107 |
+
```
|
108 |
+
|
109 |
+
### Training Procedure
|
110 |
+
The training of the data requires ResNet50V2 to start as the base model and then using further layers to extract more information and to help in classification
|
111 |
+
|
112 |
+
#### Building the model
|
113 |
+
```
|
114 |
+
from keras.applications import VGG16, ResNet50V2
|
115 |
+
|
116 |
+
base_model = ResNet50V2(
|
117 |
+
include_top=False, input_shape=(224, 224, 3), weights="imagenet"
|
118 |
+
)
|
119 |
+
base_model.trainable = False
|
120 |
+
|
121 |
+
def CreateModel():
|
122 |
+
model = Sequential()
|
123 |
+
model.add(base_model)
|
124 |
+
# model.add(Conv2D(filters=32, kernel_size=3, strides=(2, 2)))
|
125 |
+
model.add(AveragePooling2D(pool_size=(2, 2), strides=2))
|
126 |
+
model.add(Flatten())
|
127 |
+
model.add(Dense(256, activation="relu"))
|
128 |
+
model.add(Dense(128, activation="relu"))
|
129 |
+
model.add(Dense(2, activation="softmax"))
|
130 |
+
model.compile(
|
131 |
+
loss="sparse_categorical_crossentropy",
|
132 |
+
optimizer=Adam(learning_rate=0.000035),
|
133 |
+
metrics=["sparse_categorical_accuracy"],
|
134 |
+
)
|
135 |
+
return model
|
136 |
+
```
|
137 |
+
#### Fitting the model
|
138 |
+
```
|
139 |
+
%%time
|
140 |
+
history = model.fit(
|
141 |
+
train_datagen,
|
142 |
+
steps_per_epoch = train_datagen.n//train_datagen.batch_size,
|
143 |
+
epochs = 10,
|
144 |
+
validation_data= val_datagen,
|
145 |
+
validation_steps= val_datagen.n//val_datagen.batch_size,
|
146 |
+
callbacks=[callback, reduceLR, checkpoint],
|
147 |
+
verbose = 1
|
148 |
+
)
|
149 |
+
```
|
150 |
+
#### Preprocessing
|
151 |
+
|
152 |
+
```
|
153 |
+
train_image_generator = ImageDataGenerator(
|
154 |
+
rotation_range= 0.5,
|
155 |
+
horizontal_flip=True,
|
156 |
+
vertical_flip=True,
|
157 |
+
zoom_range=0.5,
|
158 |
+
rescale= 1./255
|
159 |
+
)
|
160 |
+
|
161 |
+
train_datagen = train_image_generator.flow_from_directory(
|
162 |
+
train_dir,
|
163 |
+
target_size= (IMG_HEIGHT,IMG_WIDTH),
|
164 |
+
color_mode='rgb',
|
165 |
+
batch_size= batch_size,
|
166 |
+
class_mode= 'binary',
|
167 |
+
classes=['NORMAL','PNEUMONIA'],
|
168 |
+
shuffle= True,
|
169 |
+
seed= 42
|
170 |
+
)
|
171 |
+
```
|
172 |
+
set the value `shuffle=False` for val_datagen and test_datagen and change the value of `train_dir` to `val_dir` and 'test_dir' respectively
|
173 |
+
|
174 |
+
#### Training Hyperparameters
|
175 |
+
|
176 |
+
- **Training regime:**
|
177 |
+
- Using keras callbacks to reduce the load on the gpu/cpu by checking the model growth and early stopping or reducing the learning rate accordingly.
|
178 |
+
- Saving the best accuracy as a checkpoint to resume the training from
|
179 |
+
```
|
180 |
+
from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
|
181 |
+
|
182 |
+
callback = EarlyStopping(
|
183 |
+
monitor="val_loss", patience=6, restore_best_weights=True, min_delta=0.03, verbose=2
|
184 |
+
)
|
185 |
+
reduceLR = ReduceLROnPlateau(
|
186 |
+
monitor="val_loss",
|
187 |
+
factor=0.01,
|
188 |
+
patience=2,
|
189 |
+
min_lr=0.000035,
|
190 |
+
min_delta=0.01,
|
191 |
+
verbose=2,
|
192 |
+
)
|
193 |
+
checkpoint = ModelCheckpoint(
|
194 |
+
filepath=f"../Checkpoints/{{val_sparse_categorical_accuracy:.2f}}",
|
195 |
+
save_weights_only=True,
|
196 |
+
monitor="val_sparse_categorical_accuracy",
|
197 |
+
mode="max",
|
198 |
+
save_best_only=True,
|
199 |
+
verbose=2,
|
200 |
+
initial_value_threshold= baseline
|
201 |
+
)
|
202 |
+
```
|
203 |
+
|
204 |
+
#### Define Defaults
|
205 |
+
|
206 |
+
Batch_size = 32 *smaller batch size for weaker systems*
|
207 |
+
IMG_HEIGHTS = 224
|
208 |
+
IMG_WEIGHTS = 224
|
209 |
+
epochs = 10
|
210 |
+
train_dir = path/to/chest_xray/train
|
211 |
+
val_dir = path/to/chest_xray/val
|
212 |
+
test_dir = path/to/chest_xray/test
|
213 |
+
#### Metrics
|
214 |
+
|
215 |
+
Evaluation metrics used are recall and pricision
|
216 |
+
|
217 |
+
### Results
|
218 |
+
|
219 |
+
![image/png](https://cdn-uploads.huggingface.co/production/uploads/652917fd8297110ffe4e04ba/cml6Bd82tv3Rpu0bxBwQq.png)
|
220 |
+
|
221 |
+
#### Summary
|
222 |
+
|
223 |
+
The model is capable of detecting pneumonia with an accuracy of 91%
|