Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

148 lines
5.9KB

  1. # YOLOv5 experimental modules
  2. import numpy as np # numpy矩阵操作模块
  3. import torch # PyTorch深度学习模块
  4. import torch.nn as nn # PYTorch模块函数库
  5. import os
  6. from models.common import Conv, DWConv
  7. from utils.google_utils import attempt_download
  8. class CrossConv(nn.Module):
  9. # Cross Convolution Downsample
  10. def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
  11. # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
  12. super(CrossConv, self).__init__()
  13. c_ = int(c2 * e) # hidden channels
  14. self.cv1 = Conv(c1, c_, (1, k), (1, s))
  15. self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
  16. self.add = shortcut and c1 == c2
  17. def forward(self, x):
  18. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  19. class Sum(nn.Module):
  20. # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
  21. def __init__(self, n, weight=False): # n: number of inputs
  22. super(Sum, self).__init__()
  23. self.weight = weight # apply weights boolean
  24. self.iter = range(n - 1) # iter object
  25. if weight:
  26. self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
  27. def forward(self, x):
  28. y = x[0] # no weight
  29. if self.weight:
  30. w = torch.sigmoid(self.w) * 2
  31. for i in self.iter:
  32. y = y + x[i + 1] * w[i]
  33. else:
  34. for i in self.iter:
  35. y = y + x[i + 1]
  36. return y
  37. """
  38. Ghost Convolution 幻象卷积 轻量化网络卷积模块
  39. 论文: https://arxiv.org/abs/1911.11907
  40. 源码: https://github.com/huawei-noah/ghostnet
  41. """
  42. class GhostConv(nn.Module):
  43. # Ghost Convolution https://github.com/huawei-noah/ghostnet
  44. def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
  45. super(GhostConv, self).__init__()
  46. c_ = c2 // 2 # hidden channels
  47. self.cv1 = Conv(c1, c_, k, s, None, g, act)
  48. self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
  49. def forward(self, x):
  50. y = self.cv1(x)
  51. return torch.cat([y, self.cv2(y)], 1)
  52. class GhostBottleneck(nn.Module):
  53. # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
  54. def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
  55. super(GhostBottleneck, self).__init__()
  56. c_ = c2 // 2
  57. self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
  58. DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
  59. GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
  60. self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
  61. Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
  62. def forward(self, x):
  63. return self.conv(x) + self.shortcut(x)
  64. class MixConv2d(nn.Module):
  65. # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
  66. def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
  67. super(MixConv2d, self).__init__()
  68. groups = len(k)
  69. if equal_ch: # equal c_ per group
  70. i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
  71. c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
  72. else: # equal weight.numel() per group
  73. b = [c2] + [0] * groups
  74. a = np.eye(groups + 1, groups, k=-1)
  75. a -= np.roll(a, 1, axis=1)
  76. a *= np.array(k) ** 2
  77. a[0] = 1
  78. c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
  79. self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
  80. self.bn = nn.BatchNorm2d(c2)
  81. self.act = nn.LeakyReLU(0.1, inplace=True)
  82. def forward(self, x):
  83. return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
  84. class Ensemble(nn.ModuleList):
  85. # Ensemble of models
  86. def __init__(self):
  87. super(Ensemble, self).__init__()
  88. def forward(self, x, augment=False):
  89. y = []
  90. for module in self:
  91. y.append(module(x, augment)[0])
  92. # y = torch.stack(y).max(0)[0] # max ensemble
  93. # y = torch.stack(y).mean(0) # mean ensemble
  94. y = torch.cat(y, 1) # nms ensemble
  95. return y, None # inference, train output
  96. """用在val.py、detect.py、train.py等文件中 一般用在测试、验证阶段
  97. 加载模型权重文件并构建模型(可以构造普通模型或者集成模型)
  98. Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
  99. :params weights: 模型的权重文件地址 默认weights/yolov5s.pt
  100. 可以是[a]也可以是list格式[a, b] 如果是list格式将调用上面的模型集成函数 多模型运算 提高最终模型的泛化误差
  101. :params map_location: attempt_download函数参数 表示模型运行设备device
  102. :params inplace: pytorch 1.7.0 compatibility设置
  103. """
  104. def attempt_load(weights, map_location=None):
  105. # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
  106. model = Ensemble()
  107. for w in weights if isinstance(weights, list) else [weights]:
  108. #attempt_download(w)
  109. assert os.path.exists(w),"%s not exists"
  110. ckpt = torch.load(w, map_location=map_location) # load
  111. model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
  112. # Compatibility updates
  113. for m in model.modules():
  114. if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
  115. m.inplace = True # pytorch 1.7.0 compatibility
  116. elif type(m) is Conv:
  117. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  118. if len(model) == 1:
  119. return model[-1] # return model
  120. else:
  121. print('Ensemble created with %s\n' % weights)
  122. for k in ['names', 'stride']:
  123. setattr(model, k, getattr(model[-1], k))
  124. return model # return ensemble