Spaces:
Sleeping
Sleeping
fixed the always one class prediction issue
Browse files- .gitignore +8 -0
- __pycache__/_debug.cpython-311.pyc +0 -0
- __pycache__/app.cpython-311.pyc +0 -0
- __pycache__/base.cpython-311.pyc +0 -0
- __pycache__/defs.cpython-311.pyc +0 -0
- __pycache__/modelbuilder.cpython-311.pyc +0 -0
- app.py +39 -92
- base.py +244 -0
- modelbuilder.py +3 -1
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# folders in the root directory
|
| 2 |
+
/models/*
|
| 3 |
+
/data/*
|
| 4 |
+
|
| 5 |
+
# files in the root directory
|
| 6 |
+
_app.py
|
| 7 |
+
_debug.py
|
| 8 |
+
_howto.ipynb
|
__pycache__/_debug.cpython-311.pyc
ADDED
|
Binary file (410 Bytes). View file
|
|
|
__pycache__/app.cpython-311.pyc
CHANGED
|
Binary files a/__pycache__/app.cpython-311.pyc and b/__pycache__/app.cpython-311.pyc differ
|
|
|
__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (10 kB). View file
|
|
|
__pycache__/defs.cpython-311.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
__pycache__/modelbuilder.cpython-311.pyc
ADDED
|
Binary file (15.6 kB). View file
|
|
|
app.py
CHANGED
|
@@ -1,109 +1,56 @@
|
|
| 1 |
-
|
| 2 |
-
import tensorflow as tf
|
| 3 |
-
from huggingface_hub import hf_hub_download
|
| 4 |
-
from datasets import load_dataset
|
| 5 |
-
from PIL import Image
|
| 6 |
-
import numpy as np
|
| 7 |
-
from tensorflow.keras.preprocessing.image import img_to_array
|
| 8 |
-
from modelbuilder import capsnet_custom_objects
|
| 9 |
|
| 10 |
-
#-------CONSTANTS-------#
|
| 11 |
-
TARGET_SIZE = (256, 256) # target size for masked images
|
| 12 |
-
CLASS_LABELS = ["COVID", "Lung_Opacity", "Normal", "Viral Pneumonia"]
|
| 13 |
# ------------------------------------------------------------
|
| 14 |
-
#
|
| 15 |
-
# capsnet for disease classification and GAN for lung segmentation/masking
|
| 16 |
# ------------------------------------------------------------
|
| 17 |
-
gan_model_path = hf_hub_download(
|
| 18 |
-
repo_id="valste/lung-segmentation-gan",
|
| 19 |
-
filename="model.keras"
|
| 20 |
-
)
|
| 21 |
-
model_gan = tf.keras.models.load_model(gan_model_path, compile=False)
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
# 2️⃣ Load sample X-ray images from your dataset
|
| 30 |
-
# ------------------------------------------------------------
|
| 31 |
-
dataset = load_dataset("valste/lung-disease-xrays", data_dir="external_xrays_299x299", split="train")
|
| 32 |
-
|
| 33 |
-
demo_images = []
|
| 34 |
-
for example in dataset:
|
| 35 |
-
if "image" in example:
|
| 36 |
-
img = example["image"]
|
| 37 |
-
demo_images.append(img)
|
| 38 |
-
elif "path" in example: # If dataset stores file paths
|
| 39 |
-
img = Image.open(example["path"])
|
| 40 |
-
demo_images.append(img)
|
| 41 |
-
|
| 42 |
-
# ------------------------------------------------------------
|
| 43 |
-
# 3️⃣ Define preprocessing and inference function
|
| 44 |
-
# ------------------------------------------------------------
|
| 45 |
-
def preprocess_image(img: Image.Image):
|
| 46 |
-
# --- 1) Prepare grayscale image for GAN (1 channel) ---
|
| 47 |
-
img = img.convert("L") # force grayscale; result shape when array: (H, W)
|
| 48 |
-
img = img.resize(TARGET_SIZE, Image.BILINEAR) # resize to target: (width, height)
|
| 49 |
-
|
| 50 |
-
img_array = np.array(img, dtype=np.float32) / 255.0 # to float32 in [0,1], shape: (H, W)
|
| 51 |
-
|
| 52 |
-
gan_input = np.expand_dims(img_array, axis=-1) # add channel dim for GAN -> (H, W, 1)
|
| 53 |
-
gan_input = np.expand_dims(gan_input, axis=0) # add batch dim for GAN -> (1, H, W, 1)
|
| 54 |
-
|
| 55 |
-
# --- 2) Run segmentation GAN to get lung mask ---
|
| 56 |
-
prediction = model_gan.predict(gan_input) # expected output e.g. (1, H, W, 1)
|
| 57 |
-
|
| 58 |
-
lung_prob = prediction[0, :, :, 0] # remove batch + channel -> prob map, shape: (H, W)
|
| 59 |
-
mask = (lung_prob > 0.5).astype(np.float32) # threshold to binary mask (0 or 1), shape: (H, W)
|
| 60 |
-
|
| 61 |
-
# --- 3) Apply mask on grayscale image ---
|
| 62 |
-
masked_gray = img_array * mask # keep lung region, zero other pixels, shape: (H, W)
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
|
| 67 |
-
|
| 68 |
-
x = np.expand_dims(masked_rgb, axis=0).astype(np.float32) # model input: (1, H, W, 3)
|
| 69 |
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
# ------------------------------------------------------------
|
| 87 |
-
# 4️⃣ Gradio interface
|
| 88 |
-
# ------------------------------------------------------------
|
| 89 |
-
demo = gr.Interface(
|
| 90 |
-
fn=predict,
|
| 91 |
-
inputs=gr.Image(type="pil", label="Upload Chest X-ray"),
|
| 92 |
-
outputs=[
|
| 93 |
-
gr.Label(num_top_classes=4, label="Prediction"),
|
| 94 |
-
gr.Image(type="numpy", label="Masked Lung Region"),
|
| 95 |
-
],
|
| 96 |
-
title="CapsNet 4-Class Lung Disease Classifier",
|
| 97 |
-
description=(
|
| 98 |
-
"This demo uses a Capsule Network trained to classify chest X-rays into "
|
| 99 |
-
"COVID-19, Lung Opacity, Normal, and Viral Pneumonia. "
|
| 100 |
-
"The masked image shows only the segmented lung region used for classification."
|
| 101 |
-
),
|
| 102 |
-
examples=demo_images
|
| 103 |
-
)
|
| 104 |
|
| 105 |
# ------------------------------------------------------------
|
| 106 |
# 5️⃣ Launch the app
|
| 107 |
# ------------------------------------------------------------
|
| 108 |
if __name__ == "__main__":
|
| 109 |
-
demo.launch()
|
|
|
|
| 1 |
+
from base import *
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
|
|
|
|
|
|
|
|
|
| 3 |
# ------------------------------------------------------------
|
| 4 |
+
# 3️⃣ Define calback function for Gradio Interface
|
|
|
|
| 5 |
# ------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
def _predict_and_display(img_path: str):
|
| 8 |
+
if not img_path:
|
| 9 |
+
# return empty values to clear outputs
|
| 10 |
+
return {}, None
|
| 11 |
+
filename_out, masked_vis, scores = predict(img_path)
|
| 12 |
+
return scores, masked_vis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
def _clear_outputs():
|
| 15 |
+
return gr.update(value=None), gr.update(value=None)
|
| 16 |
|
| 17 |
+
default_image_label = "Select or upload an image to classify" #default label for img_input
|
|
|
|
| 18 |
|
| 19 |
+
def _change_input_label(img_path: str | None, default_image_label=default_image_label) -> gr.update:
|
| 20 |
+
if img_path:
|
| 21 |
+
fname = os.path.basename(img_path)
|
| 22 |
+
return gr.update(label= f"Image to classify: {fname}")
|
| 23 |
+
return gr.update(label=default_image_label)
|
| 24 |
|
| 25 |
+
# ------------------------------------------------------------
|
| 26 |
|
| 27 |
|
| 28 |
+
with gr.Blocks() as demo:
|
| 29 |
+
img_input = gr.Image(type="filepath", label=_change_input_label(None)["label"])
|
| 30 |
+
out_mask = gr.Image(type="numpy", label="Masked Lung Region")
|
| 31 |
+
out_label = gr.Label(label="Prediction")
|
| 32 |
+
|
| 33 |
+
examples = gr.Examples(
|
| 34 |
+
label="Example X-rays",
|
| 35 |
+
examples=img_paths[:], # each element is a list of one string (path): [[path1], [path2], ... ]
|
| 36 |
+
example_labels=img_names[:],
|
| 37 |
+
inputs=img_input,
|
| 38 |
+
cache_examples=False,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
|
| 42 |
+
# event order of img_input:
|
| 43 |
+
# * for uploads: select() → upload() → change()
|
| 44 |
+
# * for examples clicks: select() → change()
|
| 45 |
+
#img_input.select(_change_input_label, inputs=img_input, outputs=img_input)
|
| 46 |
+
img_input.change(_change_input_label, inputs=img_input, outputs=img_input)
|
| 47 |
+
img_input.change(_clear_outputs, inputs=None, outputs=[out_label, out_mask], queue=False)
|
| 48 |
+
img_input.change(_predict_and_display, inputs=img_input, outputs=[out_label, out_mask])
|
| 49 |
+
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# ------------------------------------------------------------
|
| 53 |
# 5️⃣ Launch the app
|
| 54 |
# ------------------------------------------------------------
|
| 55 |
if __name__ == "__main__":
|
| 56 |
+
demo.launch(debug=True, server_name="127.0.0.1", server_port=7860)
|
base.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datasets import load_dataset
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
from tensorflow.keras.preprocessing.image import img_to_array
|
| 5 |
+
from huggingface_hub import hf_hub_download
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import os
|
| 8 |
+
import numpy as np
|
| 9 |
+
from modelbuilder import capsnet_custom_objects
|
| 10 |
+
from defs import class_to_disease_map
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from typing import Mapping
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# ------------------------------------------------------------
|
| 17 |
+
# Determine the running environment: local machine or huggingface spaces
|
| 18 |
+
# ------------------------------------------------------------
|
| 19 |
+
def running_in_spaces() -> bool:
|
| 20 |
+
"""Return True if app is running inside Hugging Face Spaces."""
|
| 21 |
+
return (
|
| 22 |
+
os.environ.get("SPACE_ID") is not None or os.environ.get("SYSTEM") == "spaces"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
is_spaces = running_in_spaces()
|
| 26 |
+
|
| 27 |
+
if is_spaces:
|
| 28 |
+
print(f"Running in Hugging Face Spaces environment.")
|
| 29 |
+
else:
|
| 30 |
+
print(f"Running on local machine environment:{os.environ.get('COMPUTERNAME','Unknown')}")
|
| 31 |
+
|
| 32 |
+
# -------CONSTANTS-------#
|
| 33 |
+
TARGET_SIZE = (256, 256) # target size for masked images
|
| 34 |
+
|
| 35 |
+
# ------------------------------------------------------------
|
| 36 |
+
# 1️⃣ Load the models from Hugging Face Hub
|
| 37 |
+
# capsnet for disease classification and GAN for lung segmentation/masking
|
| 38 |
+
# ------------------------------------------------------------
|
| 39 |
+
gan_model_path = None
|
| 40 |
+
capsnet_model_path = None
|
| 41 |
+
dataset = None
|
| 42 |
+
data_dir = None
|
| 43 |
+
|
| 44 |
+
if is_spaces:
|
| 45 |
+
# huggingface datasets is preinstalled in Spaces
|
| 46 |
+
|
| 47 |
+
data_dir = "external_xrays_299x299"
|
| 48 |
+
dataset = load_dataset(
|
| 49 |
+
"valste/lung-disease-xrays", data_dir=data_dir, split="train"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
gan_model_path = hf_hub_download(
|
| 53 |
+
repo_id="valste/lung-segmentation-gan", filename="model.keras"
|
| 54 |
+
)
|
| 55 |
+
capsnet_model_path = hf_hub_download(
|
| 56 |
+
repo_id="valste/capsnet-4class-lung-disease-classifier", filename="model.keras"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
else:
|
| 60 |
+
# local machine
|
| 61 |
+
capsnet_model_path = os.path.join(
|
| 62 |
+
".", "models", "capsnet-4class-lung-disease-classifier", "model.keras"
|
| 63 |
+
)
|
| 64 |
+
#capsnet_knl5_path = Path(r"C:\Users\User\VS_CODE_WORKSPACES\DataScience\ds_aug24_lung_desease_classification\mlruns_capsnet\923962217935764323\af22305e09b44dd686b2405b0f6c01d5\artifacts\model\data\model.keras") #conv2d_1 krnl=5
|
| 65 |
+
gan_model_path = os.path.join(".", "models", "lung-segmentation-gan", "model.keras")
|
| 66 |
+
data_dir = os.path.join(".", "data", "external_xrays_299x299")
|
| 67 |
+
dataset = load_dataset(
|
| 68 |
+
"imagefolder", data_dir=data_dir, split="train" # path to your local folder
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
model_gan = tf.keras.models.load_model(gan_model_path, compile=False)
|
| 72 |
+
model_capsnet = tf.keras.models.load_model(
|
| 73 |
+
capsnet_model_path,
|
| 74 |
+
#capsnet_knl5_path,
|
| 75 |
+
custom_objects=capsnet_custom_objects, compile=False
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------
|
| 79 |
+
# 2️⃣ Load sample X-ray images from your dataset
|
| 80 |
+
# ------------------------------------------------------------
|
| 81 |
+
imgs=[]
|
| 82 |
+
img_paths = []
|
| 83 |
+
img_names = []
|
| 84 |
+
|
| 85 |
+
class DemoException(Exception):
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
for ex in dataset:
|
| 90 |
+
if "image" in ex:
|
| 91 |
+
imgs.append(ex["image"])
|
| 92 |
+
path = getattr(ex["image"], "filename", None) # string
|
| 93 |
+
if path:
|
| 94 |
+
img_paths.append([path])
|
| 95 |
+
img_names.append(os.path.basename(path))
|
| 96 |
+
else:
|
| 97 |
+
raise DemoException("Missing path")
|
| 98 |
+
else:
|
| 99 |
+
raise DemoException("Dataset examples do not contain 'image' field.")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ------------------------------------------------------------
|
| 103 |
+
# 3️⃣ Define preprocessing and inference function
|
| 104 |
+
# ------------------------------------------------------------
|
| 105 |
+
|
| 106 |
+
def create_binary_mask(img: Image.Image, seg_model=model_gan, target_size=TARGET_SIZE) -> np.ndarray:
|
| 107 |
+
"""Create a binary mask from a PIL Image."""
|
| 108 |
+
# --- 1) Grayscale base image ---
|
| 109 |
+
img_gray = img.convert("L")
|
| 110 |
+
#print(f" image size: {img_gray.size}")
|
| 111 |
+
img_gray = img_gray.resize(target_size, Image.BILINEAR)
|
| 112 |
+
#print(f" image rescaled size: {img_gray.size}")
|
| 113 |
+
|
| 114 |
+
# float32 in [0, 1]
|
| 115 |
+
gray_array = np.array(img_gray, dtype=np.float32) / 255.0
|
| 116 |
+
#print(f" gray_array shape: {gray_array.shape}")
|
| 117 |
+
|
| 118 |
+
# --- 2) GAN input ---
|
| 119 |
+
gan_input = gray_array[..., np.newaxis] # (H, W, 1)
|
| 120 |
+
gan_input = np.expand_dims(gan_input, axis=0) # (1, H, W, 1)
|
| 121 |
+
#print(f" GAN input shape (before prediction): {gan_input.shape}")
|
| 122 |
+
# --- 3) Run segmentation GAN ---
|
| 123 |
+
prediction = seg_model.predict(gan_input)
|
| 124 |
+
mask = (prediction[0, :, :, 0] > 0.5).astype(np.uint8) * 255 # take first batch & channel, threshold at 0.5, get 0/255 mask
|
| 125 |
+
mask = (mask > 127).astype(np.uint8) # ensure strictly binary mask with values 0 or 1
|
| 126 |
+
|
| 127 |
+
return mask
|
| 128 |
+
|
| 129 |
+
def create_masked_img(img: Image.Image, seg_model=model_gan, target_size=TARGET_SIZE) -> tuple[tf.Tensor, np.ndarray, np.ndarray]:
|
| 130 |
+
|
| 131 |
+
"""Create masked image tensor for CapsNet input from a PIL Image."""
|
| 132 |
+
img = img.resize(target_size, Image.BILINEAR)
|
| 133 |
+
mask = create_binary_mask(img, seg_model=seg_model, target_size=target_size) # (H, W), values in {0, 1}
|
| 134 |
+
img_arr = img_to_array(img).astype(np.float32) # (H,W,3)
|
| 135 |
+
|
| 136 |
+
# --- 4) Apply mask ---
|
| 137 |
+
masked = img_arr * mask[..., None] # still float # (H,W,3)
|
| 138 |
+
masked = masked.astype(np.uint8) # back to 0–255 image # (H,W,3)
|
| 139 |
+
|
| 140 |
+
# --- 5) Prepare input for CapsNet ---
|
| 141 |
+
# masked_3ch = np.repeat(masked[..., np.newaxis], 3, axis=-1) # (H,W,3)
|
| 142 |
+
|
| 143 |
+
x = tf.convert_to_tensor(
|
| 144 |
+
np.expand_dims(masked, axis=0), # (1, H, W, 3)
|
| 145 |
+
dtype=tf.float32, # ✅ float32, not uint8
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return x, masked, mask
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def to_probabilities(predictions, model_type: str = "capsnet"):
|
| 153 |
+
"""
|
| 154 |
+
Convert model outputs to class probabilities.
|
| 155 |
+
|
| 156 |
+
Parameters
|
| 157 |
+
----------
|
| 158 |
+
dis_confs : np.ndarray
|
| 159 |
+
Raw model outputs.
|
| 160 |
+
For CapsNet this is expected to be of shape (n, n_classes, 1)
|
| 161 |
+
where the last dim is just a singleton and dis_confs need normalization means the sum along class axis is not equal to 1.
|
| 162 |
+
model_type : str
|
| 163 |
+
"capsnet" → normalize along class axis and squeeze last dim.
|
| 164 |
+
anything else → return dis_confs unchanged as np.ndarray.
|
| 165 |
+
|
| 166 |
+
Returns
|
| 167 |
+
-------
|
| 168 |
+
np.ndarray
|
| 169 |
+
Probabilities of shape (n, n_classes) for capsnet,
|
| 170 |
+
or np.asarray(dis_confs) for other models.
|
| 171 |
+
"""
|
| 172 |
+
predictions = np.asarray(predictions)
|
| 173 |
+
|
| 174 |
+
if model_type != "capsnet":
|
| 175 |
+
# Assume other models (e.g. softmax CNN) already return probs.
|
| 176 |
+
return predictions
|
| 177 |
+
|
| 178 |
+
# --- CapsNet branch ---
|
| 179 |
+
# Ensure we have a 3D tensor with the singleton last dimension
|
| 180 |
+
if predictions.ndim == 2:
|
| 181 |
+
# (n, n_classes) -> (n, n_classes, 1)
|
| 182 |
+
predictions = predictions[..., np.newaxis]
|
| 183 |
+
elif predictions.ndim != 3:
|
| 184 |
+
raise ValueError(f"Expected dis_confs to have 2 or 3 dims for capsnet, got shape {predictions.shape}")
|
| 185 |
+
|
| 186 |
+
# Normalize along the class axis (axis=1)
|
| 187 |
+
sums = np.sum(predictions, axis=1, keepdims=True)
|
| 188 |
+
|
| 189 |
+
# Avoid division by zero just in case
|
| 190 |
+
eps = 1e-12
|
| 191 |
+
sums = np.where(sums == 0, eps, sums)
|
| 192 |
+
|
| 193 |
+
predictions = predictions / sums
|
| 194 |
+
|
| 195 |
+
# Remove the last singleton dim: (n, n_classes, 1) -> (n, n_classes)
|
| 196 |
+
predictions = predictions.squeeze(-1)
|
| 197 |
+
|
| 198 |
+
return predictions
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def map_probabilities_to_classes(probabilities, class_map):
|
| 203 |
+
"""
|
| 204 |
+
Map a probability vector to a dict {class_name: probability}.
|
| 205 |
+
|
| 206 |
+
Parameters
|
| 207 |
+
----------
|
| 208 |
+
probabilities : array-like
|
| 209 |
+
Shape (n_classes,) – probabilities after softmax or normalization.
|
| 210 |
+
class_map : dict
|
| 211 |
+
Mapping from class index → class name.
|
| 212 |
+
|
| 213 |
+
Returns
|
| 214 |
+
-------
|
| 215 |
+
dict
|
| 216 |
+
{class_name: float(probability)} sorted by descending probability.
|
| 217 |
+
"""
|
| 218 |
+
probs = np.asarray(probabilities).flatten()
|
| 219 |
+
|
| 220 |
+
if len(probs) != len(class_map):
|
| 221 |
+
raise ValueError(f"Probability length {len(probs)} does not match class_map size {len(class_map)}")
|
| 222 |
+
|
| 223 |
+
mapped = {class_map[i]: float(probs[i]) for i in range(len(probs))}
|
| 224 |
+
|
| 225 |
+
# Sort by highest probability
|
| 226 |
+
mapped = dict(sorted(mapped.items(), key=lambda x: x[1], reverse=True))
|
| 227 |
+
|
| 228 |
+
return mapped
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def predict(img_path: str) -> tuple[str, np.ndarray, np.ndarray]:
|
| 233 |
+
img = Image.open(img_path)
|
| 234 |
+
x, masked_vis, _ = create_masked_img(img)
|
| 235 |
+
# ---> ok
|
| 236 |
+
preds = model_capsnet.predict(x, verbose=1) #(1,4,1) aka (batch_size, 4_class_prob, 1)
|
| 237 |
+
probs = to_probabilities(preds, model_type="capsnet") # shape (1,4)
|
| 238 |
+
probs = probs[0] # shape (4,)
|
| 239 |
+
|
| 240 |
+
prob_dict = map_probabilities_to_classes(probs, class_to_disease_map)
|
| 241 |
+
|
| 242 |
+
filename_out = os.path.basename(img_path)
|
| 243 |
+
|
| 244 |
+
return filename_out, masked_vis, prob_dict
|
modelbuilder.py
CHANGED
|
@@ -128,6 +128,8 @@ class ModelBuilder:
|
|
| 128 |
def build_capsnet(self, inputs, **params):
|
| 129 |
"""
|
| 130 |
Build a Capsule Network model for four class lung iseases classification: COVID, Normal, Pneumonia and Opacity.
|
|
|
|
|
|
|
| 131 |
Args:
|
| 132 |
name (_type_): _description_
|
| 133 |
first_Conv2DKernel_size (int, optional): _description_. Defaults to 10.
|
|
@@ -269,7 +271,7 @@ class PrimaryCaps(layers.Layer):
|
|
| 269 |
|
| 270 |
@register_keras_serializable()
|
| 271 |
class DigitCaps(layers.Layer):
|
| 272 |
-
# DigitCaps Layer / Higher-level capsules (e.g. detecting objects like
|
| 273 |
|
| 274 |
def __init__(self, num_capsule, dim_capsule, routing_iters=3, **kwargs):
|
| 275 |
super(DigitCaps, self).__init__(**kwargs)
|
|
|
|
| 128 |
def build_capsnet(self, inputs, **params):
|
| 129 |
"""
|
| 130 |
Build a Capsule Network model for four class lung iseases classification: COVID, Normal, Pneumonia and Opacity.
|
| 131 |
+
The batch dimension is always None internally → full input shape is (None, 256, 256, 1).
|
| 132 |
+
The output shape is (None, 4, 1)
|
| 133 |
Args:
|
| 134 |
name (_type_): _description_
|
| 135 |
first_Conv2DKernel_size (int, optional): _description_. Defaults to 10.
|
|
|
|
| 271 |
|
| 272 |
@register_keras_serializable()
|
| 273 |
class DigitCaps(layers.Layer):
|
| 274 |
+
# DigitCaps Layer / Higher-level capsules (e.g. detecting objects like animals or lungs)
|
| 275 |
|
| 276 |
def __init__(self, num_capsule, dim_capsule, routing_iters=3, **kwargs):
|
| 277 |
super(DigitCaps, self).__init__(**kwargs)
|