用pytorch搭建简单的语义分割(可训练自己的数据集)
灵感来源:https://blog.csdn.net/weixin_44791964/article/details/102979289
本博客的搭建的网络源于这位博主采用的keras框架,不过基于本人电脑配置做了一些网络层数的改动。部分代码引用大佬的代码,其余均为本人原创。
整体文件目录下排放:
1、编码器Mobilenet:
这里也有大佬关于Mobilenet的博客Mobilenet的介绍。简单来说Mobilenet利用深度卷积使得数据量大大减少,有助于配置较低的机器,也可以应用到手机上。
import torch
from torch.nn import *
from torch.nn.functional import relu6
#第一个卷积块
class Conv_block(Module):
def __init__(self,inplanes,outplanes,strides):
super(Conv_block, self).__init__()
self.zeropad=ZeroPad2d(padding=1)
self.conv=Conv2d(inplanes,outplanes,kernel_size=3,stride=strides,padding=0)
self.BN=BatchNorm2d(outplanes,momentum=0.1)
# self.relu=ReLU()
def forward(self,x):
x=self.zeropad(x)
x=self.conv(x)
x=self.BN(x)
# x=self.relu(x)
x=relu6(x)
return x
#除了第一个卷积块的后面的深度卷积块
class depthwise_block(Module):
def __init__(self,inplanes,outplanes,strides):
super(depthwise_block, self).__init__()
self.zeropad=ZeroPad2d(padding=1)
self.DW=Conv2d(inplanes,inplanes, #深度卷积,输入和输出通道一致
kernel_size=3,stride=strides,
padding=0,groups=inplanes, #groups=inplanes是实现深度卷积的重点
bias=False)
self.BN_1=BatchNorm2d(inplanes,momentum=0.1)
self.BN_2=BatchNorm2d(outplanes,momentum=0.1)
self.conv=Conv2d(inplanes,outplanes,kernel_size=1,stride=1)
# self.relu=ReLU()
def forward(self,x):
x=self.zeropad(x)
x=self.DW(x)
x=self.BN_1(x)
# x=self.relu(x)
x = relu6(x)
x=self.conv(x)
x=self.BN_2(x)
# x=self.relu(x)
x=relu6(x)
return x
class Mobilenet(Module):
cfg_filter=[32,64,128,128,256,256] #每个block的inplanes、outplanes
cfg_stride=[1,2,1,2,1] #每个block的strides
cfg_block=[] #初始化后的block集成一个列表
layer_data=[] #每个block处理后的output
def __init__(self):
super(Mobilenet, self).__init__()
self.conv_block=Conv_block(