mcae.py 4.63 KB
Newer Older
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
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
"""Multi-channel autoencoder network used in:
@inproceedings{NikisinsICB2019,
    author = {Olegs Nikisins, Anjith George, Sebastien Marcel},
    title = {Domain Adaptation in Multi-Channel Autoencoder based Features for Robust Face Anti-Spoofing},
    year = {2019},
    booktitle = {ICB 2019},
}
"""
import tensorflow as tf


def get_l2_kw(weight_decay):
    l2_kw = {}
    if weight_decay is not None:
        l2_kw = {"kernel_regularizer": tf.keras.regularizers.l2(weight_decay)}
    return l2_kw


class ConvEncoder(tf.keras.Model):
    """The encoder part"""

    def __init__(
        self,
        encoder_layers,
        data_format="channels_last",
        weight_decay=1e-5,
        name="Encoder",
        **kwargs,
    ):
        super().__init__(name=name, **kwargs)
        self.data_format = data_format
        l2_kw = get_l2_kw(weight_decay)
        layers = []
        for i, (filters, kernel_size, strides, padding) in enumerate(encoder_layers):
            pad = tf.keras.layers.ZeroPadding2D(
Amir MOHAMMADI's avatar
nitpick    
Amir MOHAMMADI committed
36
                padding=padding, data_format=data_format, name=f"pad_{i}"
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
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
            )
            conv = tf.keras.layers.Conv2D(
                filters,
                kernel_size,
                strides,
                data_format=data_format,
                name=f"conv_{i}",
                **l2_kw,
            )
            act = tf.keras.layers.Activation("relu", name=f"relu_{i}")
            pool = tf.keras.layers.MaxPooling2D(
                data_format=data_format, name=f"pool_{i}"
            )
            layers.extend([pad, conv, act, pool])
        self.sequential_layers = layers

    def call(self, x, training=None):
        for l in self.sequential_layers:
            x = l(x)
        return x


class ConvDecoder(tf.keras.Model):
    """The encoder part"""

    def __init__(
        self,
        decoder_layers,
        data_format="channels_last",
        weight_decay=1e-5,
        name="Decoder",
        **kwargs,
    ):
        super().__init__(name=name, ** kwargs)
        self.data_format = data_format
        l2_kw = get_l2_kw(weight_decay)
        layers = []
        for i, (filters, kernel_size, strides, cropping) in enumerate(decoder_layers):
            dconv = tf.keras.layers.Conv2DTranspose(
                filters,
                kernel_size,
                strides=strides,
                data_format=data_format,
                name=f"dconv_{i}",
Amir MOHAMMADI's avatar
nitpick    
Amir MOHAMMADI committed
81
                **l2_kw,
Amir MOHAMMADI's avatar
Amir MOHAMMADI committed
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
            )
            crop = tf.keras.layers.Cropping2D(
                cropping=cropping, data_format=data_format, name=f"crop_{i}"
            )
            if i == len(decoder_layers) - 1:
                act = tf.keras.layers.Activation("tanh", name="tanh")
            else:
                act = tf.keras.layers.Activation("relu", name=f"relu_{i}")
            layers.extend([dconv, crop, act])
        self.sequential_layers = layers

    def call(self, x, training=None):
        for l in self.sequential_layers:
            x = l(x)
        return x


class ConvAutoencoder(tf.keras.Model):
    """
    A class defining a simple convolutional autoencoder.

    Multi-channel autoencoder network used in::

        @inproceedings{NikisinsICB2019,
            author = {Olegs Nikisins, Anjith George, Sebastien Marcel},
            title = {Domain Adaptation in Multi-Channel Autoencoder based Features for Robust Face Anti-Spoofing},
            year = {2019},
            booktitle = {ICB 2019},
        }

    Attributes
    ----------
    data_format : str
        Either channels_last or channels_first
    decoder : object
        The encoder part
    encoder : object
        The decoder part
    """

    def __init__(
        self,
        data_format="channels_last",
        encoder_layers=((16, 5, 1, 2), (16, 5, 1, 2), (16, 3, 1, 2), (16, 3, 1, 2)),
        decoder_layers=(
            (16, 3, 2, 1),
            (16, 3, 2, 1),
            (16, 5, 2, 2),
            (3, 5, 2, 2),
            (3, 2, 1, 1),
        ),
        weight_decay=1e-5,
        name="ConvAutoencoder",
        **kwargs,
    ):
        super().__init__(name=name, **kwargs)
        self.data_format = data_format
        self.weight_decay = weight_decay

        self.encoder = ConvEncoder(
            encoder_layers,
            data_format=data_format,
            weight_decay=weight_decay,
            name="Encoder",
        )
        self.decoder = ConvDecoder(
            decoder_layers,
            data_format=data_format,
            weight_decay=weight_decay,
            name="Decoder",
        )

    def call(self, x, training=None):
        x = self.encoder(x, training=training)
        self.encoder_output = x
        x = self.decoder(x, training=training)
        return x