Showing
2 changed files
with
389 additions
and
0 deletions
code/classifier/networks/grayResNet2.py
0 → 100644
| 1 | +import torch | ||
| 2 | +import torch.nn as nn | ||
| 3 | +#from .utils import load_state_dict_from_url | ||
| 4 | + | ||
| 5 | + | ||
| 6 | +__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', | ||
| 7 | + 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', | ||
| 8 | + 'wide_resnet50_2', 'wide_resnet101_2'] | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +model_urls = { | ||
| 12 | + 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', | ||
| 13 | + 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', | ||
| 14 | + 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', | ||
| 15 | + 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', | ||
| 16 | + 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', | ||
| 17 | + 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth', | ||
| 18 | + 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth', | ||
| 19 | + 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth', | ||
| 20 | + 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth', | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): | ||
| 25 | + """3x3 convolution with padding""" | ||
| 26 | + return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, | ||
| 27 | + padding=dilation, groups=groups, bias=False, dilation=dilation) | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def conv1x1(in_planes, out_planes, stride=1): | ||
| 31 | + """1x1 convolution""" | ||
| 32 | + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +class BasicBlock(nn.Module): | ||
| 36 | + expansion = 1 | ||
| 37 | + | ||
| 38 | + def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, | ||
| 39 | + base_width=64, dilation=1, norm_layer=None): | ||
| 40 | + super(BasicBlock, self).__init__() | ||
| 41 | + if norm_layer is None: | ||
| 42 | + norm_layer = nn.BatchNorm2d | ||
| 43 | + if groups != 1 or base_width != 64: | ||
| 44 | + raise ValueError('BasicBlock only supports groups=1 and base_width=64') | ||
| 45 | + if dilation > 1: | ||
| 46 | + raise NotImplementedError("Dilation > 1 not supported in BasicBlock") | ||
| 47 | + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 | ||
| 48 | + self.conv1 = conv3x3(inplanes, planes, stride) | ||
| 49 | + self.bn1 = norm_layer(planes) | ||
| 50 | + self.relu = nn.ReLU(inplace=True) | ||
| 51 | + self.conv2 = conv3x3(planes, planes) | ||
| 52 | + self.bn2 = norm_layer(planes) | ||
| 53 | + self.downsample = downsample | ||
| 54 | + self.stride = stride | ||
| 55 | + | ||
| 56 | + def forward(self, x): | ||
| 57 | + identity = x | ||
| 58 | + | ||
| 59 | + out = self.conv1(x) | ||
| 60 | + out = self.bn1(out) | ||
| 61 | + out = self.relu(out) | ||
| 62 | + | ||
| 63 | + out = self.conv2(out) | ||
| 64 | + out = self.bn2(out) | ||
| 65 | + | ||
| 66 | + if self.downsample is not None: | ||
| 67 | + identity = self.downsample(x) | ||
| 68 | + | ||
| 69 | + out += identity | ||
| 70 | + out = self.relu(out) | ||
| 71 | + | ||
| 72 | + return out | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +class Bottleneck(nn.Module): | ||
| 76 | + # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) | ||
| 77 | + # while original implementation places the stride at the first 1x1 convolution(self.conv1) | ||
| 78 | + # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. | ||
| 79 | + # This variant is also known as ResNet V1.5 and improves accuracy according to | ||
| 80 | + # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. | ||
| 81 | + | ||
| 82 | + expansion = 4 | ||
| 83 | + | ||
| 84 | + def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, | ||
| 85 | + base_width=64, dilation=1, norm_layer=None): | ||
| 86 | + super(Bottleneck, self).__init__() | ||
| 87 | + if norm_layer is None: | ||
| 88 | + norm_layer = nn.BatchNorm2d | ||
| 89 | + width = int(planes * (base_width / 64.)) * groups | ||
| 90 | + # Both self.conv2 and self.downsample layers downsample the input when stride != 1 | ||
| 91 | + self.conv1 = conv1x1(inplanes, width) | ||
| 92 | + self.bn1 = norm_layer(width) | ||
| 93 | + self.conv2 = conv3x3(width, width, stride, groups, dilation) | ||
| 94 | + self.bn2 = norm_layer(width) | ||
| 95 | + self.conv3 = conv1x1(width, planes * self.expansion) | ||
| 96 | + self.bn3 = norm_layer(planes * self.expansion) | ||
| 97 | + self.relu = nn.ReLU(inplace=True) | ||
| 98 | + self.downsample = downsample | ||
| 99 | + self.stride = stride | ||
| 100 | + | ||
| 101 | + def forward(self, x): | ||
| 102 | + identity = x | ||
| 103 | + | ||
| 104 | + out = self.conv1(x) | ||
| 105 | + out = self.bn1(out) | ||
| 106 | + out = self.relu(out) | ||
| 107 | + | ||
| 108 | + out = self.conv2(out) | ||
| 109 | + out = self.bn2(out) | ||
| 110 | + out = self.relu(out) | ||
| 111 | + | ||
| 112 | + out = self.conv3(out) | ||
| 113 | + out = self.bn3(out) | ||
| 114 | + | ||
| 115 | + if self.downsample is not None: | ||
| 116 | + identity = self.downsample(x) | ||
| 117 | + | ||
| 118 | + out += identity | ||
| 119 | + out = self.relu(out) | ||
| 120 | + | ||
| 121 | + return out | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +class ResNet(nn.Module): | ||
| 125 | + | ||
| 126 | + def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, | ||
| 127 | + groups=1, width_per_group=64, replace_stride_with_dilation=None, | ||
| 128 | + norm_layer=None): | ||
| 129 | + super(ResNet, self).__init__() | ||
| 130 | + if norm_layer is None: | ||
| 131 | + norm_layer = nn.BatchNorm2d | ||
| 132 | + self._norm_layer = norm_layer | ||
| 133 | + | ||
| 134 | + self.inplanes = 64 | ||
| 135 | + self.dilation = 1 | ||
| 136 | + if replace_stride_with_dilation is None: | ||
| 137 | + # each element in the tuple indicates if we should replace | ||
| 138 | + # the 2x2 stride with a dilated convolution instead | ||
| 139 | + replace_stride_with_dilation = [False, False, False] | ||
| 140 | + if len(replace_stride_with_dilation) != 3: | ||
| 141 | + raise ValueError("replace_stride_with_dilation should be None " | ||
| 142 | + "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) | ||
| 143 | + self.groups = groups | ||
| 144 | + self.base_width = width_per_group | ||
| 145 | + # change dimension 3->1 for grayscale input | ||
| 146 | + self.conv1 = nn.Conv2d(1, self.inplanes, kernel_size=7, stride=2, padding=3, | ||
| 147 | + bias=False) | ||
| 148 | + self.bn1 = norm_layer(self.inplanes) | ||
| 149 | + self.relu = nn.ReLU(inplace=True) | ||
| 150 | + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) | ||
| 151 | + self.layer1 = self._make_layer(block, 64, layers[0]) | ||
| 152 | + self.layer2 = self._make_layer(block, 128, layers[1], stride=2, | ||
| 153 | + dilate=replace_stride_with_dilation[0]) | ||
| 154 | + self.layer3 = self._make_layer(block, 256, layers[2], stride=2, | ||
| 155 | + dilate=replace_stride_with_dilation[1]) | ||
| 156 | + self.layer4 = self._make_layer(block, 512, layers[3], stride=2, | ||
| 157 | + dilate=replace_stride_with_dilation[2]) | ||
| 158 | + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) | ||
| 159 | + self.fc = nn.Linear(512 * block.expansion, num_classes) | ||
| 160 | + | ||
| 161 | + for m in self.modules(): | ||
| 162 | + if isinstance(m, nn.Conv2d): | ||
| 163 | + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') | ||
| 164 | + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): | ||
| 165 | + nn.init.constant_(m.weight, 1) | ||
| 166 | + nn.init.constant_(m.bias, 0) | ||
| 167 | + | ||
| 168 | + # Zero-initialize the last BN in each residual branch, | ||
| 169 | + # so that the residual branch starts with zeros, and each residual block behaves like an identity. | ||
| 170 | + # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 | ||
| 171 | + if zero_init_residual: | ||
| 172 | + for m in self.modules(): | ||
| 173 | + if isinstance(m, Bottleneck): | ||
| 174 | + nn.init.constant_(m.bn3.weight, 0) | ||
| 175 | + elif isinstance(m, BasicBlock): | ||
| 176 | + nn.init.constant_(m.bn2.weight, 0) | ||
| 177 | + | ||
| 178 | + def _make_layer(self, block, planes, blocks, stride=1, dilate=False): | ||
| 179 | + norm_layer = self._norm_layer | ||
| 180 | + downsample = None | ||
| 181 | + previous_dilation = self.dilation | ||
| 182 | + if dilate: | ||
| 183 | + self.dilation *= stride | ||
| 184 | + stride = 1 | ||
| 185 | + if stride != 1 or self.inplanes != planes * block.expansion: | ||
| 186 | + downsample = nn.Sequential( | ||
| 187 | + conv1x1(self.inplanes, planes * block.expansion, stride), | ||
| 188 | + norm_layer(planes * block.expansion), | ||
| 189 | + ) | ||
| 190 | + | ||
| 191 | + layers = [] | ||
| 192 | + layers.append(block(self.inplanes, planes, stride, downsample, self.groups, | ||
| 193 | + self.base_width, previous_dilation, norm_layer)) | ||
| 194 | + self.inplanes = planes * block.expansion | ||
| 195 | + for _ in range(1, blocks): | ||
| 196 | + layers.append(block(self.inplanes, planes, groups=self.groups, | ||
| 197 | + base_width=self.base_width, dilation=self.dilation, | ||
| 198 | + norm_layer=norm_layer)) | ||
| 199 | + | ||
| 200 | + return nn.Sequential(*layers) | ||
| 201 | + | ||
| 202 | + def _forward_impl(self, x): | ||
| 203 | + # See note [TorchScript super()] | ||
| 204 | + x = self.conv1(x) | ||
| 205 | + x = self.bn1(x) | ||
| 206 | + x = self.relu(x) | ||
| 207 | + x = self.maxpool(x) | ||
| 208 | + | ||
| 209 | + x = self.layer1(x) | ||
| 210 | + x = self.layer2(x) | ||
| 211 | + x = self.layer3(x) | ||
| 212 | + x = self.layer4(x) | ||
| 213 | + | ||
| 214 | + x = self.avgpool(x) | ||
| 215 | + x = torch.flatten(x, 1) | ||
| 216 | + x = self.fc(x) | ||
| 217 | + | ||
| 218 | + return x | ||
| 219 | + | ||
| 220 | + def forward(self, x): | ||
| 221 | + return self._forward_impl(x) | ||
| 222 | + | ||
| 223 | + | ||
| 224 | +def _resnet(arch, block, layers, pretrained, progress, **kwargs): | ||
| 225 | + model = ResNet(block, layers, **kwargs) | ||
| 226 | + # if pretrained: | ||
| 227 | + # state_dict = load_state_dict_from_url(model_urls[arch], | ||
| 228 | + # progress=progress) | ||
| 229 | + # model.load_state_dict(state_dict) | ||
| 230 | + return model | ||
| 231 | + | ||
| 232 | + | ||
| 233 | +def resnet18(pretrained=False, progress=True, **kwargs): | ||
| 234 | + r"""ResNet-18 model from | ||
| 235 | + `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ | ||
| 236 | + Args: | ||
| 237 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 238 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 239 | + """ | ||
| 240 | + return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, | ||
| 241 | + **kwargs) | ||
| 242 | + | ||
| 243 | + | ||
| 244 | +def resnet34(pretrained=False, progress=True, **kwargs): | ||
| 245 | + r"""ResNet-34 model from | ||
| 246 | + `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ | ||
| 247 | + Args: | ||
| 248 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 249 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 250 | + """ | ||
| 251 | + return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, | ||
| 252 | + **kwargs) | ||
| 253 | + | ||
| 254 | + | ||
| 255 | +def resnet50(pretrained=False, progress=True, **kwargs): | ||
| 256 | + r"""ResNet-50 model from | ||
| 257 | + `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ | ||
| 258 | + Args: | ||
| 259 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 260 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 261 | + """ | ||
| 262 | + return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, | ||
| 263 | + **kwargs) | ||
| 264 | + | ||
| 265 | + | ||
| 266 | +def resnet101(pretrained=False, progress=True, **kwargs): | ||
| 267 | + r"""ResNet-101 model from | ||
| 268 | + `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ | ||
| 269 | + Args: | ||
| 270 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 271 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 272 | + """ | ||
| 273 | + return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, | ||
| 274 | + **kwargs) | ||
| 275 | + | ||
| 276 | + | ||
| 277 | +def resnet152(pretrained=False, progress=True, **kwargs): | ||
| 278 | + r"""ResNet-152 model from | ||
| 279 | + `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ | ||
| 280 | + Args: | ||
| 281 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 282 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 283 | + """ | ||
| 284 | + return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, | ||
| 285 | + **kwargs) | ||
| 286 | + | ||
| 287 | + | ||
| 288 | +def resnext50_32x4d(pretrained=False, progress=True, **kwargs): | ||
| 289 | + r"""ResNeXt-50 32x4d model from | ||
| 290 | + `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_ | ||
| 291 | + Args: | ||
| 292 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 293 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 294 | + """ | ||
| 295 | + kwargs['groups'] = 32 | ||
| 296 | + kwargs['width_per_group'] = 4 | ||
| 297 | + return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], | ||
| 298 | + pretrained, progress, **kwargs) | ||
| 299 | + | ||
| 300 | + | ||
| 301 | +def resnext101_32x8d(pretrained=False, progress=True, **kwargs): | ||
| 302 | + r"""ResNeXt-101 32x8d model from | ||
| 303 | + `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_ | ||
| 304 | + Args: | ||
| 305 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 306 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 307 | + """ | ||
| 308 | + kwargs['groups'] = 32 | ||
| 309 | + kwargs['width_per_group'] = 8 | ||
| 310 | + return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], | ||
| 311 | + pretrained, progress, **kwargs) | ||
| 312 | + | ||
| 313 | + | ||
| 314 | +def wide_resnet50_2(pretrained=False, progress=True, **kwargs): | ||
| 315 | + r"""Wide ResNet-50-2 model from | ||
| 316 | + `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_ | ||
| 317 | + The model is the same as ResNet except for the bottleneck number of channels | ||
| 318 | + which is twice larger in every block. The number of channels in outer 1x1 | ||
| 319 | + convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 | ||
| 320 | + channels, and in Wide ResNet-50-2 has 2048-1024-2048. | ||
| 321 | + Args: | ||
| 322 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 323 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 324 | + """ | ||
| 325 | + kwargs['width_per_group'] = 64 * 2 | ||
| 326 | + return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], | ||
| 327 | + pretrained, progress, **kwargs) | ||
| 328 | + | ||
| 329 | + | ||
| 330 | +def wide_resnet101_2(pretrained=False, progress=True, **kwargs): | ||
| 331 | + r"""Wide ResNet-101-2 model from | ||
| 332 | + `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_ | ||
| 333 | + The model is the same as ResNet except for the bottleneck number of channels | ||
| 334 | + which is twice larger in every block. The number of channels in outer 1x1 | ||
| 335 | + convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 | ||
| 336 | + channels, and in Wide ResNet-50-2 has 2048-1024-2048. | ||
| 337 | + Args: | ||
| 338 | + pretrained (bool): If True, returns a model pre-trained on ImageNet | ||
| 339 | + progress (bool): If True, displays a progress bar of the download to stderr | ||
| 340 | + """ | ||
| 341 | + kwargs['width_per_group'] = 64 * 2 | ||
| 342 | + return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3], | ||
| 343 | + pretrained, progress, **kwargs) |
code/getNormalFrames.m
0 → 100644
| 1 | +inputheader = '..\data\Normal_all\'; | ||
| 2 | +outfolder = '..\data\Normal_frames\'; | ||
| 3 | + | ||
| 4 | +files = dir(inputheader); | ||
| 5 | +id = {files.name}; | ||
| 6 | +% files + dir file | ||
| 7 | +flag = ~strcmp(id, '.') & ~strcmp(id, '..'); | ||
| 8 | +files = files(flag); | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +for i = 1 : length(files) | ||
| 12 | + | ||
| 13 | + id = split(files(i).name, '.nii'); | ||
| 14 | + id = char(id(1)); | ||
| 15 | + fprintf('ID #%d = %s\n', i, id); | ||
| 16 | + filename = id; % BraTS19_2013_2_1_seg_flair.nii | ||
| 17 | + data_path = strcat(inputheader,'\', filename); | ||
| 18 | + data = niftiread(data_path); %size 240x240x155 | ||
| 19 | + | ||
| 20 | + [x,y,z] = size(data); | ||
| 21 | + | ||
| 22 | + c = 0; | ||
| 23 | + | ||
| 24 | + for k = 18:24 | ||
| 25 | + type = '.png'; | ||
| 26 | + filename = strcat(id, '_', int2str(c), type); % BraTS19_2013_2_1_seg_flair_c.png | ||
| 27 | + outpath = strcat(outfolder, filename); | ||
| 28 | + % typecase int16 to double, range[0, 1], rotate 90 and filp updown | ||
| 29 | + % range [0, 1] | ||
| 30 | + %cp_data = flipud(rot90(mat2gray(double(data(:,:,k))))); | ||
| 31 | + cp_data = flipud(rot90(mat2gray(double(data(:,:,k))))); | ||
| 32 | +% M = max(cp_data(:)); | ||
| 33 | +% disp(M); | ||
| 34 | + imwrite(cp_data, outpath); | ||
| 35 | + | ||
| 36 | + c = c+ 1; | ||
| 37 | + end | ||
| 38 | + | ||
| 39 | +end | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +% p = 'st: %d\n'; | ||
| 43 | +% fprintf(p, st); | ||
| 44 | +% p = 'en: %d\n'; | ||
| 45 | +% fprintf(p, en); | ||
| 46 | + |
-
Please register or login to post a comment