UNet网络详解

上一篇介绍了UNet网络的总体结构和工程实现,详见UNet的PyTorch实现,本篇进一步深入UNet网络细节,进行代码层面的分析。

首先,还是先贴出UNet的网络结构图,以便和实现细节做对照。

从上图可以看到,Unet网络的结构比较简单,左侧分支每一层包含两个重复的卷积,我们命名为DoubleConv,从第二层开始,都是max_pool+DoubleConv;右侧分支每一层都是up_conv +copy_crop+DoubleConv,在最后输出层,有一个1x1 conv。所以,我们可以将以上网络简化为4个模块,分别是:

  • 输入层的DoubleConv模块;
  • 左侧分支从第二层开始的max_pool+DoubleConv,称为Down模块;
  • 右侧分支的up_conv+copy_crop+DoubleConv,称为Up模块;
  • 输出层的1x1卷积,称为OutConv模块。

下面我们分别来介绍这几个模块的实现细节。

1. 模块实现

1.1 DoubleConv

 每个DoubleConv模块由两个“Conv2d+NatchNorm2d+ReLU”组成,代码如下:

class DoubleConv(nn.Module):
    """(convolution => [BN] => ReLU) * 2"""

    def __init__(self, in_channels, out_channels, mid_channels=None):
        super().__init__()
        if not mid_channels:
            mid_channels = out_channels
        self.double_conv = nn.Sequential(
            nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(mid_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        return self.double_conv(x)

1.2 Down

从架构图中可知,每个Down模块由一个“MaxPool2d+DoubleConv”组成,代码如下:

class Down(nn.Module):
    """Downscaling with maxpool then double conv"""

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.maxpool_conv = nn.Sequential(
            nn.MaxPool2d(2),
            DoubleConv(in_channels, out_channels)
        )

    def forward(self, x):
        return self.maxpool_conv(x)

MaxPool2d(2)相当于2倍下采样。

1.3 Up 

右侧上行模块由于涉及到copy and crop,所以实现起来会略微复杂一些。首先经过一个上采样或转置卷积,然后从左侧路径的同一层feature map中截取相同的size(从图中很容易可以看出,左侧同一层中的feature map比右侧的size要大一些),与右侧feature map合并,最后再进行DoubleConv。代码如下:

class Up(nn.Module):
    """Upscaling then double conv"""

    def __init__(self, in_channels, out_channels, bilinear=True):
        super().__init__()

        # if bilinear, use the normal convolutions to reduce the number of channels
        if bilinear:
            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
            self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)
        else:
            self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
            self.conv = DoubleConv(in_channels, out_channels)

    def forward(self, x1, x2):
        x1 = self.up(x1)
        # input is CHW
        diffY = x2.size()[2] - x1.size()[2]
        diffX = x2.size()[3] - x1.size()[3]

        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
                        diffY // 2, diffY - diffY // 2])
        # if you have padding issues, see
        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a
        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd
        x = torch.cat([x2, x1], dim=1)
        return self.conv(x)

1.4 OutConv

最后是输出层,由1x1卷积实现:

class OutConv(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(OutConv, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)

    def forward(self, x):
        return self.conv(x)

2. 整体架构

有了以上几个网络组成模块,我们就可以按照原始网络模型架构来组织网络,代码如下:

class UNet(nn.Module):
    def __init__(self, n_channels, n_classes, bilinear=False):
        super(UNet, self).__init__()
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.bilinear = bilinear

        self.inc = DoubleConv(n_channels, 64)  # 第一层只有DoubleConv

        self.down1 = Down(64, 128)  # max_pool + DoubleConv生成左侧第二层
        self.down2 = Down(128, 256)  # 同上生成左侧第三层
        self.down3 = Down(256, 512)  # 同上生成左侧第四层
        factor = 2 if bilinear else 1     # 默认bilinear==False
        self.down4 = Down(512, 1024 // factor)   # 生成最下面一层

        self.up1 = Up(1024, 512 // factor, bilinear)   # TransposedConv + copy_crop + DoubleConv生成右侧分支第四层
        self.up2 = Up(512, 256 // factor, bilinear)   # 同上,生成右侧第三层
        self.up3 = Up(256, 128 // factor, bilinear)   # 同上,生成右侧第二层
        self.up4 = Up(128, 64, bilinear)              # 同上,生成右侧第二层

        self.outc = OutConv(64, n_classes)            # 输出层

    def forward(self, x):
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits

OK,UNet的网络结构就构造完成了,接下来就可以用已有数据集对它训练了。篇幅原因,本篇就写这么多吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值