Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Batches in guided_backprop.py #530

Open
MoH-assan opened this issue Sep 10, 2024 · 0 comments
Open

Batches in guided_backprop.py #530

MoH-assan opened this issue Sep 10, 2024 · 0 comments

Comments

@MoH-assan
Copy link

MoH-assan commented Sep 10, 2024

Does guided_backprop.py support batchs?

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

loss = output[0, target_category]

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant