PSPNet-Model(pytorch版本)

P S P N e t − M o d e l ( p y t o r c h 版 本 ) PSPNet-Model(pytorch版本) PSPNetModel(pytorch)

训练、验证代码逻辑




All.ipynb

import torch
from torch import nn
from torch.nn import functional as F
import extractors
import warnings
warnings.filterwarnings("ignore")
class PSPModule(nn.Module):
    def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):
        super().__init__()
        self.stages = []
        self.stages = nn.ModuleList([self._make_stage(features, size) for size in sizes])
        self.bottleneck = nn.Conv2d(features * (len(sizes) + 1), out_features, kernel_size=1)
        self.relu = nn.ReLU()

    def _make_stage(self, features, size):
        prior = nn.AdaptiveAvgPool2d(output_size=(size, size))
        conv = nn.Conv2d(features, features, kernel_size=1, bias=False)
        return nn.Sequential(prior, conv)

    def forward(self, feats):
        h, w = feats.size(2), feats.size(3)
        print(feats.size())
        priors = [F.upsample(input=stage(feats), size=(h, w), mode='bilinear') for stage in self.stages] + [feats]
        bottle = self.bottleneck(torch.cat(priors, 1))
        return self.relu(bottle)


class PSPUpsample(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, 3, padding=1),
            nn.BatchNorm2d(out_channels),
            nn.PReLU()
        )

    def forward(self, x):
        h, w = 2 * x.size(2), 2 * x.size(3)
        p = F.upsample(input=x, size=(h, w), mode='bilinear')
        return self.conv(p)


class PSPNet(nn.Module):
    def __init__(self, n_classes=18, sizes=(1, 2, 3, 6), psp_size=2048, deep_features_size=256, backend='resnet34',
                 pretrained=False):
        super().__init__()
        self.feats = getattr(extractors, backend)(pretrained)
        self.psp = PSPModule(psp_size, 1024, sizes)
        self.drop_1 = nn.Dropout2d(p=0.3)

        self.up_1 = PSPUpsample(1024, 256)
        self.up_2 = PSPUpsample(256, 64)
        self.up_3 = PSPUpsample(64, 64)

        self.drop_2 = nn.Dropout2d(p=0.15)
        self.final = nn.Sequential(
            nn.Conv2d(64, n_classes, kernel_size=1),
            nn.LogSoftmax()
        )

        self.classifier = nn.Sequential(
            nn.Linear(deep_features_size, 256),
            nn.ReLU(),
            nn.Linear(256, n_classes)
        )

    def forward(self, x):
        print('x:', x.size())
        f, class_f = self.feats(x);print('f:', f.size());print('class_f:', class_f.size());
        p = self.psp(f);print('p:', p.size())
        p = self.drop_1(p);print('p:', p.size())

        p = self.up_1(p);print('p:', p.size())
        p = self.drop_2(p);print('p:', p.size())

        p = self.up_2(p);print('p:', p.size())
        p = self.drop_2(p);print('p:', p.size())

        p = self.up_3(p);print('p:', p.size())
        p = self.drop_2(p);print('p:', p.size())

        auxiliary = F.adaptive_max_pool2d(input=class_f, output_size=(1, 1)).view(-1, class_f.size(1));print('auxiliary:', auxiliary.size())

        res1 = self.final(p);print('res1:', res1.size())
        res2 = self.classifier(auxiliary);print('res2:', res2.size())

        return res1 , res2
# 随机生成输入数据
rgb = torch.randn(1, 3, 512, 512)
# 定义网络
net = PSPNet(psp_size=512,n_classes=8,deep_features_size=256)
# 前向传播
out, out_cls = net(rgb)
# 打印输出大小
print('---out--'*5)
print(out.shape)
print('--out_cls---'*5)
print(out_cls)
print('-----'*5)

在这里插入图片描述

PSPNet(Pyramid Scene Parsing Network)是一种用于图像语义分割的深度学习模型,它通过利用金字塔池化和空洞卷积等技术来提取不同尺度的特征信息,并结合全局上下文信息进行像素级别的分类。下面是PSPNetPyTorch代码的简要介绍: 1. 导入所需的库和模块: ```python import torch import torch.nn as nn import torch.nn.functional as F ``` 2. 定义PSPNet模型的主体结构: ```python class PSPNet(nn.Module): def __init__(self, num_classes): super(PSPNet, self).__init__() # 定义各个模块的结构 def forward(self, x): # 定义前向传播过程 return x ``` 3. 定义PSPNet中使用的各个模块,如PSP模块、ResNet等: ```python class PSPModule(nn.Module): def __init__(self, in_channels, sizes=(1, 2, 3, 6)): super(PSPModule, self).__init__() # 定义PSP模块的结构 class ResNet(nn.Module): def __init__(self, block, layers): super(ResNet, self).__init__() # 定义ResNet的结构 class Bottleneck(nn.Module): def __init__(self, in_channels, out_channels, stride=1, dilation=1): super(Bottleneck, self).__init__() # 定义Bottleneck的结构 ``` 4. 在PSPNet模型中使用定义好的模块: ```python class PSPNet(nn.Module): def __init__(self, num_classes): super(PSPNet, self).__init__() self.resnet = ResNet(Bottleneck, [3, 4, 23, 3]) self.psp = PSPModule(2048) self.final_conv = nn.Conv2d(4096, num_classes, kernel_size=1) def forward(self, x): # 前向传播过程中使用各个模块 x = self.resnet(x) x = self.psp(x) x = self.final_conv(x) return x ``` 这只是PSPNet代码的一个简要介绍,实际的代码可能更加复杂,包括数据加载、损失函数的定义、训练和测试等部分。如果你对PSPNet的代码实现有更具体的问题,可以提出来,我会尽力回答。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值