用kafka接收消息
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.

ccnet.py 5.4KB

2 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. """Criss-Cross Network"""
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from core.nn import CrissCrossAttention
  6. from core.models.segbase import SegBaseModel
  7. from core.models.fcn import _FCNHead
  8. #失败:NameError: name '_C' is not defined
  9. __all__ = ['CCNet', 'get_ccnet', 'get_ccnet_resnet50_citys', 'get_ccnet_resnet101_citys',
  10. 'get_ccnet_resnet152_citys', 'get_ccnet_resnet50_ade', 'get_ccnet_resnet101_ade',
  11. 'get_ccnet_resnet152_ade']
  12. class CCNet(SegBaseModel):
  13. r"""CCNet
  14. Parameters
  15. ----------
  16. nclass : int
  17. Number of categories for the training dataset.
  18. backbone : string
  19. Pre-trained dilated backbone network type (default:'resnet50'; 'resnet50',
  20. 'resnet101' or 'resnet152').
  21. norm_layer : object
  22. Normalization layer used in backbone network (default: :class:`nn.BatchNorm`;
  23. for Synchronized Cross-GPU BachNormalization).
  24. aux : bool
  25. Auxiliary loss.
  26. Reference:
  27. Zilong Huang, et al. "CCNet: Criss-Cross Attention for Semantic Segmentation."
  28. arXiv preprint arXiv:1811.11721 (2018).
  29. """
  30. def __init__(self, nclass, backbone='resnet50', aux=False, pretrained_base=True, **kwargs):
  31. super(CCNet, self).__init__(nclass, aux, backbone, pretrained_base=pretrained_base, **kwargs)
  32. self.head = _CCHead(nclass, **kwargs)
  33. if aux:
  34. self.auxlayer = _FCNHead(1024, nclass, **kwargs)
  35. self.__setattr__('exclusive', ['head', 'auxlayer'] if aux else ['head'])
  36. def forward(self, x):
  37. size = x.size()[2:]
  38. _, _, c3, c4 = self.base_forward(x)
  39. outputs = list()
  40. x = self.head(c4)
  41. x = F.interpolate(x, size, mode='bilinear', align_corners=True)
  42. outputs.append(x)
  43. if self.aux:
  44. auxout = self.auxlayer(c3)
  45. auxout = F.interpolate(auxout, size, mode='bilinear', align_corners=True)
  46. outputs.append(auxout)
  47. return tuple(outputs)
  48. class _CCHead(nn.Module):
  49. def __init__(self, nclass, norm_layer=nn.BatchNorm2d, **kwargs):
  50. super(_CCHead, self).__init__()
  51. self.rcca = _RCCAModule(2048, 512, norm_layer, **kwargs)
  52. self.out = nn.Conv2d(512, nclass, 1)
  53. def forward(self, x):
  54. x = self.rcca(x)
  55. x = self.out(x)
  56. return x
  57. class _RCCAModule(nn.Module):
  58. def __init__(self, in_channels, out_channels, norm_layer, **kwargs):
  59. super(_RCCAModule, self).__init__()
  60. inter_channels = in_channels // 4
  61. self.conva = nn.Sequential(
  62. nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
  63. norm_layer(inter_channels),
  64. nn.ReLU(True))
  65. self.cca = CrissCrossAttention(inter_channels)
  66. self.convb = nn.Sequential(
  67. nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),
  68. norm_layer(inter_channels),
  69. nn.ReLU(True))
  70. self.bottleneck = nn.Sequential(
  71. nn.Conv2d(in_channels + inter_channels, out_channels, 3, padding=1, bias=False),
  72. norm_layer(out_channels),
  73. nn.Dropout2d(0.1))
  74. def forward(self, x, recurrence=1):
  75. out = self.conva(x)
  76. for i in range(recurrence):
  77. out = self.cca(out)
  78. out = self.convb(out)
  79. out = torch.cat([x, out], dim=1)
  80. out = self.bottleneck(out)
  81. return out
  82. def get_ccnet(dataset='pascal_voc', backbone='resnet50', pretrained=False, root='~/.torch/models',
  83. pretrained_base=True, **kwargs):
  84. acronyms = {
  85. 'pascal_voc': 'pascal_voc',
  86. 'pascal_aug': 'pascal_aug',
  87. 'ade20k': 'ade',
  88. 'coco': 'coco',
  89. 'citys': 'citys',
  90. }
  91. from ..data.dataloader import datasets
  92. model = CCNet(datasets[dataset].NUM_CLASS, backbone=backbone, pretrained_base=pretrained_base, **kwargs)
  93. if pretrained:
  94. from .model_store import get_model_file
  95. device = torch.device(kwargs['local_rank'])
  96. model.load_state_dict(torch.load(get_model_file('ccnet_%s_%s' % (backbone, acronyms[dataset]), root=root),
  97. map_location=device))
  98. return model
  99. def get_ccnet_resnet50_citys(**kwargs):
  100. return get_ccnet('citys', 'resnet50', **kwargs)
  101. def get_ccnet_resnet101_citys(**kwargs):
  102. return get_ccnet('citys', 'resnet101', **kwargs)
  103. def get_ccnet_resnet152_citys(**kwargs):
  104. return get_ccnet('citys', 'resnet152', **kwargs)
  105. def get_ccnet_resnet50_ade(**kwargs):
  106. return get_ccnet('ade20k', 'resnet50', **kwargs)
  107. def get_ccnet_resnet101_ade(**kwargs):
  108. return get_ccnet('ade20k', 'resnet101', **kwargs)
  109. def get_ccnet_resnet152_ade(**kwargs):
  110. return get_ccnet('ade20k', 'resnet152', **kwargs)
  111. if __name__ == '__main__':
  112. # model = get_ccnet_resnet50_citys()
  113. # img = torch.randn(1, 3, 480, 480)
  114. # outputs = model(img)
  115. input = torch.rand(2, 3, 224, 224)
  116. model = CCNet(4, pretrained_base=False)
  117. # target = torch.zeros(4, 512, 512).cuda()
  118. # model.eval()
  119. # print(model)
  120. loss = model(input)
  121. print(loss, loss.shape)
  122. # from torchsummary import summary
  123. #
  124. # summary(model, (3, 224, 224)) # 打印表格,按顺序输出每层的输出形状和参数
  125. import torch
  126. from thop import profile
  127. from torchsummary import summary
  128. flop, params = profile(model, input_size=(1, 3, 512, 512))
  129. print('flops:{:.3f}G\nparams:{:.3f}M'.format(flop / 1e9, params / 1e6))