卷积 - 偶数和奇数大小的反卷积

Convolution - Deconvolution for even and odd size

我有两个不同大小的张量要放入网络中。

C = nn.Conv1d(1, 1, kernel_size=1, stride=2)
TC = nn.ConvTranspose1d(1, 1, kernel_size=1, stride=2)

a = torch.rand(1, 1, 100)
b = torch.rand(1, 1, 101)

a_out, b_out = TC(C(a)), TC(C(b))

结果是

a_out = torch.size([1, 1, 99]) # What I want is [1, 1, 100]
b_out = torch.size([1, 1, 101])

有什么方法可以解决这个问题吗?
我需要你的帮助。
谢谢

这是符合 documentation 的预期行为。当检测到甚至输入长度以获得与输入相同的长度时,可以使用填充。

像这样

class PadEven(nn.Module):
    def __init__(self, conv, deconv, pad_value=0, padding=(0, 1)):
        super().__init__()
        self.conv = conv
        self.deconv = deconv
        self.pad = nn.ConstantPad1d(padding=padding, value=pad_value)

    def forward(self, x):
        nd = x.size(-1)
        x = self.deconv(self.conv(x))
        if nd % 2 == 0:
            x = self.pad(x)
        return x


C = nn.Conv1d(1, 1, kernel_size=1, stride=2)
TC = nn.ConvTranspose1d(1, 1, kernel_size=1, stride=2)
P = PadEven(C, TC)

a = torch.rand(1, 1, 100)
b = torch.rand(1, 1, 101)

a_out, b_out = P(a), P(b)