gan_conf_image.py 8.0 KB
Newer Older
1
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
W
wangyang59 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# 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 paddle.trainer_config_helpers import *

mode = get_config_arg("mode", str, "generator")
W
wangyang59 已提交
17
dataSource = get_config_arg("data", str, "mnist")
Y
Yu Yang 已提交
18 19 20
assert mode in set([
    "generator", "discriminator", "generator_training", "discriminator_training"
])
W
wangyang59 已提交
21 22 23 24 25 26

is_generator_training = mode == "generator_training"
is_discriminator_training = mode == "discriminator_training"
is_generator = mode == "generator"
is_discriminator = mode == "discriminator"

W
wangyang59 已提交
27 28 29
# The network structure below follows the dcgan paper 
# (https://arxiv.org/abs/1511.06434)

W
wangyang59 已提交
30
print('mode=%s' % mode)
W
wangyang59 已提交
31
# the dim of the noise (z) as the input of the generator network
W
wangyang59 已提交
32
noise_dim = 100
W
wangyang59 已提交
33 34
# the number of filters in the layer in generator/discriminator that is 
# closet to the image
W
wangyang59 已提交
35 36
gf_dim = 64
df_dim = 64
W
wangyang59 已提交
37
if dataSource == "mnist":
Y
Yu Yang 已提交
38 39
    sample_dim = 28  # image dim
    c_dim = 1  # image color
W
wangyang59 已提交
40 41 42
else:
    sample_dim = 32
    c_dim = 3
Y
Yu Yang 已提交
43 44
s2, s4 = int(sample_dim / 2), int(sample_dim / 4),
s8, s16 = int(sample_dim / 8), int(sample_dim / 16)
W
wangyang59 已提交
45 46

settings(
W
wangyang59 已提交
47 48
    batch_size=128,
    learning_rate=2e-4,
Y
Yu Yang 已提交
49
    learning_method=AdamOptimizer(beta1=0.5))
W
wangyang59 已提交
50

Y
Yu Yang 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64

def conv_bn(input,
            channels,
            imgSize,
            num_filters,
            output_x,
            stride,
            name,
            param_attr,
            bias_attr,
            param_attr_bn,
            bn,
            trans=False,
            act=ReluActivation()):
W
wangyang59 已提交
65 66 67 68 69 70 71 72 73
    """
    conv_bn is a utility function that constructs a convolution/deconv layer 
    with an optional batch_norm layer

    :param bn: whether to use batch_norm_layer
    :type bn: bool
    :param trans: whether to use conv (False) or deconv (True)
    :type trans: bool
    """
Y
Yu Yang 已提交
74

W
wangyang59 已提交
75 76
    # calculate the filter_size and padding size based on the given
    # imgSize and ouput size
Y
Yu Yang 已提交
77
    tmp = imgSize - (output_x - 1) * stride
W
wangyang59 已提交
78 79 80 81 82 83 84 85 86
    if tmp <= 1 or tmp > 5:
        raise ValueError("conv input-output dimension does not fit")
    elif tmp <= 3:
        filter_size = tmp + 2
        padding = 1
    else:
        filter_size = tmp
        padding = 0

Y
Yu Yang 已提交
87 88
    print(imgSize, output_x, stride, filter_size, padding)

89 90
    if trans:
        nameApx = "_convt"
91 92
    else:
        nameApx = "_conv"
Y
Yu Yang 已提交
93

W
wangyang59 已提交
94
    if bn:
Y
Yu Yang 已提交
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
        conv = img_conv_layer(
            input,
            filter_size=filter_size,
            num_filters=num_filters,
            name=name + nameApx,
            num_channels=channels,
            act=LinearActivation(),
            groups=1,
            stride=stride,
            padding=padding,
            bias_attr=bias_attr,
            param_attr=param_attr,
            shared_biases=True,
            layer_attr=None,
            filter_size_y=None,
            stride_y=None,
            padding_y=None,
            trans=trans)

        conv_bn = batch_norm_layer(
            conv,
            act=act,
            name=name + nameApx + "_bn",
            bias_attr=bias_attr,
            param_attr=param_attr_bn,
            use_global_stats=False)

W
wangyang59 已提交
122 123
        return conv_bn
    else:
Y
Yu Yang 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        conv = img_conv_layer(
            input,
            filter_size=filter_size,
            num_filters=num_filters,
            name=name + nameApx,
            num_channels=channels,
            act=act,
            groups=1,
            stride=stride,
            padding=padding,
            bias_attr=bias_attr,
            param_attr=param_attr,
            shared_biases=True,
            layer_attr=None,
            filter_size_y=None,
            stride_y=None,
            padding_y=None,
            trans=trans)
W
wangyang59 已提交
142
        return conv
Y
Yu Yang 已提交
143 144


W
wangyang59 已提交
145 146 147 148
def generator(noise):
    """
    generator generates a sample given noise
    """
Y
Yu Yang 已提交
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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    param_attr = ParamAttr(
        is_static=is_discriminator_training, initial_mean=0.0, initial_std=0.02)
    bias_attr = ParamAttr(
        is_static=is_discriminator_training, initial_mean=0.0, initial_std=0.0)

    param_attr_bn = ParamAttr(
        is_static=is_discriminator_training, initial_mean=1.0, initial_std=0.02)

    h1 = fc_layer(
        input=noise,
        name="gen_layer_h1",
        size=s8 * s8 * gf_dim * 4,
        bias_attr=bias_attr,
        param_attr=param_attr,
        act=LinearActivation())

    h1_bn = batch_norm_layer(
        h1,
        act=ReluActivation(),
        name="gen_layer_h1_bn",
        bias_attr=bias_attr,
        param_attr=param_attr_bn,
        use_global_stats=False)

    h2_bn = conv_bn(
        h1_bn,
        channels=gf_dim * 4,
        output_x=s8,
        num_filters=gf_dim * 2,
        imgSize=s4,
        stride=2,
        name="gen_layer_h2",
        param_attr=param_attr,
        bias_attr=bias_attr,
        param_attr_bn=param_attr_bn,
        bn=True,
        trans=True)

    h3_bn = conv_bn(
        h2_bn,
        channels=gf_dim * 2,
        output_x=s4,
        num_filters=gf_dim,
        imgSize=s2,
        stride=2,
        name="gen_layer_h3",
        param_attr=param_attr,
        bias_attr=bias_attr,
        param_attr_bn=param_attr_bn,
        bn=True,
        trans=True)

    return conv_bn(
        h3_bn,
        channels=gf_dim,
        output_x=s2,
        num_filters=c_dim,
        imgSize=sample_dim,
        stride=2,
        name="gen_layer_h4",
        param_attr=param_attr,
        bias_attr=bias_attr,
        param_attr_bn=param_attr_bn,
        bn=False,
        trans=True,
        act=TanhActivation())
W
wangyang59 已提交
215 216 217 218 219 220 221 222 223 224


def discriminator(sample):
    """
    discriminator ouputs the probablity of a sample is from generator
    or real data.
    The output has two dimenstional: dimension 0 is the probablity
    of the sample is from generator and dimension 1 is the probabblity
    of the sample is from real data.
    """
Y
Yu Yang 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    param_attr = ParamAttr(
        is_static=is_generator_training, initial_mean=0.0, initial_std=0.02)
    bias_attr = ParamAttr(
        is_static=is_generator_training, initial_mean=0.0, initial_std=0.0)

    param_attr_bn = ParamAttr(
        is_static=is_generator_training, initial_mean=1.0, initial_std=0.02)

    h0 = conv_bn(
        sample,
        channels=c_dim,
        imgSize=sample_dim,
        num_filters=df_dim,
        output_x=s2,
        stride=2,
        name="dis_h0",
        param_attr=param_attr,
        bias_attr=bias_attr,
        param_attr_bn=param_attr_bn,
        bn=False)

    h1_bn = conv_bn(
        h0,
        channels=df_dim,
        imgSize=s2,
        num_filters=df_dim * 2,
        output_x=s4,
        stride=2,
        name="dis_h1",
        param_attr=param_attr,
        bias_attr=bias_attr,
        param_attr_bn=param_attr_bn,
        bn=True)

    h2_bn = conv_bn(
        h1_bn,
        channels=df_dim * 2,
        imgSize=s4,
        num_filters=df_dim * 4,
        output_x=s8,
        stride=2,
        name="dis_h2",
        param_attr=param_attr,
        bias_attr=bias_attr,
        param_attr_bn=param_attr_bn,
        bn=True)
W
wangyang59 已提交
271

Y
Yu Yang 已提交
272 273 274 275 276 277 278
    return fc_layer(
        input=h2_bn,
        name="dis_prob",
        size=2,
        bias_attr=bias_attr,
        param_attr=param_attr,
        act=SoftmaxActivation())
W
wangyang59 已提交
279 280 281 282 283 284 285


if is_generator_training:
    noise = data_layer(name="noise", size=noise_dim)
    sample = generator(noise)

if is_discriminator_training:
Y
Yu Yang 已提交
286
    sample = data_layer(name="sample", size=sample_dim * sample_dim * c_dim)
W
wangyang59 已提交
287 288 289

if is_generator_training or is_discriminator_training:
    label = data_layer(name="label", size=1)
290
    prob = discriminator(sample)
W
wangyang59 已提交
291
    cost = cross_entropy(input=prob, label=label)
Y
Yu Yang 已提交
292 293
    classification_error_evaluator(
        input=prob, label=label, name=mode + '_error')
W
wangyang59 已提交
294 295 296 297 298
    outputs(cost)

if is_generator:
    noise = data_layer(name="noise", size=noise_dim)
    outputs(generator(noise))