torchvision里densenet代码分析
#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代码分析的更多相关文章
- angular代码分析之异常日志设计
angular代码分析之异常日志设计 错误异常是面向对象开发中的记录提示程序执行问题的一种重要机制,在程序执行发生问题的条件下,异常会在中断程序执行,同时会沿着代码的执行路径一步一步的向上抛出异常,最 ...
- WordPress HOOK机制原理及代码分析
WordPress强大的插件机制让我们可以自由扩展功能.网上对插件的使用以及开发方法都有大量资料可以查询. 今天我们就分析一下四个主要函数的代码,包括: add_action.do_action.ad ...
- AngularJS PhoneCat代码分析
转载自:http://www.tuicool.com/articles/ym6Jfen AngularJS 官方网站提供了一个用于学习的示例项目:PhoneCat.这是一个Web应用,用户可以浏览一些 ...
- Linux内核启动代码分析二之开发板相关驱动程序加载分析
Linux内核启动代码分析二之开发板相关驱动程序加载分析 1 从linux开始启动的函数start_kernel开始分析,该函数位于linux-2.6.22/init/main.c start_ke ...
- 阅读代码分析工具Understand 2.0试用
Understand 2.0是一款源码阅读分析软件,功能强大.试用过一段时间后,感觉相当不错,确实能够大大提高代码阅读效率. 因为Understand功能十分强大,本文不可能详尽地介绍它的全部功能,所 ...
- cocos2d-x v3.2 FlappyBird 各个类对象详细代码分析(6)
今天我们要讲三个类,这三个类应该算比較简单的 HelpLayer类 NumberLayer类 GetLocalScore类 HelpLayer类,主要放了两个图形精灵上去,一个是游戏的名字,一个是提示 ...
- twemproxy接收流程探索——twemproxy代码分析正编
在这篇文章开始前,大家要做好一个小小的心理准备,由于twemproxy代码是一份优秀的c语言,为此,在twemproxy的代码中会大篇幅使用c指针.但是不论是普通类型的指针还是函数指针,都可以让我们这 ...
- 使用代码分析来分析托管代码质量 之 CA2200
vs的代码分析功能:vs菜单 “生成”下面有“对解决方案运行代码分析 Alt+F11”和“对[当前项目]运行代码分析”2个子菜单. 使用这个功能,可以对托管代码运行代码分析,发现代码中的缺陷和潜在问题 ...
- Spring AOP实现声明式事务代码分析
众所周知,Spring的声明式事务是利用AOP手段实现的,所谓"深入一点,你会更快乐",本文试图给出相关代码分析. AOP联盟为增强定义了org.aopalliance.aop.A ...
随机推荐
- tomcat启动后8005端口未被占用
8005端口是tomcat本身的端口,如果这个端口在启动时未被tomcat占用的话,就无法使用它自带的shutdown.sh脚本关闭tomcat 接下来我以tomcat-9.0.12为例说明 下载to ...
- 友盟分享因为Bundle Id 校验不通过 无法分享到微信
微信分享应用里面资料有个APP bundle id需要填的, 以前申请的时候不需要填也可以正常分享, 但是最近开始微信需要验证, 在那填上APP对应bundle ID 就可以了
- SSM获取表单数据插入数据库并返回插入记录的ID值
以下指示插入操作以及获取记录值的ID的部分操作代码!!! 首先是简单的表单实现 <%@ page language="java" contentType="text ...
- java笔记 -- 类与对象
封装: 从形式上看, 封装是将数据和行为组合在一个包中, 并对对象的使用者隐藏了数据的实现方式. 对象中的数据称为实例域, 操纵数据的过程称为方法. 对于每个特定的类实例(对象)都有一组特定的实例域值 ...
- 非递归遍历N-ary树Java实现
2019-03-25 14:10:51 非递归遍历二叉树的Java版本实现之前已经进行了总结,这次做的是非递归遍历多叉树的Java版本实现. 在非递归遍历二叉树的问题中我个人比较推荐的是使用双whil ...
- Python自学:第二章 使用函数str( )避免类型错误
age = 23 message = "Happy " + str(age) + "rd Birthday" print(message) 输出位 Happy ...
- jq初入行常用动画
--jq动画分类--(1)jQuery的动画其实就是将之前提到过的各种特效进行封装,并对其性能进行优化.(2)jQuery动画分为三个部分:非自定义动画,自定义动画,和全局动画设置. 一.非自定义动画 ...
- SSH框架学习摸索记
Unable to load configuration. - bean - jar:file:/E:/tomcat-7.0.11/webapps/struts/WEB-INF/lib/struts ...
- 微信小程序textarea组件在fixed定位中随页面滚动
如果 textarea 是在一个 position:fixed 的区域,需要显示指定属性 fixed 为 true https://developers.weixin.qq.com/miniprogr ...
- Php的基本语法学习
1.php语法 当 PHP 解析一个文件时,会寻找开始和结束标记,标记告诉 PHP 开始和停止解释其中的代码. 1)标记语法 是以<?php 开头,?> 结束,相当于html标签的开始标签 ...