2018年1月15日月曜日

pytorchで可変個のレイヤーを使う


title: pytorchで可変個のレイヤーを使う
tags: [Deep Learning, PyTorch]


        self.encoders = [EncoderBlock(in_channels, int(0.5*kernel_scale), 1*kernel_scale, dropout)]
        for i in range(1, depth):
            self.encoders.append(EncoderBlock(int((1/2) * 2**i *kernel_scale),
                                              int((3/4) * 2**i *kernel_scale),
                                              2**i *kernel_scale, dropout))
            # in_channels -> 0.5*kernel_scale -> 1*kernel_scale
            # --> 1 -> 1.5, 2 --> ...
            # --> 2**(depth-2) -> 3* 2**(depth-3)  -> 2**(depth-1)
        self.encoders = nn.Sequential(*self.encoders)

モデル定義内でこのようにただのリストを使ってレイヤーの長さを可変にしようとしても,pytorchはリストの中身をモデルの一部と認識できず,optimiserに渡すときやモデルをcudaに移すときに怒られる. よってこういう場合はtorch.nn.ModuleList を利用する.

        self.encoders = nn.ModuleList([EncoderBlock(in_channels, int(0.5*kernel_scale), 1*kernel_scale, dropout)])
        for i in range(1, depth):
            self.encoders.append(EncoderBlock(int((1/2) * 2**i *kernel_scale),
                                              int((3/4) * 2**i *kernel_scale),
                                              2**i *kernel_scale, dropout))
            # in_channels -> 0.5*kernel_scale -> 1*kernel_scale
            # --> 1 -> 1.5, 2 --> ...
            # --> 2**(depth-2) -> 3* 2**(depth-3)  -> 2**(depth-1)

補遺 Python 2.8だと重み初期化の際にZeroDivisionする.