Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
3 |
+
from tensorflow.keras.models import Sequential
|
4 |
+
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from tensorflow.keras.applications import MobileNetV2
|
7 |
+
from tensorflow.keras.models import Sequential
|
8 |
+
from tensorflow.keras.layers import Dense, Dropout, GlobalAveragePooling2D
|
9 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
10 |
+
from sklearn.metrics import classification_report, roc_auc_score, roc_curve, auc
|
11 |
+
from sklearn.utils.class_weight import compute_class_weight
|
12 |
+
from sklearn.metrics import roc_auc_score
|
13 |
+
from tensorflow.keras.callbacks import EarlyStopping
|
14 |
+
from tensorflow.keras import regularizers
|
15 |
+
from tensorflow.keras.preprocessing import image
|
16 |
+
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
|
17 |
+
import numpy as np
|
18 |
+
import cv2
|
19 |
+
|
20 |
+
|
21 |
+
def predict_pneumonia(img_path, model, class_labels):
|
22 |
+
# Preprocess the image
|
23 |
+
img = image.load_img(img_path, target_size=(224, 224))
|
24 |
+
img_array = image.img_to_array(img)
|
25 |
+
img_array = np.expand_dims(img_array, axis=0)
|
26 |
+
img_array = img_array / 255.0
|
27 |
+
|
28 |
+
# Make a prediction
|
29 |
+
predictions = model.predict(img_array)
|
30 |
+
predicted_class_idx = np.argmax(predictions, axis=1)[0]
|
31 |
+
predicted_class = class_labels[predicted_class_idx]
|
32 |
+
print(f"Prediction: {predicted_class} (Confidence: {predictions[0][predicted_class_idx]:.2f})")
|
33 |
+
return predicted_class
|
34 |
+
|
35 |
+
|
36 |
+
class_labels = {0: 'Normal', 1: 'Pneumonia'}
|
37 |
+
|
38 |
+
import os
|
39 |
+
|
40 |
+
base_path = "/kaggle/input/chest-xray-pneumonia/chest_xray"
|
41 |
+
print(os.listdir(base_path))
|
42 |
+
|
43 |
+
train_dir = "/kaggle/input/chest-xray-pneumonia/chest_xray/train"
|
44 |
+
val_dir = "/kaggle/input/chest-xray-pneumonia/chest_xray/val"
|
45 |
+
test_dir = "/kaggle/input/chest-xray-pneumonia/chest_xray/test"
|
46 |
+
|
47 |
+
train_datagen = ImageDataGenerator(rescale=1.0/255, rotation_range=20, zoom_range=0.2, horizontal_flip=True,shear_range=0.2
|
48 |
+
)
|
49 |
+
val_datagen = ImageDataGenerator(rescale=1.0/255)
|
50 |
+
test_datagen = ImageDataGenerator(rescale=1.0/255)
|
51 |
+
|
52 |
+
train_generator = train_datagen.flow_from_directory(
|
53 |
+
train_dir, target_size=(224, 224), batch_size=32, class_mode='binary'
|
54 |
+
)
|
55 |
+
val_generator = val_datagen.flow_from_directory(
|
56 |
+
val_dir, target_size=(224, 224), batch_size=32, class_mode='binary'
|
57 |
+
)
|
58 |
+
test_generator = test_datagen.flow_from_directory(
|
59 |
+
test_dir, target_size=(224, 224), batch_size=32, class_mode='binary'
|
60 |
+
)
|
61 |
+
|
62 |
+
from tensorflow.keras.applications import MobileNetV2
|
63 |
+
|
64 |
+
|
65 |
+
base_model = MobileNetV2(weights='/kaggle/input/mobile-v2-1-0-224/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224_no_top.h5',
|
66 |
+
include_top=False, input_shape=(224, 224, 3))
|
67 |
+
base_model.trainable = False
|
68 |
+
|
69 |
+
from tensorflow.keras.models import Sequential
|
70 |
+
from tensorflow.keras.layers import Flatten, Dense, Dropout
|
71 |
+
|
72 |
+
|
73 |
+
model = Sequential([
|
74 |
+
base_model,
|
75 |
+
Flatten(),
|
76 |
+
Dense(128, activation='relu'),
|
77 |
+
Dropout(0.5),
|
78 |
+
Dense(1, activation='sigmoid')
|
79 |
+
])
|
80 |
+
|
81 |
+
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
82 |
+
|
83 |
+
import os
|
84 |
+
|
85 |
+
|
86 |
+
print("Train directory content:", os.listdir(train_dir))
|
87 |
+
print("Validation directory content:", os.listdir(val_dir))
|
88 |
+
print("Test directory content:", os.listdir(test_dir))
|
89 |
+
|
90 |
+
class_weights = compute_class_weight(
|
91 |
+
class_weight='balanced',
|
92 |
+
classes=np.unique(train_generator.classes),
|
93 |
+
y=train_generator.classes
|
94 |
+
)
|
95 |
+
|
96 |
+
|
97 |
+
class_weights = {i: weight for i, weight in enumerate(class_weights)}
|
98 |
+
|
99 |
+
|
100 |
+
if 1 in class_weights:
|
101 |
+
class_weights[1] = class_weights[1] * 2
|
102 |
+
|
103 |
+
|
104 |
+
history = model.fit(
|
105 |
+
train_generator,
|
106 |
+
steps_per_epoch=train_generator.samples // train_generator.batch_size,
|
107 |
+
validation_data=val_generator,
|
108 |
+
validation_steps=val_generator.samples // val_generator.batch_size,
|
109 |
+
epochs=10, #
|
110 |
+
class_weight=class_weights
|
111 |
+
)
|
112 |
+
|
113 |
+
test_loss, test_acc = model.evaluate(test_generator)
|
114 |
+
print(f"Test Accuracy: {test_acc:.2f}")
|
115 |
+
|
116 |
+
plt.figure(figsize=(10, 5))
|
117 |
+
plt.subplot(1, 2, 1)
|
118 |
+
plt.plot(history.history['accuracy'], label='Train Accuracy')
|
119 |
+
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
|
120 |
+
plt.legend()
|
121 |
+
plt.title('Accuracy')
|
122 |
+
|
123 |
+
plt.subplot(1, 2, 2)
|
124 |
+
plt.plot(history.history['loss'], label='Train Loss')
|
125 |
+
plt.plot(history.history['val_loss'], label='Validation Loss')
|
126 |
+
plt.legend()
|
127 |
+
plt.title('Loss')
|
128 |
+
|
129 |
+
plt.show()
|
130 |
+
|
131 |
+
true_labels = test_generator.classes
|
132 |
+
predicted_probs = model.predict(test_generator, steps=test_generator.samples // test_generator.batch_size + 1)
|
133 |
+
predicted_labels = np.argmax(predicted_probs, axis=1)
|
134 |
+
|
135 |
+
import numpy as np
|
136 |
+
from sklearn.metrics import classification_report
|
137 |
+
|
138 |
+
|
139 |
+
test_generator.reset()
|
140 |
+
predictions = model.predict(test_generator, steps=test_generator.samples // test_generator.batch_size + 1)
|
141 |
+
|
142 |
+
|
143 |
+
predicted_labels = (predictions > 0.5).astype(int)
|
144 |
+
|
145 |
+
|
146 |
+
true_labels = test_generator.classes
|
147 |
+
|
148 |
+
# Step 3: Classification report
|
149 |
+
report = classification_report(true_labels, predicted_labels, target_names=['Normal', 'Pneumonia'])
|
150 |
+
|
151 |
+
print("Classification Report:")
|
152 |
+
print(report)
|
153 |
+
|
154 |
+
true_labels = test_generator.classes
|
155 |
+
|
156 |
+
|
157 |
+
predicted_probs = model.predict(test_generator)
|
158 |
+
|
159 |
+
|
160 |
+
roc_auc = roc_auc_score(true_labels, predicted_probs)
|
161 |
+
print(f"ROC-AUC Score: {roc_auc:.2f}")
|
162 |
+
|
163 |
+
true_labels = test_generator.classes
|
164 |
+
|
165 |
+
|
166 |
+
predicted_probs = model.predict(test_generator)
|
167 |
+
|
168 |
+
|
169 |
+
|
170 |
+
fpr, tpr, _ = roc_curve(true_labels, predicted_probs)
|
171 |
+
|
172 |
+
|
173 |
+
roc_auc = auc(fpr, tpr)
|
174 |
+
|
175 |
+
|
176 |
+
plt.figure()
|
177 |
+
plt.plot(fpr, tpr, color='darkorange', lw=2, label=f"ROC curve (area = {roc_auc:.2f})")
|
178 |
+
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
|
179 |
+
plt.xlabel('False Positive Rate')
|
180 |
+
plt.ylabel('True Positive Rate')
|
181 |
+
plt.title('Receiver Operating Characteristic')
|
182 |
+
plt.legend(loc="lower right")
|
183 |
+
plt.show()
|
184 |
+
|
185 |
+
img_path = '/kaggle/input/chest-xray-pneumonia/chest_xray/val/PNEUMONIA/person1951_bacteria_4882.jpeg' # Path to the X-ray image
|
186 |
+
predicted_class = predict_pneumonia(img_path, model, class_labels)
|
187 |
+
print(f"The X-ray image is classified as: {predicted_class}")
|