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

Function predict_with_inferer

monai/apps/detection/utils/predict_utils.py:92–141  ·  view source on GitHub ↗

Predict network dict output with an inferer. Compared with directly output network(images), it enables a sliding window inferer that can be used to handle large inputs. Args: images: input of the network, Tensor sized (B, C, H, W) or (B, C, H, W, D) network: a network

(
    images: Tensor, network: nn.Module, keys: list[str], inferer: SlidingWindowInferer | None = None
)

Source from the content-addressed store, hash-verified

90
91
92def predict_with_inferer(
93 images: Tensor, network: nn.Module, keys: list[str], inferer: SlidingWindowInferer | None = None
94) -> dict[str, list[Tensor]]:
95 """
96 Predict network dict output with an inferer. Compared with directly output network(images),
97 it enables a sliding window inferer that can be used to handle large inputs.
98
99 Args:
100 images: input of the network, Tensor sized (B, C, H, W) or (B, C, H, W, D)
101 network: a network that takes an image Tensor sized (B, C, H, W) or (B, C, H, W, D) as input
102 and outputs a dictionary Dict[str, List[Tensor]] or Dict[str, Tensor].
103 keys: the keys in the output dict, should be network output keys or a subset of them.
104 inferer: a SlidingWindowInferer to handle large inputs.
105
106 Return:
107 The predicted head_output from network, a Dict[str, List[Tensor]]
108
109 Example:
110 .. code-block:: python
111
112 # define a naive network
113 import torch
114 import monai
115 class NaiveNet(torch.nn.Module):
116 def __init__(self, ):
117 super().__init__()
118
119 def forward(self, images: torch.Tensor):
120 return {"cls": torch.randn(images.shape), "box_reg": [torch.randn(images.shape)]}
121
122 # create a predictor
123 network = NaiveNet()
124 inferer = monai.inferers.SlidingWindowInferer(
125 roi_size = (128, 128, 128),
126 overlap = 0.25,
127 cache_roi_weight_map = True,
128 )
129 network_output_keys=["cls", "box_reg"]
130 images = torch.randn((2, 3, 512, 512, 512)) # a large input
131 head_outputs = predict_with_inferer(images, network, network_output_keys, inferer)
132
133 """
134 if inferer is None:
135 raise ValueError("Please set inferer as a monai.inferers.inferer.SlidingWindowInferer(*)")
136 head_outputs_sequence = inferer(images, _network_sequence_output, network, keys=keys)
137 num_output_levels: int = len(head_outputs_sequence) // len(keys)
138 head_outputs = {}
139 for i, k in enumerate(keys):
140 head_outputs[k] = list(head_outputs_sequence[num_output_levels * i : num_output_levels * (i + 1)])
141 return head_outputs

Callers 2

forwardMethod · 0.90
test_naive_predictorMethod · 0.90

Calls

no outgoing calls

Tested by 1

test_naive_predictorMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…