This repository has been archived by the owner on Jun 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
model.py
203 lines (162 loc) · 7.76 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
195
196
197
198
199
200
201
202
203
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tflib as tl
# ==============================================================================
# = alias =
# ==============================================================================
conv = partial(tl.conv2d, activation_fn=None)
dconv = partial(slim.conv2d_transpose, activation_fn=None)
fc = partial(tl.flatten_fully_connected_v2, activation_fn=None)
relu = tf.nn.relu
lrelu = tf.nn.leaky_relu
# batch_norm = partial(slim.batch_norm, scale=True)
batch_norm = partial(slim.batch_norm, scale=True, updates_collections=None)
layer_norm = slim.layer_norm
instance_norm = slim.instance_norm
# spectral_norm = tl.spectral_normalization
spectral_norm = partial(tl.spectral_normalization, updates_collections=None)
# ==============================================================================
# = models =
# ==============================================================================
def _get_norm_fn(norm_name, is_training):
if norm_name == 'none':
norm = None
elif norm_name == 'batch_norm':
norm = partial(batch_norm, is_training=is_training)
elif norm_name == 'instance_norm':
norm = instance_norm
elif norm_name == 'layer_norm':
norm = layer_norm
return norm
def _get_weight_norm_fn(weights_norm_name, is_training):
if weights_norm_name == 'none':
weights_norm = None
elif weights_norm_name == 'spectral_norm':
weights_norm = partial(spectral_norm, is_training=is_training)
return weights_norm
def G_conv_mnist(z, dim=64, is_training=True):
norm = _get_norm_fn('batch_norm', is_training)
fc_norm_relu = partial(fc, normalizer_fn=norm, activation_fn=relu)
dconv_norm_relu = partial(dconv, normalizer_fn=norm, activation_fn=relu)
with tf.variable_scope('G', reuse=tf.AUTO_REUSE):
y = fc_norm_relu(z, 1024)
y = fc_norm_relu(y, 7 * 7 * dim * 2)
y = tf.reshape(y, [-1, 7, 7, dim * 2])
y = dconv_norm_relu(y, dim * 2, 4, 2)
x = tf.tanh(dconv(y, 1, 4, 2))
return x
def D_conv_mnist(x, dim=64, is_training=True, norm_name='batch_norm', weights_norm_name='none'):
norm = _get_norm_fn(norm_name, is_training)
weights_nome = _get_weight_norm_fn(weights_norm_name, is_training)
fc_norm_lrelu = partial(fc, normalizer_fn=norm, weights_normalizer_fn=weights_nome, activation_fn=lrelu)
conv_norm_lrelu = partial(conv, normalizer_fn=norm, weights_normalizer_fn=weights_nome, activation_fn=lrelu)
with tf.variable_scope('D', reuse=tf.AUTO_REUSE):
y = conv_norm_lrelu(x, 1, 4, 2)
y = conv_norm_lrelu(y, dim, 4, 2)
y = fc_norm_lrelu(y, 1024) # fc_norm doesn't work with instance normalization
logit = fc(y, 1, weights_normalizer_fn=weights_nome)
# logit = fc(y, 1)
return logit
def G_conv_64(z, dim=64, is_training=True):
norm = _get_norm_fn('batch_norm', is_training)
fc_norm_relu = partial(fc, normalizer_fn=norm, activation_fn=relu)
dconv_norm_relu = partial(dconv, normalizer_fn=norm, activation_fn=relu)
with tf.variable_scope('G', reuse=tf.AUTO_REUSE):
y = fc_norm_relu(z, 4 * 4 * dim * 8)
y = tf.reshape(y, [-1, 4, 4, dim * 8])
y = dconv_norm_relu(y, dim * 4, 4, 2)
y = dconv_norm_relu(y, dim * 2, 4, 2)
y = dconv_norm_relu(y, dim * 1, 4, 2)
x = tf.tanh(dconv(y, 3, 4, 2))
return x
def D_conv_64(x, dim=64, is_training=True, norm_name='batch_norm', weights_norm_name='none'):
norm = _get_norm_fn(norm_name, is_training)
weights_nome = _get_weight_norm_fn(weights_norm_name, is_training)
conv_norm_lrelu = partial(conv, normalizer_fn=norm, weights_normalizer_fn=weights_nome, activation_fn=lrelu)
with tf.variable_scope('D', reuse=tf.AUTO_REUSE):
y = conv_norm_lrelu(x, dim, 4, 2)
y = conv_norm_lrelu(y, dim * 2, 4, 2)
y = conv_norm_lrelu(y, dim * 4, 4, 2)
y = conv_norm_lrelu(y, dim * 8, 4, 2)
logit = fc(y, 1, weights_normalizer_fn=weights_nome)
# logit = fc(y, 1)
return logit
def get_models(model_name):
if model_name == 'conv_mnist':
return G_conv_mnist, D_conv_mnist
elif model_name == 'conv_64':
return G_conv_64, D_conv_64
# ==============================================================================
# = loss function =
# ==============================================================================
def get_loss_fn(mode):
if mode == 'gan':
def d_loss_fn(r_logit, f_logit):
r_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(r_logit), r_logit)
f_loss = tf.losses.sigmoid_cross_entropy(tf.zeros_like(f_logit), f_logit)
return r_loss, f_loss
def g_loss_fn(f_logit):
f_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(f_logit), f_logit)
return f_loss
elif mode == 'lsgan':
def d_loss_fn(r_logit, f_logit):
r_loss = tf.losses.mean_squared_error(tf.ones_like(r_logit), r_logit)
f_loss = tf.losses.mean_squared_error(tf.zeros_like(f_logit), f_logit)
return r_loss, f_loss
def g_loss_fn(f_logit):
f_loss = tf.losses.mean_squared_error(tf.ones_like(f_logit), f_logit)
return f_loss
elif mode == 'wgan':
def d_loss_fn(r_logit, f_logit):
r_loss = - tf.reduce_mean(r_logit)
f_loss = tf.reduce_mean(f_logit)
return r_loss, f_loss
def g_loss_fn(f_logit):
f_loss = - tf.reduce_mean(f_logit)
return f_loss
elif mode == 'hinge':
def d_loss_fn(r_logit, f_logit):
r_loss = tf.reduce_mean(tf.maximum(1 - r_logit, 0))
f_loss = tf.reduce_mean(tf.maximum(1 + f_logit, 0))
return r_loss, f_loss
def g_loss_fn(f_logit):
# f_loss = tf.reduce_mean(tf.maximum(1 - f_logit, 0))
f_loss = tf.reduce_mean(- f_logit)
return f_loss
return d_loss_fn, g_loss_fn
# ==============================================================================
# = others =
# ==============================================================================
def gradient_penalty(f, real, fake, mode):
def _gradient_penalty(f, real, fake=None):
def _interpolate(a, b=None):
with tf.name_scope('interpolate'):
if b is None: # interpolation in DRAGAN
beta = tf.random_uniform(shape=tf.shape(a), minval=0., maxval=1.)
_, variance = tf.nn.moments(a, range(a.shape.ndims))
b = a + 0.5 * tf.sqrt(variance) * beta
shape = [tf.shape(a)[0]] + [1] * (a.shape.ndims - 1)
alpha = tf.random_uniform(shape=shape, minval=0., maxval=1.)
inter = a + alpha * (b - a)
inter.set_shape(a.get_shape().as_list())
return inter
with tf.name_scope('gradient_penalty'):
x = _interpolate(real, fake)
pred = f(x)
if isinstance(pred, tuple):
pred = pred[0]
grad = tf.gradients(pred, x)[0]
norm = tf.norm(slim.flatten(grad), axis=1)
gp = tf.reduce_mean((norm - 1.)**2)
return gp
if mode == 'none':
gp = tf.constant(0, dtype=tf.float32)
elif mode == 'wgan-gp':
gp = _gradient_penalty(f, real, fake)
elif mode == 'dragan':
gp = _gradient_penalty(f, real)
return gp