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

    该表配置可以坐骑的使用区域,可能需要修改spell.dbc,允许在室内等特殊区域使用坐骑技能

  2. redis+spring 整合

    最近在研究redis也结合了许多网上的资料分享给大家,有些不足的还望大家多补充提点,下面直接进入主题. 结构图: 几个redis的核心jar,spring的一些jar自行导入 接下来开始配置项目: 1 ...

  3. 【三】jquery之选择器

    转自:https://www.cnblogs.com/youfeng365/p/5846650.html jquery参考手册:http://jquery.cuishifeng.cn/index.ht ...

  4. 自我学习成长系列之<<FirstHead设计模式>>

    第一章 设计模式入门 1.好词好句: 好的设计是可以应付改变. 2.驱动改变的因素:(a)客户需求不清晰,后期会一直变 (b)遇到坑爹的产品,自己不会全扔给程序员 (c)在开发过程中,产生一个新概念, ...

  5. 『Python CoolBook:Collections』数据结构和算法_collections.deque队列&yield应用

    一.collections.deque队列 deque(maxlen=N)构造函数会新建一个固定大小的队列.当新的元素加入并且这个队列已满的时候,最老的元素会自动被移除掉. 如果你不设置最大队列大小, ...

  6. 如果SQL Server 配置管理器没有找到就代表安装失败?

    如果SQL Server 配置管理器没有找到就代表安装失败? 2017-05-09 17:58 124人阅读 评论(0) 收藏 举报 版权声明:本文为博主原创文章,未经博主允许不得转载. 首先,只要你 ...

  7. [cf div 2 706E] Working routine

    [cf div 2 706E] Working routine Vasiliy finally got to work, where there is a huge amount of tasks w ...

  8. 学习笔记——SM2算法原理及实现

    RSA算法的危机在于其存在亚指数算法,对ECC算法而言一般没有亚指数攻击算法 SM2椭圆曲线公钥密码算法:我国自主知识产权的商用密码算法,是ECC(Elliptic Curve Cryptosyste ...

  9. css样式 + 特殊符号

    color控制字体颜色 十六进制值 #cc0066: font-size控制字体大小 单位 px / % / em / rem:像素 / 相对于父级元素 / 取决自己使用字体大小 / 取决于根元素ht ...

  10. HTML⑤

    W3C : 万维网联盟!(World Wide Web Consortium ) 创建于1994年,是web技术领域最权威最具有影响力的标准机构! W3C规定了web技术领域相关技术的标准! 官网地址 ...