UNet详细解读(二)pytorch从头开始搭建UNet

Unet代码

网络架构图

请添加图片描述

  • 输入是572x572的,但是输出变成了388x388,这说明经过网络以后,输出的结果和原图不是完全对应的,这在计算loss和输出结果都可以得到体现.

  • 蓝色箭头代表3x3的卷积操作,并且步长是1,不进行padding,因此,每个该操作以后,featuremap的大小会减2.

  • 红色箭头代表2x2的最大池化操作.如果池化之前特征向量的大小是奇数,那么就会损失一些信息 。输入的大小最好满足一个条件,就是可以让每一层池化操作前的特征向量的大小是偶数,这样就不会损失一些信息,并且crop的时候不会产生误差.

  • 绿色箭头代表2x2的反卷积操作.

  • 灰色箭头表示复制和剪切操作.

  • 输出的最后一层,使用了1x1的卷积层做了分类

  • 前半部分也就是图中左边部分的作用是特征提取,后半部分也就是图中的右边部分是上采样,也叫 encoder-deconder结构

两个3X3卷积层

蓝色箭头代表3x3的卷积操作,并且步长是1,不进行padding,因此,每个该操作以后,featuremap的大小会减2.

class DoubleConvolution(nn.Module):

	def __init__(self, in_channels: int, out_channels: int):
    	super().__init__()

		self.first = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
		self.act1 = nn.ReLU()
		self.second = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
		self.act2 = nn.ReLU()
		
	def forward(self, x: torch.Tensor):
		x = self.first(x)
        x = self.act1(x)
        x = self.second(x)
        return self.act2(x)

下采样

红色箭头代表2x2的最大池化操作。

class DownSample(nn.Module):
    def __init__(self):
        super().__init__()
        self.pool = nn.MaxPool2d(2)

    def forward(self,x:torch.Tensor):
        return self.pool(x)

上采样

绿色箭头代表2x2的反卷积操作.

class UpSample(nn.Module):
    def __init__(self,input_channals:int,output_channals:int):
        super().__init__()
        self.up = nn.ConvTranspose2d(input_channals,output_channals,kernel_size=2,stride=2)

    def forward(self,x:torch.Tensor):
        return self.up(x)

裁剪并连接特征图

在扩展路径中的每个步骤,来自收缩路径的对应特征图与当前特征图连接。

contracting_x:将特征图从收缩路径裁剪为当前特征图的大小

class CropAndConcat(nn.Module):

    def forward(self,x:torch.Tensor,contracting_x:torch.Tensor):
        contracting_x = torchvision.transforms.functional.center_crop(contracting_x,[x.shape[2],x.shape[3]])
        x = torch.cat([x,contracting_x],dim=1)
        return x

网络架构代码

class Unet(nn.Module):
    def __init__(self,input_channals:int,output_channals:int):
        super().__init__()

        self.down_conv = nn.ModuleList([DoubleConvolution(i,0) for i,o in [(input_channals,64),(64,128),(128,256),(256,512)]])
        self.down_sample = nn.ModuleList([DownSample() for _ in range(4)])
        self.middel_conv = DoubleConvolution(512,1024)
        self.up_sample = nn.ModuleList([UpSample(i,o) for i,o in [(1024,512),(512,256),(256,128),(128,64)]])
        self.up_conv = nn.ModuleList([DoubleConvolution(i,o) for i,o in [(1024,512),(512,256),(256,128),(128,64)]])
        self.concat = nn.ModuleList(CropAndConcat() for _ in range(4))
        self.final_conv = nn.Conv2d(64,output_channals,kernel_size=1)

    def forward(self,x:torch.Tensor):
        pass_through = []

        for i in range(len(self.down_conv)):
            x = self.down_conv[i](x)
            pass_through.append(x)
            x = self.down_sample[i](x)

        x = self.middel_conv(x)

        for i in range(len(self.up_conv)):
            x = self.up_sample[i](x)
            x = self.concat[i](x,pass_through.pop())
            x = self.up_conv[i](x)

        x = self.final_conv(x)

        return x
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用PyTorch搭建UNet,可以按照以下步骤进行: 1. 导入必要的模块: ```python import torch import torch.nn as nn import torch.nn.functional as F ``` 2. 定义UNet的核心模块: ```python class DoubleConv(nn.Module): def __init__(self, in_channels, out_channels): super(DoubleConv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True) ) def forward(self, x): return self.conv(x) ``` 3. 定义UNet的编码器: ```python class UNet(nn.Module): def __init__(self, in_channels, out_channels): super(UNet, self).__init__() self.down1 = DoubleConv(in_channels, 64) self.down2 = DoubleConv(64, 128) self.down3 = DoubleConv(128, 256) self.down4 = DoubleConv(256, 512) self.up1 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2) self.up2 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2) self.up3 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2) self.up4 = nn.ConvTranspose2d(64, out_channels, kernel_size=2, stride=2) def forward(self, x): x1 = self.down1(x) x2 = self.down2(F.max_pool2d(x1, 2)) x3 = self.down3(F.max_pool2d(x2, 2)) x4 = self.down4(F.max_pool2d(x3, 2)) x = self.up1(x4) x = self.up2(torch.cat([x, x3], dim=1)) x = self.up3(torch.cat([x, x2], dim=1)) x = self.up4(torch.cat([x, x1], dim=1)) return x ``` 4. 创建UNet实例并定义输入输出通道数: ```python model = UNet(in_channels=3, out_channels=1) ``` 这是一个基本的UNet模型,你可以根据自己的需求进行修改和扩展。记得在训练之前,要根据你的任务定义损失函数和优化器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江小皮不皮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值