This repository has been archived by the owner on Oct 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 238
/
discriminator.py
78 lines (66 loc) · 2.58 KB
/
discriminator.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
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, BatchNormalization, LeakyReLU
from keras_contrib.layers import InstanceNormalization
from layers import ZeroPadding2D, ReflectionPadding2D, StridedConv
class Discriminator(Model):
def __init__(self,
base_filters=32,
lrelu_alpha=0.2,
pad_type="reflect",
norm_type="batch"):
super(Discriminator, self).__init__(name="Discriminator")
if pad_type == "reflect":
self.flat_pad = ReflectionPadding2D()
elif pad_type == "constant":
self.flat_pad = ZeroPadding2D()
else:
raise ValueError(f"pad_type not recognized {pad_type}")
self.flat_conv = Conv2D(base_filters, 3)
self.flat_lru = LeakyReLU(lrelu_alpha)
self.strided_conv1 = StridedConv(base_filters * 2,
lrelu_alpha,
pad_type,
norm_type)
self.strided_conv2 = StridedConv(base_filters * 4,
lrelu_alpha,
pad_type,
norm_type)
self.conv2 = Conv2D(base_filters * 8, 3)
if norm_type == "instance":
self.norm = InstanceNormalization()
elif norm_type == "batch":
self.norm = BatchNormalization()
self.lrelu = LeakyReLU(lrelu_alpha)
self.final_conv = Conv2D(1, 3)
def build(self, input_shape):
super(Discriminator, self).build(input_shape)
def call(self, x, training=False):
x = self.flat_pad(x)
x = self.flat_conv(x)
x = self.flat_lru(x)
x = self.strided_conv1(x, training=training)
x = self.strided_conv2(x, training=training)
x = self.conv2(x)
x = self.norm(x, training=training)
x = self.lrelu(x)
x = self.final_conv(x)
return x
if __name__ == "__main__":
import numpy as np
shape = (1, 256, 256, 3)
nx = np.random.rand(*shape).astype(np.float32)
t = tf.keras.Input(shape=nx.shape[1:], batch_size=nx.shape[0])
tf.keras.backend.clear_session()
sc = StridedConv(t.shape[-1])
out = sc(t)
sc.summary()
print(f"Input Shape: {t.shape}")
print(f"Output Shape: {out.shape}")
print("\n" * 2)
tf.keras.backend.clear_session()
d = Discriminator()
out = d(t)
d.summary()
print(f"Input Shape: {t.shape}")
print(f"Output Shape: {out.shape}")