#densenet原文地址 https://arxiv.org/abs/1608.06993 
#densenet介绍 https://blog.csdn.net/zchang81/article/details/76155291
#以下代码就是densenet在torchvision.models里的源码,为了提高自身的模型构建能力尝试分析下源代码:
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict __all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161'] model_urls = {
'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth',
'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',
'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth',
} #这个是预训练模型可以在下边的densenet121,169等里直接在pretrained=True就可以下载 def densenet121(pretrained=False, **kwargs): #这是densenet121 返回一个在ImageNet上的预训练模型 #
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16),
**kwargs) #这里是模型的主要构建,使用了DenseNet类 直接就看Densenet类#
if pretrained:
# '.'s are no longer allowed in module names, but pervious _DenseLayer
# has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
# They are also in the checkpoints in model_urls. This pattern is used
# to find such keys.
pattern = re.compile(
r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
state_dict = model_zoo.load_url(model_urls['densenet121'])
for key in list(state_dict.keys()):
res = pattern.match(key)
if res:
new_key = res.group(1) + res.group(2)
state_dict[new_key] = state_dict[key]
del state_dict[key]
model.load_state_dict(state_dict)
return model
#把densenet169等就删除了,和上边的结构相同。 # class DenseNet(nn.Module): #这就是densenet的主类了,看继承了nn.Modele类 #
r"""Densenet-BC model class, based on
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args:
growth_rate (int) - how many filters to add each layer (`k` in paper) #每个denseblock里应该,每个Layer的输出特征数,就是论文里的k #
block_config (list of 4 ints) - how many layers in each pooling block #每个denseblock里layer层数, block_config的长度表示block的个数 #
num_init_features (int) - the number of filters to learn in the first convolution layer #初始化层里卷积输出的channel数#
bn_size (int) - multiplicative factor for number of bottle neck layers #这个是在block里一个denselayer里两个卷积层间的channel数 需要bn_size*growth_rate #
(i.e. bn_size * k features in the bottleneck layer)
drop_rate (float) - dropout rate after each dense layer #dropout的概率,正则化的方法 #
num_classes (int) - number of classification classes #输出的类别数,看后边接的是linear,应该最后加损失函数的时候应该加softmax,或者交叉熵,而且是要带计算概率的函数 #
"""
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),
num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000): super(DenseNet, self).__init__() # First convolution #初始化层,图像进来后不是直接进入denseblock,先使用大的卷积核,大步长,进一步压缩图像尺寸 #
     # 注意的是nn.Sequential的用法,ordereddict使用的方法,给layer命名,还有就是各层的排列,conv->bn->relu->pool 经过这一个操作就是尺寸就成为了1/4,数据量压缩了#
self.features = nn.Sequential(OrderedDict([
('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),
('norm0', nn.BatchNorm2d(num_init_features)),
('relu0', nn.ReLU(inplace=True)),
('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
])) #这里使用了batchnorm2d batchnorm 最近有group norm 是否可以换 # # Each denseblock 创建denseblock
num_features = num_init_features
for i, num_layers in enumerate(block_config): #根据block_config里关于每个denseblock里的layer数量产生响应的block #
block = _DenseBlock(num_layers=num_layers, num_input_features=num_features,
bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate) #这是产生一个denseblock #
self.features.add_module('denseblock%d' % (i + 1), block) #加入到 nn.Sequential 里 #
num_features = num_features + num_layers * growth_rate #每一个denseblock最后输出的channel,因为是dense连接所以原始的输出有,也有内部每一层的特征 #
if i != len(block_config) - 1: #如果不是最后一层 #
trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2) #transition层是压缩输出的特征数量为一半#
self.features.add_module('transition%d' % (i + 1), trans)
num_features = num_features // 2 # Final batch norm
self.features.add_module('norm5', nn.BatchNorm2d(num_features)) # Linear layer
self.classifier = nn.Linear(num_features, num_classes) # Official init from torch repo.
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal(m.weight.data)
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_() def forward(self, x):
features = self.features(x)
out = F.relu(features, inplace=True)
out = F.avg_pool2d(out, kernel_size=7, stride=1).view(features.size(0), -1)
out = self.classifier(out)
return out
class _DenseLayer(nn.Sequential):    #这是denselayer,也是nn.Seqquential,看来要好好学习用法 #
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):
super(_DenseLayer, self).__init__()
self.add_module('norm1', nn.BatchNorm2d(num_input_features)), #这里要看到denselayer里其实主要包括两个卷积层,而且他们的channel数值得关注 #
self.add_module('relu1', nn.ReLU(inplace=True)), #其实在add_module后边的逗号可以去掉,没有任何意义,又不是构成元组徒增歧义 #
self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *
growth_rate, kernel_size=1, stride=1, bias=False)),
self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)),
self.add_module('relu2', nn.ReLU(inplace=True)),
self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,
kernel_size=3, stride=1, padding=1, bias=False)), #这里注意的是输出的channel数是growth_rate #
self.drop_rate = drop_rate def forward(self, x): #这里是前传,主要解决的就是要把输出整形,把layer的输出和输入要cat在一起 #
new_features = super(_DenseLayer, self).forward(x) # #
if self.drop_rate > 0:
new_features = F.dropout(new_features, p=self.drop_rate, training=self.training) #加入dropout增加泛化 #
return torch.cat([x, new_features], 1) #在channel上cat在一起,以形成dense连接 # class _DenseBlock(nn.Sequential): #是nn.Sequential的子类,将一个block里的layer组合起来 #
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size, drop_rate) #后一层的输入channel是该denseblock的输入channel数,加上该层前面层的channnel数的和 #
self.add_module('denselayer%d' % (i + 1), layer) class _Transition(nn.Sequential): #是nn.Sequential的子类,#这个就比较容易了,也是以后自己搭建module的案例#
    def __init__(self, num_input_features, num_output_features):
        super(_Transition, self).__init__()
        self.add_module('norm', nn.BatchNorm2d(num_input_features))
        self.add_module('relu', nn.ReLU(inplace=True))
        self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,
                                          kernel_size=1, stride=1, bias=False))
        self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))'pool', nn.AvgPool2d(kernel_size=2, stride=2))

大概就是这样,作为去年最好的分类框架densenet,里边有很多学习的地方。

可以给自己搭建网络提供参考。

torchvision里densenet代码分析的更多相关文章

  1. angular代码分析之异常日志设计

    angular代码分析之异常日志设计 错误异常是面向对象开发中的记录提示程序执行问题的一种重要机制,在程序执行发生问题的条件下,异常会在中断程序执行,同时会沿着代码的执行路径一步一步的向上抛出异常,最 ...

  2. WordPress HOOK机制原理及代码分析

    WordPress强大的插件机制让我们可以自由扩展功能.网上对插件的使用以及开发方法都有大量资料可以查询. 今天我们就分析一下四个主要函数的代码,包括: add_action.do_action.ad ...

  3. AngularJS PhoneCat代码分析

    转载自:http://www.tuicool.com/articles/ym6Jfen AngularJS 官方网站提供了一个用于学习的示例项目:PhoneCat.这是一个Web应用,用户可以浏览一些 ...

  4. Linux内核启动代码分析二之开发板相关驱动程序加载分析

    Linux内核启动代码分析二之开发板相关驱动程序加载分析 1 从linux开始启动的函数start_kernel开始分析,该函数位于linux-2.6.22/init/main.c  start_ke ...

  5. 阅读代码分析工具Understand 2.0试用

    Understand 2.0是一款源码阅读分析软件,功能强大.试用过一段时间后,感觉相当不错,确实能够大大提高代码阅读效率. 因为Understand功能十分强大,本文不可能详尽地介绍它的全部功能,所 ...

  6. cocos2d-x v3.2 FlappyBird 各个类对象详细代码分析(6)

    今天我们要讲三个类,这三个类应该算比較简单的 HelpLayer类 NumberLayer类 GetLocalScore类 HelpLayer类,主要放了两个图形精灵上去,一个是游戏的名字,一个是提示 ...

  7. twemproxy接收流程探索——twemproxy代码分析正编

    在这篇文章开始前,大家要做好一个小小的心理准备,由于twemproxy代码是一份优秀的c语言,为此,在twemproxy的代码中会大篇幅使用c指针.但是不论是普通类型的指针还是函数指针,都可以让我们这 ...

  8. 使用代码分析来分析托管代码质量 之 CA2200

    vs的代码分析功能:vs菜单 “生成”下面有“对解决方案运行代码分析 Alt+F11”和“对[当前项目]运行代码分析”2个子菜单. 使用这个功能,可以对托管代码运行代码分析,发现代码中的缺陷和潜在问题 ...

  9. Spring AOP实现声明式事务代码分析

    众所周知,Spring的声明式事务是利用AOP手段实现的,所谓"深入一点,你会更快乐",本文试图给出相关代码分析. AOP联盟为增强定义了org.aopalliance.aop.A ...

随机推荐

  1. 要想成为前端大神,那些你不得不知晓的web前端命名规范。

    一.Web语义化 1.1 H5的语义化 对于经验资深的前端er,在给web布局时,相信都会很注重标签和命名的规范.尤其是随着html5的普及发展,更是把web前端语义化推向一个新的台阶上.比如html ...

  2. maven 如何使用

    以前没有用过maven管理过项目的依赖,最后使用上了maven,发现通过不能方式建立出来的web应用程序目录结构基本都不一样,既然每次都要到网上搜索如何建立maven管理的Web应用程序,不如自己找百 ...

  3. Linux下的串口调试工具——Xgcom

    Linux下的串口调试工具——Xgcom xgcom的下载网址:https://code.google.com/archive/p/xgcom/downloads (1)安装必须的库 apt-get ...

  4. 【Core】.NET Core 部署( Docker + CentOS)

    CentOS 下 Docker安装 使用脚本安装 Docker (1)安装docker  sudo yum install docker (2)启动docker systemctl  start do ...

  5. QT编程环境

    (1)QT的工具 ① assistant 帮助手册 ② qmake -v 查看qt版本 ③ qmake -project 可以把项目的源文件组织成项目的描述文件 .pro ④ qmake 可以根据.p ...

  6. 如何在nginx容器中使用ping、nslookup、ip、curl 等工具?

    Nginx镜像太精简了,启动一个容器进行测试时,常用的网络工具都没有,可以使用下面的命令进行安装.也可以直接起一个busybox容器进行测试. apt update #ping apt install ...

  7. laravel 资源篇

    转自:https://github.com/qianyugang/learn-laravel # Learn-Laravel — 学习资料和开源项目集 ## Laravel 学习资料 ### 官方网站 ...

  8. 『计算机视觉』感受野和anchor

    原文链接:关于感受野的总结 论文链接:Understanding the Effective Receptive Field in Deep Convolutional Neural Networks ...

  9. vue中提示toFixed不是函数

     vue中toFixed获取小数点后两位 错误提示:.toFixed is not a function解决办法:Number(_this.group_cash).toFixed(2) 转自:http ...

  10. 【阅读笔记】《C程序员 从校园到职场》第七章 指针和结构体

    原文地址:让你提前认识软件开发(13):指针及结构体的使用 CSDN博客 https://blog.csdn.net/zhouzhaoxiong1227/article/details/2387299 ...