-
Notifications
You must be signed in to change notification settings - Fork 1
/
began.py
178 lines (149 loc) · 5.09 KB
/
began.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
# -*- coding: utf-8 -*-
import math
import numpy as np
import chainer, os, collections, six, math, random, time, copy
from chainer import cuda, Variable, optimizers, serializers, function, optimizer, initializers
from chainer.utils import type_check
from chainer import functions as F
from chainer import links as L
import sequential
class Object(object):
pass
def to_object(dict):
obj = Object()
for key, value in dict.iteritems():
setattr(obj, key, value)
return obj
class Params():
def __init__(self, dict=None):
if dict:
self.from_dict(dict)
def from_dict(self, dict):
for attr, value in dict.iteritems():
if hasattr(self, attr):
setattr(self, attr, value)
def to_dict(self):
dict = {}
for attr, value in self.__dict__.iteritems():
if hasattr(value, "to_dict"):
dict[attr] = value.to_dict()
else:
dict[attr] = value
return dict
def dump(self):
for attr, value in self.__dict__.iteritems():
print " {}: {}".format(attr, value)
class Config(Params):
def __init__(self):
self.gamma = 0.5
self.ndim_z = 50
self.ndim_h = 50
self.weight_std = 0.001
self.weight_initializer = "Normal" # Normal, GlorotNormal or HeNormal
self.nonlinearity_d = "leaky_relu"
self.nonlinearity_g = "relu"
self.optimizer = "adam"
self.learning_rate = 0.0001
self.momentum = 0.5
self.gradient_clipping = 1
self.weight_decay = 0
class BEGAN():
def __init__(self, params):
self.params = copy.deepcopy(params)
self.config = to_object(params["config"])
self.chain_discriminator = sequential.chain.Chain(weight_initializer=self.config.weight_initializer, weight_std=self.config.weight_std)
self.chain_generator = sequential.chain.Chain(weight_initializer=self.config.weight_initializer, weight_std=self.config.weight_std)
# add decoder
self.decoder = sequential.from_dict(self.params["decoder"])
self.chain_discriminator.add_sequence_with_name(self.decoder, "decoder")
# add encoder
self.encoder = sequential.from_dict(self.params["encoder"])
self.chain_discriminator.add_sequence_with_name(self.encoder, "encoder")
# add generator
self.generator = sequential.from_dict(self.params["generator"])
self.chain_generator.add_sequence_with_name(self.generator, "generator")
# setup optimizer
self.chain_discriminator.setup_optimizers(self.config.optimizer, self.config.learning_rate, self.config.momentum)
self.chain_generator.setup_optimizers(self.config.optimizer, self.config.learning_rate, self.config.momentum)
self._gpu = False
def update_learning_rate(self, lr):
self.chain_discriminator.update_learning_rate(lr)
self.chain_generator.update_learning_rate(lr)
def to_gpu(self):
self.chain_discriminator.to_gpu()
self.chain_generator.to_gpu()
self._gpu = True
@property
def gpu_enabled(self):
if cuda.available is False:
return False
return self._gpu
@property
def xp(self):
if self.gpu_enabled:
return cuda.cupy
return np
def to_variable(self, x):
if isinstance(x, Variable) == False:
x = Variable(x)
if self.gpu_enabled:
x.to_gpu()
return x
def to_numpy(self, x):
if isinstance(x, Variable) == True:
x = x.data
if isinstance(x, cuda.ndarray) == True:
x = cuda.to_cpu(x)
return x
def get_batchsize(self, x):
return x.shape[0]
def sample_z(self, batchsize=1, gaussian=False):
ndim_z = self.config.ndim_z
if gaussian:
# gaussian
z = np.random.normal(0, 1, (batchsize, ndim_z)).astype(np.float32)
else:
# uniform
z = np.random.uniform(-1, 1, (batchsize, ndim_z)).astype(np.float32)
return z
def generate_x(self, batchsize=1, test=False, as_numpy=False, from_gaussian=False):
return self.generate_x_from_z(self.sample_z(batchsize, gaussian=from_gaussian), test=test, as_numpy=as_numpy)
def generate_x_from_z(self, z, test=False, as_numpy=False):
z = self.to_variable(z)
x = self.generator(z, test=test)
if as_numpy:
return self.to_numpy(x)
return x
def encode(self, x, test=False):
x = self.to_variable(x)
return self.encoder(x, test=test)
def decode(self, z, test=False, as_numpy=False):
z = self.to_variable(z)
x = self.decoder(z, test=test)
if as_numpy:
return self.to_numpy(x)
return x
def compute_loss(self, x, test=False):
x = self.to_variable(x)
z = self.encode(x, test=test)
_x = self.decode(z, test=test)
return F.mean_absolute_error(x, _x)
# return F.mean_squared_error(x, _x)
def backprop_discriminator(self, loss):
self.chain_discriminator.backprop(loss)
def backprop_generator(self, loss):
self.chain_generator.backprop(loss)
def load(self, model_dir=None):
if model_dir is None:
raise Exception()
self.chain_discriminator.load(model_dir + "/discriminator.hdf5")
self.chain_generator.load(model_dir + "/generator.hdf5")
def save(self, model_dir=None):
if model_dir is None:
raise Exception()
try:
os.mkdir(model_dir)
except:
pass
self.chain_discriminator.save(model_dir + "/discriminator.hdf5")
self.chain_generator.save(model_dir + "/generator.hdf5")