“41e6a032c97ad23245aad1ebc28b573e91ab48c0”上不存在“doc/fluid/install/install_Ubuntu.md”
densenet.py 9.6 KB
Newer Older
littletomatodonkey's avatar
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

littletomatodonkey's avatar
littletomatodonkey 已提交
19
import numpy as np
W
WuHaobo 已提交
20 21 22
import paddle
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
littletomatodonkey's avatar
littletomatodonkey 已提交
23 24 25 26
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, BatchNorm, Linear, Dropout

import math
W
WuHaobo 已提交
27 28

__all__ = [
littletomatodonkey's avatar
littletomatodonkey 已提交
29
    "DenseNet121", "DenseNet161", "DenseNet169", "DenseNet201", "DenseNet264"
W
WuHaobo 已提交
30 31 32
]


littletomatodonkey's avatar
littletomatodonkey 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
class BNACConvLayer(fluid.dygraph.Layer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 pad=0,
                 groups=1,
                 act="relu",
                 name=None):
        super(BNACConvLayer, self).__init__()

        self._batch_norm = BatchNorm(
            num_channels,
            act=act,
            param_attr=ParamAttr(name=name + '_bn_scale'),
            bias_attr=ParamAttr(name + '_bn_offset'),
            moving_mean_name=name + '_bn_mean',
            moving_variance_name=name + '_bn_variance')

        self._conv = Conv2D(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=filter_size,
            stride=stride,
            padding=pad,
            groups=groups,
            act=None,
            param_attr=ParamAttr(name=name + "_weights"),
            bias_attr=False)

    def forward(self, input):
        y = self._batch_norm(input)
        y = self._conv(y)
        return y


class DenseLayer(fluid.dygraph.Layer):
    def __init__(self, num_channels, growth_rate, bn_size, dropout, name=None):
        super(DenseLayer, self).__init__()
        self.dropout = dropout

        self.bn_ac_func1 = BNACConvLayer(
            num_channels=num_channels,
            num_filters=bn_size * growth_rate,
            filter_size=1,
            pad=0,
            stride=1,
            name=name + "_x1")

        self.bn_ac_func2 = BNACConvLayer(
            num_channels=bn_size * growth_rate,
            num_filters=growth_rate,
            filter_size=3,
            pad=1,
            stride=1,
            name=name + "_x2")

        if dropout:
            self.dropout_func = Dropout(p=dropout)

    def forward(self, input):
        conv = self.bn_ac_func1(input)
        conv = self.bn_ac_func2(conv)
        if self.dropout:
            conv = self.dropout_func(conv)
        conv = fluid.layers.concat([input, conv], axis=1)
        return conv


class DenseBlock(fluid.dygraph.Layer):
    def __init__(self,
                 num_channels,
                 num_layers,
                 bn_size,
                 growth_rate,
                 dropout,
                 name=None):
        super(DenseBlock, self).__init__()
        self.dropout = dropout

        self.dense_layer_func = []

        pre_channel = num_channels
        for layer in range(num_layers):
            self.dense_layer_func.append(
                self.add_sublayer(
                    "{}_{}".format(name, layer + 1),
                    DenseLayer(
                        num_channels=pre_channel,
                        growth_rate=growth_rate,
                        bn_size=bn_size,
                        dropout=dropout,
                        name=name + '_' + str(layer + 1))))
            pre_channel = pre_channel + growth_rate

    def forward(self, input):
        conv = input
        for func in self.dense_layer_func:
            conv = func(conv)
        return conv


class TransitionLayer(fluid.dygraph.Layer):
    def __init__(self, num_channels, num_output_features, name=None):
        super(TransitionLayer, self).__init__()

        self.conv_ac_func = BNACConvLayer(
            num_channels=num_channels,
            num_filters=num_output_features,
            filter_size=1,
            pad=0,
            stride=1,
            name=name)

        self.pool2d_avg = Pool2D(pool_size=2, pool_stride=2, pool_type='avg')

    def forward(self, input):
        y = self.conv_ac_func(input)
        y = self.pool2d_avg(y)
        return y


class ConvBNLayer(fluid.dygraph.Layer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 pad=0,
                 groups=1,
                 act="relu",
                 name=None):
        super(ConvBNLayer, self).__init__()

        self._conv = Conv2D(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=filter_size,
            stride=stride,
            padding=pad,
            groups=groups,
            act=None,
            param_attr=ParamAttr(name=name + "_weights"),
            bias_attr=False)
        self._batch_norm = BatchNorm(
            num_filters,
            act=act,
            param_attr=ParamAttr(name=name + '_bn_scale'),
            bias_attr=ParamAttr(name + '_bn_offset'),
            moving_mean_name=name + '_bn_mean',
            moving_variance_name=name + '_bn_variance')

    def forward(self, input):
        y = self._conv(input)
        y = self._batch_norm(y)
        return y


class DenseNet(fluid.dygraph.Layer):
    def __init__(self, layers=60, bn_size=4, dropout=0, class_dim=1000):
        super(DenseNet, self).__init__()
W
WuHaobo 已提交
195 196 197

        supported_layers = [121, 161, 169, 201, 264]
        assert layers in supported_layers, \
littletomatodonkey's avatar
littletomatodonkey 已提交
198 199
            "supported layers are {} but input layer is {}".format(
                supported_layers, layers)
W
WuHaobo 已提交
200 201 202 203 204 205 206 207
        densenet_spec = {
            121: (64, 32, [6, 12, 24, 16]),
            161: (96, 48, [6, 12, 36, 24]),
            169: (64, 32, [6, 12, 32, 32]),
            201: (64, 32, [6, 12, 48, 32]),
            264: (64, 32, [6, 12, 64, 48])
        }
        num_init_features, growth_rate, block_config = densenet_spec[layers]
littletomatodonkey's avatar
littletomatodonkey 已提交
208 209 210

        self.conv1_func = ConvBNLayer(
            num_channels=3,
W
WuHaobo 已提交
211 212 213
            num_filters=num_init_features,
            filter_size=7,
            stride=2,
littletomatodonkey's avatar
littletomatodonkey 已提交
214
            pad=3,
W
WuHaobo 已提交
215
            act='relu',
littletomatodonkey's avatar
littletomatodonkey 已提交
216 217 218 219 220 221 222 223 224 225
            name="conv1")

        self.pool2d_max = Pool2D(
            pool_size=3, pool_stride=2, pool_padding=1, pool_type='max')

        self.block_config = block_config

        self.dense_block_func_list = []
        self.transition_func_list = []
        pre_num_channels = num_init_features
W
WuHaobo 已提交
226 227
        num_features = num_init_features
        for i, num_layers in enumerate(block_config):
littletomatodonkey's avatar
littletomatodonkey 已提交
228 229 230 231 232 233 234 235 236 237 238
            self.dense_block_func_list.append(
                self.add_sublayer(
                    "db_conv_{}".format(i + 2),
                    DenseBlock(
                        num_channels=pre_num_channels,
                        num_layers=num_layers,
                        bn_size=bn_size,
                        growth_rate=growth_rate,
                        dropout=dropout,
                        name='conv' + str(i + 2))))

W
WuHaobo 已提交
239
            num_features = num_features + num_layers * growth_rate
littletomatodonkey's avatar
littletomatodonkey 已提交
240 241
            pre_num_channels = num_features

W
WuHaobo 已提交
242
            if i != len(block_config) - 1:
littletomatodonkey's avatar
littletomatodonkey 已提交
243 244 245 246 247 248 249 250
                self.transition_func_list.append(
                    self.add_sublayer(
                        "tr_conv{}_blk".format(i + 2),
                        TransitionLayer(
                            num_channels=pre_num_channels,
                            num_output_features=num_features // 2,
                            name='conv' + str(i + 2) + "_blk")))
                pre_num_channels = num_features // 2
W
WuHaobo 已提交
251
                num_features = num_features // 2
littletomatodonkey's avatar
littletomatodonkey 已提交
252 253 254 255

        self.batch_norm = BatchNorm(
            num_features,
            act="relu",
W
WuHaobo 已提交
256 257 258 259
            param_attr=ParamAttr(name='conv5_blk_bn_scale'),
            bias_attr=ParamAttr(name='conv5_blk_bn_offset'),
            moving_mean_name='conv5_blk_bn_mean',
            moving_variance_name='conv5_blk_bn_variance')
littletomatodonkey's avatar
littletomatodonkey 已提交
260 261 262 263 264 265 266 267 268

        self.pool2d_avg = Pool2D(pool_type='avg', global_pooling=True)

        stdv = 1.0 / math.sqrt(num_features * 1.0)

        self.out = Linear(
            num_features,
            class_dim,
            param_attr=ParamAttr(
W
WuHaobo 已提交
269 270
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name="fc_weights"),
littletomatodonkey's avatar
littletomatodonkey 已提交
271
            bias_attr=ParamAttr(name="fc_offset"))
W
WuHaobo 已提交
272

littletomatodonkey's avatar
littletomatodonkey 已提交
273 274 275
    def forward(self, input):
        conv = self.conv1_func(input)
        conv = self.pool2d_max(conv)
W
WuHaobo 已提交
276

littletomatodonkey's avatar
littletomatodonkey 已提交
277 278 279 280
        for i, num_layers in enumerate(self.block_config):
            conv = self.dense_block_func_list[i](conv)
            if i != len(self.block_config) - 1:
                conv = self.transition_func_list[i](conv)
W
WuHaobo 已提交
281

littletomatodonkey's avatar
littletomatodonkey 已提交
282 283 284 285 286
        conv = self.batch_norm(conv)
        y = self.pool2d_avg(conv)
        y = fluid.layers.reshape(y, shape=[0, -1])
        y = self.out(y)
        return y
W
WuHaobo 已提交
287 288


littletomatodonkey's avatar
littletomatodonkey 已提交
289 290
def DenseNet121(**args):
    model = DenseNet(layers=121, **args)
W
WuHaobo 已提交
291 292 293
    return model


littletomatodonkey's avatar
littletomatodonkey 已提交
294 295
def DenseNet161(**args):
    model = DenseNet(layers=161, **args)
W
WuHaobo 已提交
296 297 298
    return model


littletomatodonkey's avatar
littletomatodonkey 已提交
299 300
def DenseNet169(**args):
    model = DenseNet(layers=169, **args)
W
WuHaobo 已提交
301 302 303
    return model


littletomatodonkey's avatar
littletomatodonkey 已提交
304 305
def DenseNet201(**args):
    model = DenseNet(layers=201, **args)
W
WuHaobo 已提交
306 307 308
    return model


littletomatodonkey's avatar
littletomatodonkey 已提交
309 310
def DenseNet264(**args):
    model = DenseNet(layers=264, **args)
W
WuHaobo 已提交
311
    return model