#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. 自制URL转换器

    自定义 url 转换器五个步骤: 定义一个类. 在类中定义一个属性  regex  ,这个属性是用来保存 url 转换器规则的正则表达式. 实现  to_python(self,value)  方法, ...

  2. SpringMVC 拦截器HandlerInterceptor(一)

    HandlerInterceptor 接口: 进入 Handler方法之前执行比如身份认证,如果认证通过表示当前用户没有登陆,需要此方法拦截不再向下执行 boolean preHandle(HttpS ...

  3. vscode ----> 学习笔记

    java开发环境 jdk配置 maven配置 file --> preferences --> settings 在search settings搜索关键词 java.home , mav ...

  4. Oracle 11g streams部署

    环境   源服务器 目标服务器 系统版本 CentOS Linux release 7.3.1611 (Core) CentOS Linux release 7.3.1611 (Core) 主机名 s ...

  5. Linux进程间通信机制

    Linux支持管道.信号.unix system V三种IPC(Inter-Process-Communication)机制.以下分别对三种机制加以简单介绍. 一.信号机制: 信号又称作软中断,用来通 ...

  6. Netflix:我们为什么要将 GraphQL 引入前端架构? (转)

    在刚开始时,Monet 的 React UI 层需要访问由 Tomcat 服务器提供的传统 REST API.随着时间的推移,随着应用程序的发展,我们的用例变得越来越复杂,即使是一个简单页面也需要从各 ...

  7. SQL语句中Left join,right join,inner join用法

    转载于:https://blog.csdn.net/lichkui/article/details/2002895 一.先看一些最简单的例子 例子 Table Aaid   adate 1      ...

  8. unity中鼠标左键控制摄像机视角上下左右移动

    enum RotationAxes { MouseXAndY, MouseX, MouseY } RotationAxes axes = RotationAxes.MouseXAndY; //@Hid ...

  9. [Codeforces477D]Dreamoon and Binary

    Problem 给定一个字符串数的二进制表示(不含前导0)s(长度不超过5000), 对于一个数n(初值为0),可以进行以下两种操作: 1.将n的二进制表示(无前导0)写到已经写的串的后面. 2.n加 ...

  10. Android : 关于HTTPS、TLS/SSL认证以及客户端证书导入方法

    一.HTTPS 简介 HTTPS 全称 HTTP over TLS/SSL(TLS就是SSL的新版本3.1).TLS/SSL是在传输层上层的协议,应用层的下层,作为一个安全层而存在,翻译过来一般叫做传 ...