|
| 1 | +# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import paddle.v2 as paddle |
| 16 | + |
| 17 | +__all__ = ['resnet_cifar10'] |
| 18 | + |
| 19 | + |
| 20 | +def conv_bn_layer(input, |
| 21 | + ch_out, |
| 22 | + filter_size, |
| 23 | + stride, |
| 24 | + padding, |
| 25 | + active_type=paddle.activation.Relu(), |
| 26 | + ch_in=None): |
| 27 | + tmp = paddle.layer.img_conv( |
| 28 | + input=input, |
| 29 | + filter_size=filter_size, |
| 30 | + num_channels=ch_in, |
| 31 | + num_filters=ch_out, |
| 32 | + stride=stride, |
| 33 | + padding=padding, |
| 34 | + act=paddle.activation.Linear(), |
| 35 | + bias_attr=False) |
| 36 | + return paddle.layer.batch_norm(input=tmp, act=active_type) |
| 37 | + |
| 38 | + |
| 39 | +def shortcut(ipt, n_in, n_out, stride): |
| 40 | + if n_in != n_out: |
| 41 | + return conv_bn_layer(ipt, n_out, 1, stride, 0, |
| 42 | + paddle.activation.Linear()) |
| 43 | + else: |
| 44 | + return ipt |
| 45 | + |
| 46 | + |
| 47 | +def basicblock(ipt, ch_out, stride): |
| 48 | + ch_in = ch_out * 2 |
| 49 | + tmp = conv_bn_layer(ipt, ch_out, 3, stride, 1) |
| 50 | + tmp = conv_bn_layer(tmp, ch_out, 3, 1, 1, paddle.activation.Linear()) |
| 51 | + short = shortcut(ipt, ch_in, ch_out, stride) |
| 52 | + return paddle.layer.addto(input=[tmp, short], act=paddle.activation.Relu()) |
| 53 | + |
| 54 | + |
| 55 | +def layer_warp(block_func, ipt, features, count, stride): |
| 56 | + tmp = block_func(ipt, features, stride) |
| 57 | + for i in range(1, count): |
| 58 | + tmp = block_func(tmp, features, 1) |
| 59 | + return tmp |
| 60 | + |
| 61 | + |
| 62 | +def resnet_cifar10(ipt, depth=32): |
| 63 | + # depth should be one of 20, 32, 44, 56, 110, 1202 |
| 64 | + assert (depth - 2) % 6 == 0 |
| 65 | + n = (depth - 2) / 6 |
| 66 | + nStages = {16, 64, 128} |
| 67 | + conv1 = conv_bn_layer( |
| 68 | + ipt, ch_in=3, ch_out=16, filter_size=3, stride=1, padding=1) |
| 69 | + res1 = layer_warp(basicblock, conv1, 16, n, 1) |
| 70 | + res2 = layer_warp(basicblock, res1, 32, n, 2) |
| 71 | + res3 = layer_warp(basicblock, res2, 64, n, 2) |
| 72 | + pool = paddle.layer.img_pool( |
| 73 | + input=res3, pool_size=8, stride=1, pool_type=paddle.pooling.Avg()) |
| 74 | + return pool |
0 commit comments