-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSource_code.py
More file actions
223 lines (144 loc) · 5 KB
/
Copy pathSource_code.py
File metadata and controls
223 lines (144 loc) · 5 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
import json
# Load the notebook
with open("/mnt/data/Malaria.ipynb", "r", encoding="utf-8") as f:
notebook = json.load(f)
# Extract all code cells
code_cells = []
for cell in notebook.get("cells", []):
if cell.get("cell_type") == "code":
code_cells.append("".join(cell.get("source", [])))
code_output = "\n\n# -----------------------------\n\n".join(code_cells)
code_output[:5000]
DATA_DIR = "Malaria_Dataset"
# -----------------------------
import os
Parasitized_DIR = os.path.sep.join([DATA_DIR , "Parasitized"])
Unifected_DIR = os.path.sep.join([DATA_DIR , "Uninfected"])
# -----------------------------
len(os.listdir(Parasitized_DIR)), len(os.listdir(Unifected_DIR))
# -----------------------------
os.listdir(Parasitized_DIR)[:5]
# -----------------------------
os.listdir(Unifected_DIR)[:5]
# -----------------------------
import matplotlib.pyplot as plt
# -----------------------------
import tensorflow as tf
# -----------------------------
from tensorflow.keras.utils import load_img , img_to_array
# -----------------------------
img = load_img(os.path.join(Parasitized_DIR , os.listdir(Parasitized_DIR)[0]) , target_size=(224 , 224))
plt.imshow(img)
# -----------------------------
plt.axis("off")
# -----------------------------
img
# -----------------------------
type(img)
# -----------------------------
plt.figure(figsize=(12 , 8))
parasitized_imgs = os.listdir(Parasitized_DIR)[:3]
uninfected_imgs = os.listdir(Unifected_DIR)[:3]
for i , img_name in enumerate(parasitized_imgs):
img = load_img(os.path.join(Parasitized_DIR , img_name ) , target_size=(128 , 128))
plt.subplot(2, 3, i+1)
plt.imshow(img)
plt.title("Parasitized")
plt.axis("off")
for i , img_name in enumerate(uninfected_imgs):
img = load_img(os.path.join(Unifected_DIR , img_name) , target_size=(128 , 128))
plt.subplot(2, 3, i+4)
plt.imshow(img)
plt.title("Uninfected")
plt.axis("off")
plt.tight_layout()
plt.show()
# -----------------------------
from sklearn.model_selection import train_test_split
import numpy as np
# -----------------------------
data = []
labels = []
# - Parasitized
for name in os.listdir(Parasitized_DIR):
img_path = os.path.join(Parasitized_DIR , name)
img = load_img(img_path , target_size=(64 , 64))
img_arr = img_to_array(img)
data.append(img_arr)
labels.append(1)
# - Uninfected
for name in os.listdir(Unifected_DIR):
img_path = os.path.join(Unifected_DIR , name)
img = load_img(img_path , target_size=(64 , 64))
img_arr = img_to_array(img)
data.append(img_arr)
labels.append(0)
# -----------------------------
data = np.array(data , dtype="float32") / 255.0
labels = np.array(labels)
# -----------------------------
# Preparing Train and Test Data
X_train , X_test , y_train , y_test = train_test_split(data , labels , test_size=0.2 , random_state=42)
# -----------------------------
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D , MaxPooling2D , Flatten , Dense , Dropout
# -----------------------------
# Building CNN Model
model = Sequential([
Conv2D(32 , (3,3) , activation="relu" , input_shape=(64 , 64 , 3)),
MaxPooling2D((2,2)),
Conv2D(64 , (3,3) , activation="relu"),
MaxPooling2D((2,2)),
Flatten(),
Dense(128 , activation="relu"),
Dropout(0.3),
Dense(1 , activation="sigmoid")
])
# -----------------------------
model.compile(optimizer="adam" , loss="binary_crossentropy" , metrics=["accuracy"])
# -----------------------------
history = model.fit(X_train , y_train , validation_split=0.2 , epochs=7 , batch_size=32)
# -----------------------------
loss , accuracy = model.evaluate(X_test , y_test)
# -----------------------------
print("Test Loss:" , loss)
print("Test Accuracy:" , accuracy)
# -----------------------------
# Plot Accuracy
plt.figure(figsize=(10 , 4))
plt.plot(history.history["accuracy"], label="train_acc")
plt.plot(history.history["val_accuracy"], label="val_acc")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.title("Training and Validation Accuracy")
plt.legend()
plt.show()
# -----------------------------
# Plot Loss
plt.figure(figsize=(10 , 4))
plt.plot(history.history["loss"], label="train_loss")
plt.plot(history.history["val_loss"], label="val_loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Training and Validation Loss")
plt.legend()
plt.show()
# -----------------------------
from sklearn.metrics import classification_report , confusion_matrix
preds = (model.predict(X_test) > 0.5).astype("int32")
print(classification_report(y_test , preds))
# -----------------------------
cm = confusion_matrix(y_test , preds)
cm
# -----------------------------
import seaborn as sns
plt.figure(figsize=(5 , 4))
sns.heatmap(cm , annot=True , fmt="d" , cmap="Blues")
plt.title("Confusion Matrix")
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.show()
# -----------------------------
model.save("malaria_cnn_model.h5")
# -----------------------------
print("Model Saved Successfully")