File size: 8,001 Bytes
7e855bb |
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 224 225 226 227 228 229 230 231 232 233 234 235 |
import os
import numpy as np
import gradio as gr
from glob import glob
from functools import partial
from dataclasses import dataclass
import torch
import torchvision
import torch.nn as nn
import lightning.pytorch as pl
import torchvision.transforms as TF
from torchmetrics import MeanMetric
from torchmetrics.classification import MultilabelF1Score
@dataclass
class DatasetConfig:
IMAGE_SIZE: tuple = (384, 384) # (W, H)
CHANNELS: int = 3
NUM_CLASSES: int = 10
MEAN: tuple = (0.485, 0.456, 0.406)
STD: tuple = (0.229, 0.224, 0.225)
@dataclass
class TrainingConfig:
METRIC_THRESH: float = 0.4
MODEL_NAME: str = "efficientnet_v2_s"
FREEZE_BACKBONE: bool = False
def get_model(model_name: str, num_classes: int, freeze_backbone: bool = True):
"""A helper function to load and prepare any classification model
available in Torchvision for transfer learning or fine-tuning."""
model = getattr(torchvision.models, model_name)(weights="DEFAULT")
if freeze_backbone:
# Set all layer to be non-trainable
for param in model.parameters():
param.requires_grad = False
model_childrens = [name for name, _ in model.named_children()]
try:
final_layer_in_features = getattr(model, f"{model_childrens[-1]}")[-1].in_features
except Exception as e:
final_layer_in_features = getattr(model, f"{model_childrens[-1]}").in_features
new_output_layer = nn.Linear(in_features=final_layer_in_features, out_features=num_classes)
try:
getattr(model, f"{model_childrens[-1]}")[-1] = new_output_layer
except:
setattr(model, model_childrens[-1], new_output_layer)
return model
class ProteinModel(pl.LightningModule):
def __init__(
self,
model_name: str,
num_classes: int = 10,
freeze_backbone: bool = False,
init_lr: float = 0.001,
optimizer_name: str = "Adam",
weight_decay: float = 1e-4,
use_scheduler: bool = False,
f1_metric_threshold: float = 0.4,
):
super().__init__()
# Save the arguments as hyperparameters.
self.save_hyperparameters()
# Loading model using the function defined above.
self.model = get_model(
model_name=self.hparams.model_name,
num_classes=self.hparams.num_classes,
freeze_backbone=self.hparams.freeze_backbone,
)
# Intialize loss class.
self.loss_fn = nn.BCEWithLogitsLoss()
# Initializing the required metric objects.
self.mean_train_loss = MeanMetric()
self.mean_train_f1 = MultilabelF1Score(num_labels=self.hparams.num_classes, average="macro", threshold=self.hparams.f1_metric_threshold)
self.mean_valid_loss = MeanMetric()
self.mean_valid_f1 = MultilabelF1Score(num_labels=self.hparams.num_classes, average="macro", threshold=self.hparams.f1_metric_threshold)
def forward(self, x):
return self.model(x)
def training_step(self, batch, *args, **kwargs):
data, target = batch
logits = self(data)
loss = self.loss_fn(logits, target)
self.mean_train_loss(loss, weight=data.shape[0])
self.mean_train_f1(logits, target)
self.log("train/batch_loss", self.mean_train_loss, prog_bar=True)
self.log("train/batch_f1", self.mean_train_f1, prog_bar=True)
return loss
def on_train_epoch_end(self):
# Computing and logging the training mean loss & mean f1.
self.log("train/loss", self.mean_train_loss, prog_bar=True)
self.log("train/f1", self.mean_train_f1, prog_bar=True)
self.log("step", self.current_epoch)
def validation_step(self, batch, *args, **kwargs):
data, target = batch # Unpacking validation dataloader tuple
logits = self(data)
loss = self.loss_fn(logits, target)
self.mean_valid_loss.update(loss, weight=data.shape[0])
self.mean_valid_f1.update(logits, target)
def on_validation_epoch_end(self):
# Computing and logging the validation mean loss & mean f1.
self.log("valid/loss", self.mean_valid_loss, prog_bar=True)
self.log("valid/f1", self.mean_valid_f1, prog_bar=True)
self.log("step", self.current_epoch)
def configure_optimizers(self):
optimizer = getattr(torch.optim, self.hparams.optimizer_name)(
filter(lambda p: p.requires_grad, self.model.parameters()),
lr=self.hparams.init_lr,
weight_decay=self.hparams.weight_decay,
)
if self.hparams.use_scheduler:
lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer,
milestones=[
self.trainer.max_epochs // 2,
],
gamma=0.1,
)
# The lr_scheduler_config is a dictionary that contains the scheduler
# and its associated configuration.
lr_scheduler_config = {
"scheduler": lr_scheduler,
"interval": "epoch",
"name": "multi_step_lr",
}
return {"optimizer": optimizer, "lr_scheduler": lr_scheduler_config}
else:
return optimizer
@torch.inference_mode()
def predict(input_image, threshold=0.4, model=None, preprocess_fn=None, device="cpu", idx2labels=None):
input_tensor = preprocess_fn(input_image)
input_tensor = input_tensor.unsqueeze(0).to(device)
# Generate predictions
output = model(input_tensor).cpu()
probabilities = torch.sigmoid(output)[0].numpy().tolist()
output_probs = dict()
predicted_classes = []
for idx, prob in enumerate(probabilities):
output_probs[idx2labels[idx]] = prob
if prob >= threshold:
predicted_classes.append(idx2labels[idx])
predicted_classes = "\n".join(predicted_classes)
return predicted_classes, output_probs
if __name__ == "__main__":
labels = {
0: "Mitochondria",
1: "Nuclear bodies",
2: "Nucleoli",
3: "Golgi apparatus",
4: "Nucleoplasm",
5: "Nucleoli fibrillar center",
6: "Cytosol",
7: "Plasma membrane",
8: "Centrosome",
9: "Nuclear speckles",
}
DEVICE = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
CKPT_PATH = os.path.join(os.getcwd(), r"ckpt_022-vloss_0.1756_vf1_0.7919.ckpt")
model = ProteinModel.load_from_checkpoint(CKPT_PATH)
model.to(DEVICE)
model.eval()
_ = model(torch.randn(1, DatasetConfig.CHANNELS, *DatasetConfig.IMAGE_SIZE[::-1], device=DEVICE))
preprocess = TF.Compose(
[
TF.Resize(size=DatasetConfig.IMAGE_SIZE[::-1]),
TF.ToTensor(),
TF.Normalize(DatasetConfig.MEAN, DatasetConfig.STD, inplace=True),
]
)
images_dir = glob(os.path.join(os.getcwd(), "samples") + os.sep + "*.png")
examples = [[i, TrainingConfig.METRIC_THRESH] for i in np.random.choice(images_dir, size=10, replace=False)]
# print(examples)
with gr.Interface(
fn=partial(predict, model=model, preprocess_fn=preprocess, device=DEVICE, idx2labels=labels),
inputs=[
gr.Image(type="pil", label="Image"),
gr.Slider(0.0, 1.0, value=0.4, label="Threshold", info="Select the cut-off threshold for a node to be considered as a valid output."),
],
outputs=[
gr.Textbox(label="Labels Present"),
gr.Label(label="Probabilities", show_label=False),
],
examples=examples,
cache_examples=False,
allow_flagging="never",
title="Awan AI Medical Image Classification",
theme=gr.themes.Soft(primary_hue="sky", secondary_hue="pink"),
) as iface:
additional_inputs=[gr.Model3D(label="3D Model", value="./HackMercedIXRunThrough.glb", clear_color=[0.4, 0.2, 0.7, 1.0])]
iface.launch(share=True)
|