| 
 | 1 | +"""  | 
 | 2 | +DenseNet, original: https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py  | 
 | 3 | +"""  | 
 | 4 | +import re  | 
 | 5 | +from collections import OrderedDict  | 
 | 6 | + | 
 | 7 | +import torch  | 
 | 8 | +import torch.nn as nn  | 
 | 9 | +import torch.nn.functional as F  | 
 | 10 | +import torch.utils.model_zoo as model_zoo  | 
 | 11 | +import torchvision.transforms as transforms  | 
 | 12 | + | 
 | 13 | +from PIL import Image  | 
 | 14 | +import numpy as np  | 
 | 15 | + | 
 | 16 | +model_urls = {  | 
 | 17 | +    'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',  | 
 | 18 | +    'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth',  | 
 | 19 | +    'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',  | 
 | 20 | +    'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth',  | 
 | 21 | +}  | 
 | 22 | + | 
 | 23 | + | 
 | 24 | +class _DenseLayer(nn.Sequential):  | 
 | 25 | +    """Basic unit of DenseBlock (using bottleneck layer) """  | 
 | 26 | +    def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):  | 
 | 27 | +        super(_DenseLayer, self).__init__()  | 
 | 28 | +        self.add_module("norm1", nn.BatchNorm2d(num_input_features))  | 
 | 29 | +        self.add_module("relu1", nn.ReLU(inplace=True))  | 
 | 30 | +        self.add_module("conv1", nn.Conv2d(num_input_features, bn_size*growth_rate,  | 
 | 31 | +                                           kernel_size=1, stride=1, bias=False))  | 
 | 32 | +        self.add_module("norm2", nn.BatchNorm2d(bn_size*growth_rate))  | 
 | 33 | +        self.add_module("relu2", nn.ReLU(inplace=True))  | 
 | 34 | +        self.add_module("conv2", nn.Conv2d(bn_size*growth_rate, growth_rate,  | 
 | 35 | +                                           kernel_size=3, stride=1, padding=1, bias=False))  | 
 | 36 | +        self.drop_rate = drop_rate  | 
 | 37 | + | 
 | 38 | +    def forward(self, x):  | 
 | 39 | +        new_features = super(_DenseLayer, self).forward(x)  | 
 | 40 | +        if self.drop_rate > 0:  | 
 | 41 | +            new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)  | 
 | 42 | +        return torch.cat([x, new_features], 1)  | 
 | 43 | + | 
 | 44 | +class _DenseBlock(nn.Sequential):  | 
 | 45 | +    """DenseBlock"""  | 
 | 46 | +    def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):  | 
 | 47 | +        super(_DenseBlock, self).__init__()  | 
 | 48 | +        for i in range(num_layers):  | 
 | 49 | +            layer = _DenseLayer(num_input_features+i*growth_rate, growth_rate, bn_size,  | 
 | 50 | +                                drop_rate)  | 
 | 51 | +            self.add_module("denselayer%d" % (i+1,), layer)  | 
 | 52 | + | 
 | 53 | + | 
 | 54 | +class _Transition(nn.Sequential):  | 
 | 55 | +    """Transition layer between two adjacent DenseBlock"""  | 
 | 56 | +    def __init__(self, num_input_feature, num_output_features):  | 
 | 57 | +        super(_Transition, self).__init__()  | 
 | 58 | +        self.add_module("norm", nn.BatchNorm2d(num_input_feature))  | 
 | 59 | +        self.add_module("relu", nn.ReLU(inplace=True))  | 
 | 60 | +        self.add_module("conv", nn.Conv2d(num_input_feature, num_output_features,  | 
 | 61 | +                                          kernel_size=1, stride=1, bias=False))  | 
 | 62 | +        self.add_module("pool", nn.AvgPool2d(2, stride=2))  | 
 | 63 | + | 
 | 64 | + | 
 | 65 | +class DenseNet(nn.Module):  | 
 | 66 | +    "DenseNet-BC model"  | 
 | 67 | +    def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64,  | 
 | 68 | +                 bn_size=4, compression_rate=0.5, drop_rate=0, num_classes=1000):  | 
 | 69 | +        """  | 
 | 70 | +        :param growth_rate: (int) number of filters used in DenseLayer, `k` in the paper  | 
 | 71 | +        :param block_config: (list of 4 ints) number of layers in each DenseBlock  | 
 | 72 | +        :param num_init_features: (int) number of filters in the first Conv2d  | 
 | 73 | +        :param bn_size: (int) the factor using in the bottleneck layer  | 
 | 74 | +        :param compression_rate: (float) the compression rate used in Transition Layer  | 
 | 75 | +        :param drop_rate: (float) the drop rate after each DenseLayer  | 
 | 76 | +        :param num_classes: (int) number of classes for classification  | 
 | 77 | +        """  | 
 | 78 | +        super(DenseNet, self).__init__()  | 
 | 79 | +        # first Conv2d  | 
 | 80 | +        self.features = nn.Sequential(OrderedDict([  | 
 | 81 | +            ("conv0", nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),  | 
 | 82 | +            ("norm0", nn.BatchNorm2d(num_init_features)),  | 
 | 83 | +            ("relu0", nn.ReLU(inplace=True)),  | 
 | 84 | +            ("pool0", nn.MaxPool2d(3, stride=2, padding=1))  | 
 | 85 | +        ]))  | 
 | 86 | + | 
 | 87 | +        # DenseBlock  | 
 | 88 | +        num_features = num_init_features  | 
 | 89 | +        for i, num_layers in enumerate(block_config):  | 
 | 90 | +            block = _DenseBlock(num_layers, num_features, bn_size, growth_rate, drop_rate)  | 
 | 91 | +            self.features.add_module("denseblock%d" % (i + 1), block)  | 
 | 92 | +            num_features += num_layers*growth_rate  | 
 | 93 | +            if i != len(block_config) - 1:  | 
 | 94 | +                transition = _Transition(num_features, int(num_features*compression_rate))  | 
 | 95 | +                self.features.add_module("transition%d" % (i + 1), transition)  | 
 | 96 | +                num_features = int(num_features * compression_rate)  | 
 | 97 | + | 
 | 98 | +        # final bn+ReLU  | 
 | 99 | +        self.features.add_module("norm5", nn.BatchNorm2d(num_features))  | 
 | 100 | +        self.features.add_module("relu5", nn.ReLU(inplace=True))  | 
 | 101 | + | 
 | 102 | +        # classification layer  | 
 | 103 | +        self.classifier = nn.Linear(num_features, num_classes)  | 
 | 104 | + | 
 | 105 | +        # params initialization  | 
 | 106 | +        for m in self.modules():  | 
 | 107 | +            if isinstance(m, nn.Conv2d):  | 
 | 108 | +                nn.init.kaiming_normal_(m.weight)  | 
 | 109 | +            elif isinstance(m, nn.BatchNorm2d):  | 
 | 110 | +                nn.init.constant_(m.bias, 0)  | 
 | 111 | +                nn.init.constant_(m.weight, 1)  | 
 | 112 | +            elif isinstance(m, nn.Linear):  | 
 | 113 | +                nn.init.constant_(m.bias, 0)  | 
 | 114 | + | 
 | 115 | +    def forward(self, x):  | 
 | 116 | +        features = self.features(x)  | 
 | 117 | +        out = F.avg_pool2d(features, 7, stride=1).view(features.size(0), -1)  | 
 | 118 | +        out = self.classifier(out)  | 
 | 119 | +        return out  | 
 | 120 | + | 
 | 121 | +class DenseNet_MNIST(nn.Module):  | 
 | 122 | +    """DenseNet for MNIST dataset"""  | 
 | 123 | +    def __init__(self, growth_rate=12, block_config=(6, 6, 6), num_init_features=16,  | 
 | 124 | +                 bn_size=4, compression_rate=0.5, drop_rate=0, num_classes=10):  | 
 | 125 | +        """  | 
 | 126 | +        :param growth_rate: (int) number of filters used in DenseLayer, `k` in the paper  | 
 | 127 | +        :param block_config: (list of 2 ints) number of layers in each DenseBlock  | 
 | 128 | +        :param num_init_features: (int) number of filters in the first Conv2d  | 
 | 129 | +        :param bn_size: (int) the factor using in the bottleneck layer  | 
 | 130 | +        :param compression_rate: (float) the compression rate used in Transition Layer  | 
 | 131 | +        :param drop_rate: (float) the drop rate after each DenseLayer  | 
 | 132 | +        :param num_classes: (int) number of classes for classification  | 
 | 133 | +        """  | 
 | 134 | +        super(DenseNet_MNIST, self).__init__()  | 
 | 135 | +        # first Conv2d  | 
 | 136 | +        self.features = nn.Sequential(OrderedDict([  | 
 | 137 | +            ("conv0", nn.Conv2d(1, num_init_features, kernel_size=3, stride=1, padding=1, bias=False)),  | 
 | 138 | +            ("norm0", nn.BatchNorm2d(num_init_features)),  | 
 | 139 | +            ("relu0", nn.ReLU(inplace=True)),  | 
 | 140 | +        ]))  | 
 | 141 | + | 
 | 142 | +        # DenseBlock  | 
 | 143 | +        num_features = num_init_features  | 
 | 144 | +        for i, num_layers in enumerate(block_config):  | 
 | 145 | +            block = _DenseBlock(num_layers, num_features, bn_size, growth_rate, drop_rate)  | 
 | 146 | +            self.features.add_module("denseblock%d" % (i + 1), block)  | 
 | 147 | +            num_features += num_layers * growth_rate  | 
 | 148 | +            if i != len(block_config) - 1:  | 
 | 149 | +                transition = _Transition(num_features, int(num_features * compression_rate))  | 
 | 150 | +                self.features.add_module("transition%d" % (i + 1), transition)  | 
 | 151 | +                num_features = int(num_features * compression_rate)  | 
 | 152 | + | 
 | 153 | +        # final bn+ReLU  | 
 | 154 | +        self.features.add_module("norm5", nn.BatchNorm2d(num_features))  | 
 | 155 | +        self.features.add_module("relu5", nn.ReLU(inplace=True))  | 
 | 156 | + | 
 | 157 | +        # classification layer  | 
 | 158 | +        self.classifier = nn.Linear(num_features, num_classes)  | 
 | 159 | + | 
 | 160 | +        # params initialization  | 
 | 161 | +        for m in self.modules():  | 
 | 162 | +            if isinstance(m, nn.Conv2d):  | 
 | 163 | +                nn.init.kaiming_normal_(m.weight)  | 
 | 164 | +            elif isinstance(m, nn.BatchNorm2d):  | 
 | 165 | +                nn.init.constant_(m.bias, 0)  | 
 | 166 | +                nn.init.constant_(m.weight, 1)  | 
 | 167 | +            elif isinstance(m, nn.Linear):  | 
 | 168 | +                nn.init.constant_(m.bias, 0)  | 
 | 169 | + | 
 | 170 | +    def forward(self, x):  | 
 | 171 | +        features = self.features(x)  | 
 | 172 | +        out = F.avg_pool2d(features, 7, stride=1).view(features.size(0), -1)  | 
 | 173 | +        out = self.classifier(out)  | 
 | 174 | +        return out  | 
 | 175 | + | 
 | 176 | + | 
 | 177 | +def densenet121(pretrained=False, **kwargs):  | 
 | 178 | +    """DenseNet121"""  | 
 | 179 | +    model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16),  | 
 | 180 | +                     **kwargs)  | 
 | 181 | + | 
 | 182 | +    if pretrained:  | 
 | 183 | +        # '.'s are no longer allowed in module names, but pervious _DenseLayer  | 
 | 184 | +        # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.  | 
 | 185 | +        # They are also in the checkpoints in model_urls. This pattern is used  | 
 | 186 | +        # to find such keys.  | 
 | 187 | +        pattern = re.compile(  | 
 | 188 | +            r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')  | 
 | 189 | +        state_dict = model_zoo.load_url(model_urls['densenet121'])  | 
 | 190 | +        for key in list(state_dict.keys()):  | 
 | 191 | +            res = pattern.match(key)  | 
 | 192 | +            if res:  | 
 | 193 | +                new_key = res.group(1) + res.group(2)  | 
 | 194 | +                state_dict[new_key] = state_dict[key]  | 
 | 195 | +                del state_dict[key]  | 
 | 196 | +        model.load_state_dict(state_dict)  | 
 | 197 | +    return model  | 
 | 198 | + | 
 | 199 | +if __name__ == "__main__":  | 
 | 200 | +    densenet = densenet121(pretrained=True)  | 
 | 201 | +    densenet.eval()  | 
 | 202 | + | 
 | 203 | +    img = Image.open("./images/cat.jpg")  | 
 | 204 | + | 
 | 205 | +    trans_ops = transforms.Compose([  | 
 | 206 | +        transforms.Resize(256),  | 
 | 207 | +        transforms.CenterCrop(224),  | 
 | 208 | +        transforms.ToTensor(),  | 
 | 209 | +        transforms.Normalize(mean=[0.485, 0.456, 0.406],  | 
 | 210 | +                             std=[0.229, 0.224, 0.225])  | 
 | 211 | +    ])  | 
 | 212 | + | 
 | 213 | +    images = trans_ops(img).view(-1, 3, 224, 224)  | 
 | 214 | +    print(images)  | 
 | 215 | +    outputs = densenet(images)  | 
 | 216 | + | 
 | 217 | +    _, predictions = outputs.topk(5, dim=1)  | 
 | 218 | + | 
 | 219 | +    labels = list(map(lambda s: s.strip(), open("./data/imagenet/synset_words.txt").readlines()))  | 
 | 220 | +    for idx in predictions.numpy()[0]:  | 
 | 221 | +        print("Predicted labels:", labels[idx])  | 
 | 222 | + | 
 | 223 | + | 
 | 224 | + | 
 | 225 | + | 
 | 226 | + | 
 | 227 | + | 
 | 228 | + | 
0 commit comments