Skip to content

Commit

Permalink
Merge pull request mkocabas#3 from leVirve-arxiv/master
Browse files Browse the repository at this point in the history
Alternative implementation for PyTorch
  • Loading branch information
Muhammed Kocabas authored Jul 15, 2018
2 parents b525d4a + 62f701d commit d8d6a2c
Showing 1 changed file with 55 additions and 1 deletion.
56 changes: 55 additions & 1 deletion CoordConv.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def forward(self, input_tensor):
return ret


class CoordConv(nn.Module):
class CoordConvTh(nn.Module):
"""CoordConv layer as in the paper."""
def __init__(self, x_dim, y_dim, with_r, *args, **kwargs):
super(CoordConv, self).__init__()
Expand All @@ -65,3 +65,57 @@ def forward(self, input_tensor):
ret = self.addcoords(input_tensor)
ret = self.conv(ret)
return ret


'''
An alternative implementation for PyTorch with auto-infering the x-y dimensions.
'''
class AddCoords(nn.Module):

def __init__(self, with_r=False):
super().__init__()
self.with_r = with_r

def forward(self, input_tensor):
"""
Args:
input_tensor: shape(batch, channel, x_dim, y_dim)
"""
batch_size, _, x_dim, y_dim = input_tensor.size()

xx_channel = torch.arange(x_dim).repeat(1, y_dim, 1)
yy_channel = torch.arange(y_dim).repeat(1, x_dim, 1).transpose(1, 2)

xx_channel = xx_channel.float() / (x_dim - 1)
yy_channel = yy_channel.float() / (y_dim - 1)

xx_channel = xx_channel * 2 - 1
yy_channel = yy_channel * 2 - 1

xx_channel = xx_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)
yy_channel = yy_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)

ret = torch.cat([
input_tensor,
xx_channel.type_as(input_tensor),
yy_channel.type_as(input_tensor)], dim=1)

if self.with_r:
rr = torch.sqrt(torch.pow(xx_channel - 0.5, 2) + torch.pow(yy_channel - 0.5, 2))
ret = torch.cat([ret, rr], dim=1)

return ret


class CoordConv(nn.Module):

def __init__(self, in_channels, out_channels, with_r=False, **kwargs):
super().__init__()
self.addcoords = AddCoords(with_r=with_r)
self.conv = nn.Conv2d(in_channels + 2, out_channels, **kwargs)

def forward(self, x):
ret = self.addcoords(x)
ret = self.conv(ret)
return ret

0 comments on commit d8d6a2c

Please sign in to comment.