You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello, I am trying to perform inference on my SegResNetDS model that I trained with Auto3DSeg.
import os
import torch
from monai.transforms import (
Compose, LoadImaged, EnsureChannelFirstd, Orientationd,
Spacingd, NormalizeIntensityd, EnsureTyped, Activationsd,
Invertd, AsDiscreted, SaveImaged, ToTensor, ScaleIntensityRanged
)
from monai.networks.nets import SegResNetDS
from monai.inferers import SlidingWindowInferer
import numpy as np
import nibabel as nib
import functools
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
output_dir = "/mnt/local/nvme0n1/projects/appwithtensormodel/nnnnUnet"
image_list = [{'input': './Testing/Control_100000000_CTA.nii.gz'}]
def pre_process():
"""Composes transforms for preprocessing input before predicting on a model."""
my_key = "input"
return Compose([
LoadImaged(keys=my_key),
EnsureChannelFirstd(keys=my_key),
Orientationd(keys=my_key, axcodes="RAS"),
ScaleIntensityRanged(keys=my_key, a_min=42.47142857142857, a_max=526.6205357142857, b_min=-1.0, b_max=1.0, clip=False),
Spacingd(keys=my_key, pixdim=[1.0, 1.0, 1.0], mode=["bilinear"], align_corners=True),
NormalizeIntensityd(keys=my_key),
ToTensor(),
EnsureTyped(keys=my_key),
])
def post_process(pre_transforms, out_dir="/mnt/local/nvme0n1/projects/strokedetect_original/StrokeDetect_Nifti/Transformed"):
"""Composes transforms for postprocessing the prediction results."""
pred_key = "prediction"
return Compose([
Activationsd(keys=pred_key, softmax=True),
Invertd(keys=pred_key, transform=pre_transforms, orig_keys="input", nearest_interp=False, to_tensor=True),
AsDiscreted(keys=pred_key, argmax=True),
SaveImaged(keys=pred_key, output_dir=out_dir, output_postfix="seg", output_dtype=torch.uint8),
])
def load_model(model_path):
"""Loads the trained model for inference."""
checkpoint = torch.load(model_path)
model = SegResNetDS(init_filters=32, blocks_down=[1, 2, 2, 4, 4], norm='instance', in_channels=1, out_channels=2, dsdepth=4)
model.load_state_dict(checkpoint['state_dict'])
model.to(device)
model.eval()
return model
model_path = "/mnt/local/nvme0n1/projects/strokedetect_original/work_dir/segresnet_4/model/model.pt"
model = load_model(model_path) # Load model once
pre_transforms = pre_process()
for image_dict in image_list:
data = {'input': image_dict['input']}
data = pre_transforms(data)
data['input'] = data['input'].unsqueeze(0).to(device) # Ensure the data is properly batched
post_transforms = post_process(pre_transforms)
inferer = SlidingWindowInferer(roi_size=[224, 224, 144], sw_batch_size=1, overlap=0.625, mode="gaussian")
with torch.no_grad():
output = inferer(data['input'], model)
data["prediction"] = output
data = post_transforms(data)
But I am getting the following error:
Traceback (most recent call last):
File "/mnt/local/nvme0n1/projects/appwithtensormodel/inference_aida.py", line 71, in <module>
data = post_transforms(data)
File "/mnt/local/nvme0n1/projects/appwithtensormodel/venv/lib/python3.10/site-packages/monai/transforms/compose.py", line 335, in __call__
result = execute_compose(
File "/mnt/local/nvme0n1/projects/appwithtensormodel/venv/lib/python3.10/site-packages/monai/transforms/compose.py", line 111, in execute_compose
data = apply_transform(
File "/mnt/local/nvme0n1/projects/appwithtensormodel/venv/lib/python3.10/site-packages/monai/transforms/transform.py", line 171, in apply_transform
raise RuntimeError(f"applying transform {transform}") from e
RuntimeError: applying transform <monai.transforms.post.dictionary.Invertd object at 0x7f7f89604df0>
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello, I am trying to perform inference on my SegResNetDS model that I trained with Auto3DSeg.
But I am getting the following error:
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions