分割
1. U-net
网络架构图:
import torch
import torch.nn as nn
# 使用nn.sequential类定义各个模块
class down(nn.Sequential):
def __init__(self,in_channel,out_channel):
super(down,self).__init__(
nn.Conv2d(in_channel,in_channel,kernel_size= 3, stride=2,padding=1),
nn.BatchNorm2d(in_channel),
nn.ReLU(),
DoubleConv(in_channel,out_channel)
)
class DoubleConv(nn.Sequential):
def __init__(self,in_channel,out_channel):
super(DoubleConv,self).__init__(
nn.Conv2d(in_channel,out_channel,kernel_size=3,stride=1,padding=1),
nn.BatchNorm2d(out_channel),
nn.ReLU(),
nn.Conv2d(out_channel,out_channel,kernel_size=3,stride=1,padding=1),
nn.BatchNorm2d(out_channel),
nn.ReLU(),
)
class out_conv(nn.Sequential):
def __init__(self,in_channel,num_class):
super(out_conv,self).__init__(
nn.Conv2d(in_channel,num_class,kernel_size=1,stride=1),
)
class up(nn.Module):
def __init__(self,in_channel,out_channel):
super(up,self).__init__(
)
self.upsample = nn.Upsample(scale_factor=2,mode='bilinear',align_corners=True) # 上采样倍率2
self.singleconv = nn.Conv2d(in_channel ,out_channel,kernel_size=3,padding=1)
self.conv = DoubleConv(in_channel, out_channel)
def forward(self,x1,x2):
x1 = self.upsample(x1)
x1 = self.singleconv(x1)
x = torch.cat([x1,x2],1)
x = self.conv(x)
return x
class unet(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.doubleconv = DoubleConv(3,64)
self.doubleconv1 = DoubleConv(3,64)
self.down1 = down(64,128)
self.down2 = down(128,256)
self.down3 = down(256,512)
self.down4 = down(512,1024)
self.up1 = up(1024,512)
self.up2 = up(512,256)
self.up3 = up(256,128)
self.up4 = up(128,64)
self.out_conv = out_conv(64,1)
def forward(self,x):
out1 = x = self.doubleconv(x)
out2 = x = self.down1(x)
out3 =x = self.down2(x)
out4 = x = self.down3(x)
x = self.down4(x)
x = self.up1(x,out4)
x = self.up2(x,out3)
x = self.up3(x,out2)
x = self.up4(x,out1)
x = self.out_conv(x)
return {'out':x}