【pytorch】目标检测:实现DetNet的block:Detneck 对照网络结构图手动编写

【pytorch】目标检测:实现DetNet的block:Detneck 对照网络结构图手动编写,第1张

DetNet模块,引入了空洞卷积,在增大感受野的同时,保持了特征图尺寸大小不变。


DetNet在保持网络结构中前4个stage与ResNet一致,新增第5及第6个stage专用于检测,主要区别在于,以空洞卷积替换了原有的resnet卷积中的3x3部分,整体不改变输出特征图的大小。




如上图,DetNet的block有两种模式,当block输入通道等于block输出通道的图A,以及带有shortcut,输入通道不等于输出通道的图B。


下面来实现图B所示网络结构模块:

import os.path
from typing import Iterator
import numpy as np
import torch
import cv2
from PIL import Image
from torch.utils.data import Dataset, DataLoader, Subset, random_split
import re
from functools import reduce
from torch.utils.tensorboard import SummaryWriter as Writer
from torchvision import transforms, datasets
import torchvision as tv
from torch import nn
import torch.nn.functional as F
import time
# python中lambda只能跟表达式
cnnWithReluAndBn = lambda indim, outdim, ksize, padding, dilation=1,hasRelu=True: \
    nn.Sequential(nn.Conv2d(indim, outdim, kernel_size=ksize, padding=padding,dilation=dilation), nn.BatchNorm2d(outdim), nn.ReLU(True)) \
        if hasRelu else nn.Sequential(nn.Conv2d(indim, outdim, kernel_size=ksize, padding=padding,dilation=dilation),nn.BatchNorm2d(outdim))

class myCustomerDetneck(nn.Module):
    #inchannel,outchannel为输入及输出的通道数:
    def __init__(self,inchannel,outchanel,hasShortCutCnn=False):
        super().__init__()
        self.mainBranch=[]
        self.shortCut=[]
        #构造主干网络,根据空洞卷积特征图大小计算公式,其等价于一个卷积核大小为3+(3-1)*(2-1)=5的普通卷积,其特征图大小为:s-5+2*2+1=s,输出特征图大小不改变。


self.mainBranch=nn.Sequential(cnnWithReluAndBn(inchannel,outchanel,1,0),cnnWithReluAndBn(outchanel,outchanel,3,2,dilation=2), cnnWithReluAndBn(outchanel,outchanel,1,0,hasRelu=False)) self.shortCutCnn=None #如果shortcut上包含普通卷积,则普通卷积是一个1X1调节输出通道数的卷积 if hasShortCutCnn: self.shortCutCnn=cnnWithReluAndBn(inchannel,outchanel,1,0,hasRelu=False) def forward(self,x): x1 = self.mainBranch(x) if self.shortCut is not None: return nn.ReLU(False)(x1 + self.shortCutCnn(x)) else: return nn.ReLU(False)(x1 + x) #进行实际测试: myNet=myCustomerDetneck(3,16,True) k = torch.rand(1, 3, 56, 56) print(myNet(k).shape)

输出结果为:

torch.Size([1, 16, 56, 56])

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/570842.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存