| 3 | import torch.nn.functional as F |
| 4 | |
| 5 | class RAIN(nn.Module): |
| 6 | def __init__(self, dims_in, eps=1e-5): |
| 7 | '''Compute the instance normalization within only the background region, in which |
| 8 | the mean and standard variance are measured from the features in background region. |
| 9 | ''' |
| 10 | super(RAIN, self).__init__() |
| 11 | self.foreground_gamma = nn.Parameter(torch.zeros(dims_in), requires_grad=True) |
| 12 | self.foreground_beta = nn.Parameter(torch.zeros(dims_in), requires_grad=True) |
| 13 | self.background_gamma = nn.Parameter(torch.zeros(dims_in), requires_grad=True) |
| 14 | self.background_beta = nn.Parameter(torch.zeros(dims_in), requires_grad=True) |
| 15 | self.eps = eps |
| 16 | |
| 17 | def forward(self, x, mask): |
| 18 | mask = F.interpolate(mask.detach(), size=x.size()[2:], mode='nearest') |
| 19 | |
| 20 | mean_back, std_back = self.get_foreground_mean_std(x * (1-mask), 1 - mask) # the background features |
| 21 | normalized = (x - mean_back) / std_back |
| 22 | |
| 23 | normalized_background = (normalized * (1 + self.background_gamma[None, :, None, None]) + |
| 24 | self.background_beta[None, :, None, None]) * (1 - mask) |
| 25 | |
| 26 | mean_fore, std_fore = self.get_foreground_mean_std(x * mask, mask) # the background features |
| 27 | normalized = (x - mean_fore) / std_fore * std_back + mean_back |
| 28 | normalized_foreground = (normalized * (1 + self.foreground_gamma[None, :, None, None]) + |
| 29 | self.foreground_beta[None, :, None, None]) * mask |
| 30 | |
| 31 | return normalized_foreground + normalized_background |
| 32 | |
| 33 | def get_foreground_mean_std(self, region, mask): |
| 34 | sum = torch.sum(region, dim=[2, 3]) # (B, C) |
| 35 | num = torch.sum(mask, dim=[2, 3]) # (B, C) |
| 36 | mu = sum / (num + self.eps) |
| 37 | mean = mu[:, :, None, None] |
| 38 | var = torch.sum((region + (1 - mask)*mean - mean) ** 2, dim=[2, 3]) / (num + self.eps) |
| 39 | var = var[:, :, None, None] |
| 40 | return mean, torch.sqrt(var+self.eps) |
| 41 |
nothing calls this directly
no outgoing calls
no test coverage detected