MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / run_inference_test

Function run_inference_test

tests/integration/test_integration_workflows.py:218–282  ·  view source on GitHub ↗
(root_dir, model_file, device="cuda:0", amp=False, num_workers=4)

Source from the content-addressed store, hash-verified

216
217
218def run_inference_test(root_dir, model_file, device="cuda:0", amp=False, num_workers=4):
219 images = sorted(glob(os.path.join(root_dir, "im*.nii.gz")))
220 segs = sorted(glob(os.path.join(root_dir, "seg*.nii.gz")))
221 val_files = [{"image": img, "label": seg} for img, seg in zip(images, segs)]
222
223 # define transforms for image and segmentation
224 val_transforms = Compose(
225 [
226 LoadImaged(keys=["image", "label"]),
227 EnsureChannelFirstd(keys=["image", "label"], channel_dim=-1),
228 ScaleIntensityd(keys=["image", "label"]),
229 ]
230 )
231
232 # create a validation data loader
233 val_ds = monai.data.Dataset(data=val_files, transform=val_transforms)
234 val_loader = monai.data.DataLoader(val_ds, batch_size=1, num_workers=num_workers)
235
236 # create UNet, DiceLoss and Adam optimizer
237 net = monai.networks.nets.UNet(
238 spatial_dims=3,
239 in_channels=1,
240 out_channels=1,
241 channels=(16, 32, 64, 128, 256),
242 strides=(2, 2, 2, 2),
243 num_res_units=2,
244 ).to(device)
245
246 val_postprocessing = Compose(
247 [
248 Activationsd(keys="pred", sigmoid=True),
249 AsDiscreted(keys="pred", threshold=0.5),
250 KeepLargestConnectedComponentd(keys="pred", applied_labels=[1]),
251 # test the case that `pred` in `engine.state.output`, while `image_meta_dict` in `engine.state.batch`
252 SaveImaged(keys="pred", output_dir=root_dir, output_postfix="seg_transform"),
253 ]
254 )
255 val_handlers = [
256 StatsHandler(iteration_log=False),
257 CheckpointLoader(load_path=f"{model_file}", load_dict={"net": net}),
258 ]
259
260 saver = SaveImage(output_dir=root_dir, output_postfix="seg_handler")
261
262 def save_func(engine):
263 for o in from_engine("pred")(engine.state.output):
264 saver(o)
265
266 evaluator = SupervisedEvaluator(
267 device=device,
268 val_data_loader=val_loader,
269 network=net,
270 inferer=SlidingWindowInferer(roi_size=(96, 96, 96), sw_batch_size=4, overlap=0.5),
271 postprocessing=val_postprocessing,
272 key_val_metric={
273 "val_mean_dice": MeanDice(include_background=True, output_transform=from_engine(["pred", "label"]))
274 },
275 additional_metrics={"val_acc": Accuracy(output_transform=from_engine(["pred", "label"]))},

Callers 1

train_and_inferMethod · 0.70

Calls 15

ComposeClass · 0.90
LoadImagedClass · 0.90
EnsureChannelFirstdClass · 0.90
ScaleIntensitydClass · 0.90
ActivationsdClass · 0.90
AsDiscretedClass · 0.90
SaveImagedClass · 0.90
StatsHandlerClass · 0.90
CheckpointLoaderClass · 0.90
SaveImageClass · 0.90
SupervisedEvaluatorClass · 0.90

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…