Upload 6 files
Browse files
Medical-Image-Classification-ChestXray_Code.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
plots/confusion_matrix.png
ADDED
|
plots/training_performance.png
ADDED
|
pneumonia_pipeline_kfold.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb9424ab8225e85da7552536b27460e00e45d71c5cd1a0847ee31e2beb3dcfa0
|
| 3 |
+
size 28442750
|
reports/classification_report.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Pneumonia Prediction Model - Final Classification Report (K-Fold Averaged)
|
| 2 |
+
======================================================================
|
| 3 |
+
precision recall f1-score support
|
| 4 |
+
NORMAL 0.953021 0.691453 0.801231 234.000000
|
| 5 |
+
PNEUMONIA 0.841135 0.979487 0.905022 390.000000
|
| 6 |
+
accuracy 0.871474 0.871474 0.871474 0.871474
|
| 7 |
+
macro avg 0.897078 0.835470 0.853127 624.000000
|
| 8 |
+
weighted avg 0.883092 0.871474 0.866100 624.000000
|
ui_components/gradio_interface.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Required imports for the Gradio interface
|
| 3 |
+
import os, random, joblib, io
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import seaborn as sns
|
| 8 |
+
from tqdm.notebook import tqdm
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.optim as optim
|
| 14 |
+
from torch.utils.data import DataLoader, Subset
|
| 15 |
+
from torchvision import datasets, transforms, models
|
| 16 |
+
|
| 17 |
+
import optuna
|
| 18 |
+
from pytorch_grad_cam import GradCAM
|
| 19 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
| 20 |
+
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
from sklearn.model_selection import StratifiedKFold
|
| 24 |
+
from sklearn.metrics import classification_report, confusion_matrix
|
| 25 |
+
|
| 26 |
+
# Define device, IMG_SIZE, and get_model function if not globally available
|
| 27 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 28 |
+
IMG_SIZE = (224, 224) # Assuming this is the image size used for preprocessing
|
| 29 |
+
|
| 30 |
+
def get_model(model_name, pretrained=True):
|
| 31 |
+
weights = 'DEFAULT' if pretrained else None
|
| 32 |
+
if model_name == "resnet50":
|
| 33 |
+
model = models.resnet50(weights=weights)
|
| 34 |
+
model.fc = nn.Linear(model.fc.in_features, 2)
|
| 35 |
+
elif model_name == "efficientnet_b0":
|
| 36 |
+
model = models.efficientnet_b0(weights=weights)
|
| 37 |
+
model.classifier[1] = nn.Linear(model.classifier[1].in_features, 2)
|
| 38 |
+
elif model_name == "densenet121":
|
| 39 |
+
model = models.densenet121(weights=weights)
|
| 40 |
+
model.classifier = nn.Linear(model.classifier.in_features, 2)
|
| 41 |
+
else:
|
| 42 |
+
raise ValueError("Model name not recognized")
|
| 43 |
+
return model
|
| 44 |
+
|
| 45 |
+
# Define the path where your model pipeline is saved
|
| 46 |
+
MODEL_PIPELINE_PATH = "/content/drive/MyDrive/pneumonia_pipeline_kfold.pth"
|
| 47 |
+
|
| 48 |
+
# 1. تحميل الأنبوب المتكامل من المسار المحدد
|
| 49 |
+
pipeline = torch.load(MODEL_PIPELINE_PATH, map_location=device, weights_only=False)
|
| 50 |
+
|
| 51 |
+
# 2. استخراج المكونات من الأنبوب
|
| 52 |
+
model_name = pipeline['model_name']
|
| 53 |
+
class_names = pipeline['class_names']
|
| 54 |
+
preprocess = pipeline['transforms']
|
| 55 |
+
|
| 56 |
+
# 3. بناء الموديل وتحميل الأوزان
|
| 57 |
+
model = get_model(model_name, pretrained=False).to(device)
|
| 58 |
+
model.load_state_dict(pipeline['model_state_dict'])
|
| 59 |
+
model.eval()
|
| 60 |
+
|
| 61 |
+
# 4. تحديد طبقة الـ CAM تلقائياً
|
| 62 |
+
if model_name == "resnet50":
|
| 63 |
+
target_layers = [model.layer4[-1]]
|
| 64 |
+
elif model_name == "efficientnet_b0":
|
| 65 |
+
target_layers = [model.features[-1][0]]
|
| 66 |
+
elif model_name == "densenet121":
|
| 67 |
+
target_layers = [model.features.norm5]
|
| 68 |
+
|
| 69 |
+
cam = GradCAM(model=model, target_layers=target_layers)
|
| 70 |
+
|
| 71 |
+
def predict_and_explain(image):
|
| 72 |
+
if image is None: return None, None
|
| 73 |
+
img_rgb = image.convert("RGB")
|
| 74 |
+
input_tensor = preprocess(img_rgb).unsqueeze(0).to(device)
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
output = model(input_tensor)
|
| 77 |
+
probs = torch.softmax(output, dim=1)[0]
|
| 78 |
+
confidences = {class_names[i]: float(probs[i]) for i in range(len(class_names))}
|
| 79 |
+
grayscale_cam = cam(input_tensor=input_tensor, targets=[ClassifierOutputTarget(probs.argmax().item())], aug_smooth=True, eigen_smooth=True)[0, :]
|
| 80 |
+
img_np = np.array(img_rgb.resize(IMG_SIZE)) / 255.0
|
| 81 |
+
cam_image = show_cam_on_image(img_np, grayscale_cam, use_rgb=True)
|
| 82 |
+
return confidences, cam_image
|
| 83 |
+
|
| 84 |
+
# إطلاق واجهة Gradio مع إضافة أسماء الفريق في الوصف
|
| 85 |
+
gr.Interface(
|
| 86 |
+
fn=predict_and_explain,
|
| 87 |
+
inputs=gr.Image(type="pil", label="ارفع صورة الأشعة هنا"),
|
| 88 |
+
outputs=[gr.Label(label="التشخيص"), gr.Image(label="التفسير البصري")],
|
| 89 |
+
title=f"نظام تشخيص الالتهاب الرئوي ({model_name})",
|
| 90 |
+
description="""
|
| 91 |
+
### 🦅 تم تطوير وتدريب هذا النموذج بواسطة فريق النسور:
|
| 92 |
+
* **المهندس عبدالله الجحافي**
|
| 93 |
+
* **المهندس أيمن الوهبي**
|
| 94 |
+
* **المهندس واثق المريسي**
|
| 95 |
+
* **المهندس علي المحرابي**
|
| 96 |
+
""",
|
| 97 |
+
theme=gr.themes.Soft()
|
| 98 |
+
).launch(debug=True, share=True)
|