-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.py
63 lines (47 loc) · 2.28 KB
/
generator.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
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
import helper
class Generator():
"""Wrapper around a keras model for a generator cnn network"""
def __init__(self, res_blocks=16, upsampling=2):
self.upsampling = upsampling
self.res_blocks = res_blocks
self.generator = self._build_model()
def get_model(self):
"""Returns the model object"""
return self.generator
def _res_block(self, model_in, filters=64, kernel_size=3, strides=1):
"""Appends a residual block to the sequential model """
model = Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding="same")(model_in)
model = BatchNormalization(momentum=0.8)(model)
model = PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1, 2])(model)
model = Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding="same")(model)
model = BatchNormalization(momentum=0.8)(model)
model = Add()([model_in, model])
return model
def _upsample_block(self, model, filters=256, kernel_size=3, strides=1):
"""Appends a upsampling 2d block to the sequential model"""
model = Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding="same")(model)
model = UpSampling2D(size=2)(model)
model = LeakyReLU(alpha=0.2)(model)
return model
def _build_model(self):
"""Create the model"""
helper.cprint("Building generator network")
model_input = Input(shape=(None, None, 3))
# Add pre-residual blocks
model = Conv2D(filters=64, kernel_size=9, strides=1, padding="same")(model_input)
model = model_1 = PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model)
# Add the residual blocks
for _ in range(self.res_blocks):
model = self._res_block(model)
# Add post residuals block
model = Conv2D(filters=64, kernel_size=3, strides=1, padding="same")(model)
model = BatchNormalization()(model)
model = Add()([model_1, model])
# Add upsampling blocks
for _ in range(self.upsampling):
model = self._upsample_block(model)
model = Conv2D(filters=3, kernel_size=9, strides=1, padding="same")(model)
model = Activation('tanh')(model)
return Model(model_input, model)