spanev:

mport torch input = torch.rand((16,16),requires_grad=True) print(input) mask = torch.zeros_like(input) mask[4:12,4:12]=1.0 masked_input = mask * input d = torch.mean(masked_input) d.backward() print(input.grad.data)


Thanks @spanev. It worked but the result looks wrong. If I ignore the region in mask, so the expected mean grad should be 1 instead of 0.11111