pytorch复现MobieNetV2


python 复制代码
import torch
import torch.nn as nn


def _make_divisible(ch, divisor=8, min_ch=None):
    """
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    """
    if min_ch is None:
        min_ch = divisor
    new_ch = max(min_ch, int(ch + divisor / 2) // divisor * divisor)
    # Make sure that round down does not go down by more than 10%.
    if new_ch < 0.9 * ch:
        new_ch += divisor
    return new_ch

class ConvBNReLU(nn.Sequential):
    def __init__(self, in_channel, out_channel, kernel_size=3, stride=1, groups=1):
        padding = (kernel_size - 1) // 2
        super(ConvBNReLU, self).__init__(
            nn.Conv2d(in_channel, out_channel, kernel_size, stride, padding, groups=groups, bias=False),
            nn.BatchNorm2d(out_channel),
            nn.ReLU6(inplace=True)
        )


class InvertedResidual(nn.Module):
    def __init__(self, in_channel, out_channel, stride, expand_ration):
        super(InvertedResidual, self).__init__()
        hidden_channel = in_channel * expand_ration
        self.use_shortcut = (stride==1 and in_channel==out_channel)

        layers = []

        if expand_ration != 1:
            layers.append(ConvBNReLU(in_channel, hidden_channel, kernel_size=1))

        #extent 添加多个元素
        layers.extend([
            #group=1 就是普通卷积, group=hidden_channel 就是depthwise卷积
            ConvBNReLU(hidden_channel, hidden_channel, stride=stride, groups=hidden_channel),
            nn.Conv2d(hidden_channel, out_channel, kernel_size=1, bias=False),
            nn.BatchNorm2d(out_channel)
        ])

        self.conv = nn.Sequential(*layers)


    def forward(self, x):
        if self.use_shortcut:
            return x+self.conv(x)
        else:
            return self.conv(x)


class MobileNetV2(nn.Module):
    def __init__(self, num_classes=1000, alpha=1.0, round_nearest=8):
        super(MobileNetV2, self).__init__()
        block = InvertedResidual
        #使通道数32*alpha 变成最接近 round_nearest 的整倍数
        input_channel = _make_divisible(32 * alpha, round_nearest)
        last_channel = _make_divisible(1280 * alpha, round_nearest)

        '''
            t:扩展因子
            c:输出特征矩阵深度channel
            n:bottleneck的重复次数
            s:步距
        '''
        inverted_residuals_setting =[

            #t, c, n, s
            [1, 16, 1, 1],
            [6, 24, 2, 2],
            [6, 32, 3, 2],
            [6, 64, 4, 2],
            [6, 96, 3, 1],
            [6, 160, 3, 2],
            [6, 320, 1, 1]
        ]

        features = []
        #conv1 layer
        features.append(ConvBNReLU(3, input_channel, stride=2))

        for t, c, n, s in inverted_residuals_setting:
            output_channel = _make_divisible(c*alpha, round_nearest)
            for i in range(n):
                #每个n层bottleneck中只有第一层的stride=s, 剩余的层stride=1
                stride = s if i == 0 else 1
                features.append(block(input_channel, output_channel, stride, expand_ration=t))
                input_channel = output_channel

        features.append(ConvBNReLU(input_channel, last_channel, 1))

        self.features = nn.Sequential(*features)

        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))

        self.classifier = nn.Sequential(
            nn.Dropout(0.2),
            nn.Linear(last_channel, num_classes)
        )

        # weight initialization
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.ones_(m.weight)
                nn.init.zeros_(m.bias)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.zeros_(m.bias)

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x
相关推荐
今天也要加油丫3 分钟前
`re.compile(r“(<.*?>)“)` 如何有效地从给定字符串中提取出所有符合 `<...>` 格式的引用
python
jndingxin13 分钟前
OpenCV特征检测(1)检测图像中的线段的类LineSegmentDe()的使用
人工智能·opencv·计算机视觉
@月落23 分钟前
alibaba获得店铺的所有商品 API接口
java·大数据·数据库·人工智能·学习
z千鑫32 分钟前
【人工智能】如何利用AI轻松将java,c++等代码转换为Python语言?程序员必读
java·c++·人工智能·gpt·agent·ai编程·ai工具
MinIO官方账号1 小时前
从 HDFS 迁移到 MinIO 企业对象存储
人工智能·分布式·postgresql·架构·开源
aWty_1 小时前
机器学习--K-Means
人工智能·机器学习·kmeans
草莓屁屁我不吃1 小时前
AI大语言模型的全面解读
人工智能·语言模型·自然语言处理·chatgpt
农民小飞侠1 小时前
python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能
开发语言·python
战神刘玉栋1 小时前
《程序猿之设计模式实战 · 观察者模式》
python·观察者模式·设计模式
敲代码不忘补水1 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践