pytorch-grad-cam icon indicating copy to clipboard operation
pytorch-grad-cam copied to clipboard

Batches in guided_backprop.py

Open MoH-assan opened this issue 5 months ago • 0 comments

Does guided_backprop.py support batchs?

I think the current implementation is hard-coded of a single (2D) image [1,C,W,H].

https://github.com/jacobgil/pytorch-grad-cam/blob/18144f2afc8a14a73e71b68dc7fbdb7378af2f8e/pytorch_grad_cam/guided_backprop.py#L87

I think this change is needed to support batches

    def __call__(self, input_img, target_category=None):
        replace_all_layer_type_recursive(self.model,
                                         torch.nn.ReLU,
                                         GuidedBackpropReLUasModule())


        input_img = input_img.to(self.device)

        input_img = input_img.requires_grad_(True)

        output = self.forward(input_img)

        target_category = output.argmax(dim=-1).detach() if target_category is None else target_category


        #loss = output[0, target_category]
        #loss.backward(retain_graph=True)
        loss = torch.sum(output[torch.arange(output.size(0)), target_category])
        output = torch.autograd.grad(loss, input_img, create_graph=True)[0] # Batch x Channel x Height x Width
        
        # output = input_img.grad.cpu().data.numpy()
        # output = output[0, :, :, :]
        # output = output.transpose((1, 2, 0))

        replace_all_layer_type_recursive(self.model,
                                         GuidedBackpropReLUasModule,
                                         torch.nn.ReLU())

        return output

Thanks, Mohamed

MoH-assan avatar Sep 10 '24 22:09 MoH-assan