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

Class CAM

monai/visualize/class_activation_maps.py:218–316  ·  view source on GitHub ↗

Compute class activation map from the last fully-connected layers before the spatial pooling. This implementation is based on: Zhou et al., Learning Deep Features for Discriminative Localization. CVPR '16, https://arxiv.org/abs/1512.04150 Examples .. code-block::

Source from the content-addressed store, hash-verified

216
217
218class CAM(CAMBase):
219 """
220 Compute class activation map from the last fully-connected layers before the spatial pooling.
221 This implementation is based on:
222
223 Zhou et al., Learning Deep Features for Discriminative Localization. CVPR '16,
224 https://arxiv.org/abs/1512.04150
225
226 Examples
227
228 .. code-block:: python
229
230 import torch
231
232 # densenet 2d
233 from monai.networks.nets import DenseNet121
234 from monai.visualize import CAM
235
236 model_2d = DenseNet121(spatial_dims=2, in_channels=1, out_channels=3)
237 cam = CAM(nn_module=model_2d, target_layers="class_layers.relu", fc_layers="class_layers.out")
238 result = cam(x=torch.rand((1, 1, 48, 64)))
239
240 # resnet 2d
241 from monai.networks.nets import seresnet50
242 from monai.visualize import CAM
243
244 model_2d = seresnet50(spatial_dims=2, in_channels=3, num_classes=4)
245 cam = CAM(nn_module=model_2d, target_layers="layer4", fc_layers="last_linear")
246 result = cam(x=torch.rand((2, 3, 48, 64)))
247
248 N.B.: To help select the target layer, it may be useful to list all layers:
249
250 .. code-block:: python
251
252 for name, _ in model.named_modules(): print(name)
253
254 See Also:
255
256 - :py:class:`monai.visualize.class_activation_maps.GradCAM`
257
258 """
259
260 def __init__(
261 self,
262 nn_module: nn.Module,
263 target_layers: str,
264 fc_layers: str | Callable = "fc",
265 upsampler: Callable = default_upsampler,
266 postprocessing: Callable = default_normalizer,
267 ) -> None:
268 """
269 Args:
270 nn_module: the model to be visualized
271 target_layers: name of the model layer to generate the feature map.
272 fc_layers: a string or a callable used to get fully-connected weights to compute activation map
273 from the target_layers (without pooling). and evaluate it at every spatial location.
274 upsampler: An upsampling method to upsample the output image. Default is
275 N dimensional linear (bilinear, trilinear, etc.) depending on num spatial

Callers 2

__call__Method · 0.90
test_shapeMethod · 0.90

Calls

no outgoing calls

Tested by 1

test_shapeMethod · 0.72