mobilenet + resnet

import torch
import torch.nn as nn
import torchvision
import numpy as np
 
print("PyTorch Version: ",torch.__version__)
print("Torchvision Version: ",torchvision.__version__)
 
__all__ = ['ResNet50', 'ResNet101','ResNet152']
 
def Conv1(in_planes, places, stride=2):
    return nn.Sequential(
        nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
        nn.BatchNorm2d(places),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
    )
 
class Bottleneck(nn.Module):
    def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 4):
        super(Bottleneck,self).__init__()
        self.expansion = expansion
        self.downsampling = downsampling
 
        self.bottleneck = nn.Sequential(
            nn.Conv2d(in_channels=in_places,out_channels=places,kernel_size=1,stride=1, bias=False),
            nn.BatchNorm2d(places),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(places),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_channels=places, out_channels=places*self.expansion, kernel_size=1, stride=1, bias=False),
            nn.BatchNorm2d(places*self.expansion),
        )
 
        if self.downsampling:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(places*self.expansion)
            )
        self.relu = nn.ReLU(inplace=True)
    def forward(self, x):
        residual = x
        out = self.bottleneck(x)
 
        if self.downsampling:
            residual = self.downsample(x)
 
        out += residual
        out = self.relu(out)
        return out
 
class ResNet(nn.Module):
    def __init__(self,blocks, num_classes=1000, expansion = 4):
        super(ResNet,self).__init__()
        self.expansion = expansion
 
        self.conv1 = Conv1(in_planes = 3, places= 64)
 
        self.layer1 = self.make_layer(in_places = 64, places= 64, block=blocks[0], stride=1)
        self.layer2 = self.make_layer(in_places = 256,places=128, block=blocks[1], stride=2)
        self.layer3 = self.make_layer(in_places=512,places=256, block=blocks[2], stride=2)
        self.layer4 = self.make_layer(in_places=1024,places=512, block=blocks[3], stride=2)
 
        self.avgpool = nn.AvgPool2d(7, stride=1)
        self.fc = nn.Linear(2048,num_classes)
 
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
 
    def make_layer(self, in_places, places, block, stride):
        layers = []
        layers.append(Bottleneck(in_places, places,stride, downsampling =True))
        for i in range(1, block):
            layers.append(Bottleneck(places*self.expansion, places))
 
        return nn.Sequential(*layers)
 
 
    def forward(self, x):
        x = self.conv1(x)
 
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
 
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x
 
def ResNet50():
    return ResNet([3, 4, 6, 3])
 
def ResNet101():
    return ResNet([3, 4, 23, 3])
 
def ResNet152():
    return ResNet([3, 8, 36, 3])
 
 
if __name__=='__main__':
    #model = torchvision.models.resnet50()
    model = ResNet50()
    print(model)
 
    input = torch.randn(1, 3, 224, 224)
    out = model(input)
    print(out.shape)
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary


class Block(nn.Module):
    '''Depthwise conv + Pointwise conv'''

    def __init__(self, in_planes, out_planes, stride=1):
        super(Block, self).__init__()
        # 深度卷积,通道数不变,用于缩小特征图大小
        self.conv1 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride, padding=1, groups=in_planes,
                               bias=False)
        #当groups = in_channel时,是在做的depth-wise conv的,具体思想可以参考MobileNet那篇论文。
        self.bn1 = nn.BatchNorm2d(in_planes)
        # 逐点卷积,用于增大通道数
        self.conv2 = nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
        self.bn2 = nn.BatchNorm2d(out_planes)

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = F.relu(self.bn2(self.conv2(out)))
        return out


class MobileNet(nn.Module):
    cfg = [
        64, (128, 2), 128, (256, 2), 256, (512, 2), 512, 512, 512, 512, 512, (1024, 2), 1024
    ]
# O = (I - K + 2P)/ S +1
    def __init__(self, num_classes=10):
        super(MobileNet, self).__init__()
        # 首先是一个标准卷积
        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(32)

        # 然后堆叠深度可分离卷积
        self.layers = self._make_layers(in_planes=32)

        self.linear = nn.Linear(1024, num_classes)  # 输入的特征图大小为1024,输出特征图大小为10

    def _make_layers(self, in_planes):
        laters = []  # 将每层添加到此列表
        for x in self.cfg:
            out_planes = x if isinstance(x, int) else x[0]  # isinstance返回的是一个布尔值
            stride = 1 if isinstance(x, int) else x[1]
            laters.append(Block(in_planes, out_planes, stride))
            in_planes = out_planes
        return nn.Sequential(*laters)

    def forward(self, x):
        # 一个普通卷积
        out = F.relu(self.bn1(self.conv1(x)))
        # 叠加深度可分离卷积
        out = self.layers(out)
        # 平均池化层会将feature变成1x1
        out = F.avg_pool2d(out, 7)
        # 展平
        out = out.view(out.size(0), -1)
        # 全连接层
        out = self.linear(out)
        # softmax层
        output = F.softmax(out, dim=1)
        return output


def test():
    net = MobileNet()
    x = torch.randn(1, 3, 224, 224)  # 输入一组数据,通道数为3,高度为224,宽度为224
    y = net(x)
    print(y.size())
    print(y)
    print(torch.max(y, dim=1))


test()
net = MobileNet()
print(net)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值