附代码 Deeplab V2(附迁移学习代码)

DeepLab: Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs 论文解读

V1链接:https://blog.csdn.net/weixin_44543648/article/details/122576853
V3链接:https://blog.csdn.net/weixin_44543648/article/details/122829741
论文链接:https://arxiv.org/pdf/1606.00915.pdf
代码链接:https://github.com/dontLoveBugs/Deeplab_pytorch

V2目标解决的问题和部分内容与V1相似,具体不过多叙述,可以看上面链接。

主要内容:

  • 采用了空洞卷积,即卷积层设置dilation > 1。空洞卷积优势如下,上面为普通卷积,下面为空洞卷积。
    在这里插入图片描述
  • 使用ASPP进行多尺度下融合特征,实际应用中,即设置不同dilation进行多尺度输出再相加。多尺度融合过程如下
    在这里插入图片描述
  • 使用CRF进行边界的精确化。
  • 使用Resnet作为backbone。

代码:

ASPP module

class ASPP_module(nn.Module):
    def __init__(self, inplanes, planes, rate):
        super(ASPP_module, self).__init__()
        if rate == 1:
            kernel_size = 1
            padding = 0
        else:
            kernel_size = 3
            padding = rate
        self.atrous_convolution = nn.Conv2d(inplanes, planes, kernel_size=kernel_size,
                                            stride=1, padding=padding, dilation=rate, bias=False)
        self.bn = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU()

        self._init_weight()

    def forward(self, x):
        x = self.atrous_convolution(x)
        x = self.bn(x)

        return self.relu(x)

    def _init_weight(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                torch.nn.init.kaiming_normal_(m.weight)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

网络结构


from torch.utils import model_zoo

from network.base.resnet import *
from network.base.oprations import *


class DeeplabV2(ResNet):
    def __init__(self, n_class, block, layers, pyramids):
        print("Constructing DeepLabv2 model...")
        print("Number of classes: {}".format(n_class))
        super(DeeplabV2, self).__init__()

        self.inplanes = 64

        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(self.inplanes, affine=True)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=True)  # change

        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=1, rate=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=1, rate=4)

        self.aspp1 = ASPP_module(2048, n_class, pyramids[0])
        self.aspp2 = ASPP_module(2048, n_class, pyramids[1])
        self.aspp3 = ASPP_module(2048, n_class, pyramids[2])
        self.aspp4 = ASPP_module(2048, n_class, pyramids[3])

        self.init_weight()

    def forward(self, input):
        x = self.conv1(input)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x1 = self.aspp1(x)
        x2 = self.aspp2(x)
        x3 = self.aspp3(x)
        x4 = self.aspp4(x)

        x = x1 + x2 + x3 + x4

        x = F.upsample(x, size=input.size()[2:], mode='bilinear', align_corners=True)
        return x

    def get_1x_lr_params(self):
        b = [self.conv1, self.bn1, self.layer1, self.layer2, self.layer3, self.layer4]
        for i in range(len(b)):
            for k in b[i].parameters():
                if k.requires_grad:
                    yield k

    def get_10x_lr_params(self):
        b = [self.aspp1, self.aspp2, self.aspp3, self.aspp4]
        for j in range(len(b)):
            for k in b[j].parameters():
                if k.requires_grad:
                    yield k

    def freeze_bn(self):
        for m in self.modules():
            if isinstance(m, nn.BatchNorm2d):
                m.eval()

    def freeze_backbone_bn(self):
        self.bn1.eval()

        for m in self.layer1:
            if isinstance(m, nn.BatchNorm2d):
                m.eval()

        for m in self.layer2:
            if isinstance(m, nn.BatchNorm2d):
                m.eval()

        for m in self.layer3:
            if isinstance(m, nn.BatchNorm2d):
                m.eval()

        for m in self.layer4:
            if isinstance(m, nn.BatchNorm2d):
                m.eval()


def resnet101(n_class, pretrained=True):

    model = DeeplabV2(n_class=n_class, block=Bottleneck, layers=[3, 4, 23, 3], pyramids=[6, 12, 18, 24])

    if pretrained:
        pretrain_dict = model_zoo.load_url(model_urls['resnet101'])
        model_dict = {}
        state_dict = model.state_dict()
        for k, v in pretrain_dict.items():
            if k in state_dict:
                model_dict[k] = v
        state_dict.update(model_dict)
        model.load_state_dict(state_dict)

    return model


if __name__ == '__main__':
    model = resnet101(n_class=21, pretrained=True)

    img = torch.randn(4, 3, 513, 513)

    with torch.no_grad():
        output = model.forward(img)

    print(output.size())

迁移学习代码

import torch
import torch.nn as nn
import torchvision.models as models
from torchvision.models.resnet import Bottleneck,BasicBlock

class Asppmodule(nn.Module):
    def __init__(self, inchannels, ouchannels, rate):
        super(Asppmodule, self).__init__()

        if rate == 1:
            kernel_size = 1
            padding = 0
        else:
            kernel_size = 3
            padding = rate

        self.conv = nn.Sequential(
            nn.Conv2d(inchannels,ouchannels,kernel_size,1,padding,dilation=rate),
            nn.BatchNorm2d(ouchannels),
            nn.ReLU(inplace=True)
        )
    def forward(self,x):
        return self.conv(x)


class DeepLab_V2(nn.Module):
    def __init__(self,inchannels,classes):
        super(DeepLab_V2, self).__init__()
        resnet = models.resnet50(pretrained=True,replace_stride_with_dilation=[False, True, True])
        self.backbone = models._utils.IntermediateLayerGetter(resnet,{"layer4": "out"})


        rate = [6,8,12,24]
        self.aspp = Asppmodule
        self.aspp1 = self.aspp(2048,classes,rate[0])
        self.aspp2 = self.aspp(2048, classes, rate[1])
        self.aspp3 = self.aspp(2048, classes, rate[2])
        self.aspp4 = self.aspp(2048, classes, rate[3])


    def forward(self,x):
        x = self.backbone(x)['out']
        x = self.aspp1(x)+self.aspp2(x)+self.aspp3(x)+self.aspp4(x)
        return x

if __name__ == '__main__':
    input = torch.empty(1,3,224,224)
    m = DeepLab_V2(3,10)
    out = m(input)
    print(out)




















<think>好的,我需要帮助用户找到关于Deeplabv3+模型在TensorFlow和PyTorch中的代码实现示例教程。首先,我需要回忆一下用户提供的引用内容,看看里面有没有相关的信息。 根据用户给出的引用[1],里面提到了使用TensorFlow和Keras库创建DeepLabV3Plus模型,并给出了代码示例。这段代码导入了必要的库,调用了`DeeplabV3Plus`类,指定了预训练权重、输入形状和类别数。这应该是一个TensorFlow的实现示例。 然后看引用[2],这里提到了一个更高性能的PyTorch实现的Deeplab-v3plus项目,项目地址是https://gitcode.com/gh_mirrors/de/Deeplab-v3plus。这可能是一个PyTorch代码库,用户可以参考这个项目的README和文档来获取实现细节。 引用[3]提到KerasCV集成了DeepLabv3+,用户可以使用预训练的主干网络进行微调,比如ResNet50_V2和EfficientNetv2_small。这可能是在TensorFlow环境下使用KerasCV库的实现方法。 引用[4]和[5]主要是关于训练自己的数据集和使用指南,可能包含一些脚本和配置说明,但具体的代码实现可能不如前几个引用直接。 接下来,我需要整理这些信息,分TensorFlow和PyTorch两部分给出代码示例,并上相关引用。对于TensorFlow部分,引用[1]和[3]提供了不同的方法,一个是直接使用Keras的DeeplabV3Plus类,另一个是通过KerasCV库。PyTorch部分则引用[2]的项目地址。 需要注意用户提到的代码实现的正确性,比如在TensorFlow中可能需要安装特定的版本或额外的库,比如`keras_cv`。同时,PyTorch的实现可能需要从Git仓库克隆代码,并按照项目文档进行配置。 另外,用户可能需要知道如何加载预训练权重、调整输入尺寸和类别数,以及如何进行训练和推理。这些步骤在引用中都有所涉及,需要简明扼要地说明。 最后,生成相关问题时要围绕Deeplabv3+的实现、训练、微调、应用场景等方面,确保问题具有针对性,帮助用户深入理解。</think>### Deeplabv3+模型代码实现示例 以下是TensorFlow和PyTorch框架下的Deeplabv3+模型实现方法及教程参考: --- #### **TensorFlow/Keras 实现** 1. **使用Keras内置模块** ```python import tensorflow as tf from tensorflow.keras.applications import DeeplabV3Plus # 创建模型(Pascal VOC预训练权重) model = DeeplabV3Plus( weights='pascal_voc', # 可选 'cityscapes' 或其他预训练权重 input_shape=(512, 512, 3), # 输入图像尺寸 classes=21 # 类别数(根据任务调整) ) ``` **说明**: - 直接调用`DeeplabV3Plus`类,需指定输入尺寸和类别数[^1]。 - 支持迁移学习,通过`weights`参数加载预训练模型。 2. **通过KerasCV库实现** ```python import keras_cv model = keras_cv.models.DeepLabV3Plus( backbone="resnet50_v2", # 主干网络选择 num_classes=21, # 类别数 input_shape=(512, 512, 3) # 输入尺寸 ) ``` **说明**: - KerasCV提供更灵活的主干网络(如EfficientNet、ResNet)[^3]。 - 需安装`keras_cv`库:`pip install keras-cv`。 --- #### **PyTorch 实现** 参考开源项目 **[Deeplab-v3plus](https://gitcode.com/gh_mirrors/de/Deeplab-v3plus)**: 1. **克隆仓库并安装依赖** ```bash git clone https://gitcode.com/gh_mirrors/de/Deeplab-v3plus cd Deeplab-v3plus pip install -r requirements.txt ``` 2. **模型定义示例** ```python from model.deeplab import DeepLab model = DeepLab( backbone='resnet', # 可选 'xception' 或 'mobilenet' output_stride=16, # 输出步长(控制特征图分辨率) num_classes=21 # 类别数 ) ``` **说明**: - 该项目提供完整的训练、验证脚本及预训练模型加载功能[^2][^5]。 - 支持多GPU训练和自定义数据集配置[^4]。 --- #### **训练自定义数据集** 1. **数据准备** - 需提供图像和对应的语义分割掩码(PNG格式)。 - 参考[引用4]的脚本进行数据预处理和加载。 2. **微调模型** ```python # TensorFlow示例(加载预训练模型后) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') model.fit(train_dataset, epochs=50, validation_data=val_dataset) ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值