File size: 7,569 Bytes
fa128ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import numpy as np
import torch
import torch.nn as nn
from torch.nn.init import xavier_uniform

class KAE(nn.Module):

    def __init__(self, w=32, h=32, c=1, nb_hidden=300, nb_active=16):
        super().__init__()
        self.nb_hidden = nb_hidden
        self.nb_active = nb_active
        self.encode = nn.Sequential(
            nn.Linear(w*h*c, nb_hidden, bias=False)
        )
        self.bias = nn.Parameter(torch.zeros(w*h*c))
        self.params = nn.ParameterList([self.bias])
        self.apply(_weights_init)

    def forward(self, X):
        size = X.size()
        X = X.view(X.size(0), -1)
        h = self.encode(X)
        Xr, _ = self.decode(h)
        Xr = Xr.view(size)
        return Xr
    
    def decode(self, h):
        thetas, _ = torch.sort(h, dim=1, descending=True)
        thetas = thetas[:, self.nb_active:self.nb_active+1]
        h = h * (h > thetas).float()
        Xr = torch.matmul(h, self.encode[0].weight) + self.bias
        Xr = nn.Sigmoid()(Xr)
        return Xr, h


class ZAE(nn.Module):

    def __init__(self, w=32, h=32, c=1, nb_hidden=300, theta=1):
        super().__init__()
        self.nb_hidden = nb_hidden
        self.theta = theta
        self.encode = nn.Sequential(
            nn.Linear(w*h*c, nb_hidden, bias=False)
        )
        self.bias = nn.Parameter(torch.zeros(w*h*c))
        self.params = nn.ParameterList([self.bias])
        self.apply(_weights_init)

    def forward(self, X):
        size = X.size()
        X = X.view(X.size(0), -1)
        h = self.encode(X)
        Xr, _ = self.decode(h)
        Xr = Xr.view(size)
        return Xr
    
    def decode(self, h):
        h  = h * (h > self.theta).float()
        Xr = torch.matmul(h, self.encode[0].weight) + self.bias
        Xr = nn.Sigmoid()(Xr)
        return Xr, h



class DenseAE(nn.Module):

    def __init__(self, w=32, h=32, c=1, encode_hidden=(300,), decode_hidden=(300,), ksparse=True, nb_active=10, denoise=None):
        super().__init__()
        self.encode_hidden = encode_hidden
        self.decode_hidden = decode_hidden
        self.ksparse = ksparse
        self.nb_active = nb_active
        self.denoise = denoise
        
        # encode layers
        layers = []
        hid_prev = w * h * c
        for hid in encode_hidden:
            layers.extend([
                nn.Linear(hid_prev, hid),
                nn.ReLU(True)
            ])
            hid_prev = hid
        self.encode = nn.Sequential(*layers)
        
        # decode layers
        layers = []
        for hid in decode_hidden:
            layers.extend([
                nn.Linear(hid_prev, hid),
                nn.ReLU(True)
            ])
            hid_prev = hid
        layers.extend([
            nn.Linear(hid_prev, w * h * c),
            nn.Sigmoid()
        ])
        self.decode = nn.Sequential(*layers)
        
        self.apply(_weights_init)

    def forward(self, X):
        size = X.size()
        if self.denoise is not None:
            X = X * ((torch.rand(X.size()) <= self.denoise).float()).to(X.device)
        X = X.view(X.size(0), -1)
        h = self.encode(X)
        if self.ksparse:
            h = ksparse(h, nb_active=self.nb_active)
        Xr = self.decode(h)
        Xr = Xr.view(size)
        return Xr



def ksparse(x, nb_active=10):
    mask = torch.ones(x.size())
    for i, xi in enumerate(x.data.tolist()):
        inds = np.argsort(xi)
        inds = inds[::-1]
        inds = inds[nb_active:]
        if len(inds):
            inds = np.array(inds)
            inds = torch.from_numpy(inds).long()
            mask[i][inds] = 0
    return x * (mask).float().to(x.device)


class ConvAE(nn.Module):

    def __init__(self, w=32, h=32, c=1, nb_filters=64, spatial=True, channel=True, channel_stride=4):
        super().__init__()
        self.spatial = spatial
        self.channel = channel
        self.channel_stride = channel_stride
        self.encode = nn.Sequential(
            nn.Conv2d(c, nb_filters, 5, 1, 0),
            nn.ReLU(True),
            nn.Conv2d(nb_filters, nb_filters, 5, 1, 0),
            nn.ReLU(True),
            nn.Conv2d(nb_filters, nb_filters, 5, 1, 0),
        )
        self.decode = nn.Sequential(
            nn.ConvTranspose2d(nb_filters, c, 13, 1, 0),
            nn.Sigmoid()
        )
        self.apply(_weights_init)

    def forward(self, X):
        size = X.size()
        h = self.encode(X)
        h = self.sparsify(h)
        Xr = self.decode(h)
        return Xr
    
    def sparsify(self, h):
        if self.spatial:
            h = spatial_sparsity(h)
        if self.channel:
            h = strided_channel_sparsity(h, stride=self.channel_stride)
        return h

class SimpleConvAE(nn.Module):

    def __init__(self, w=32, h=32, c=1, nb_filters=64, spatial=True, channel=True, channel_stride=4):
        super().__init__()
        self.spatial = spatial
        self.channel = channel
        self.channel_stride = channel_stride
        self.encode = nn.Sequential(
            nn.Conv2d(c, nb_filters, 13, 1, 0),
            nn.ReLU(True),
        )
        self.decode = nn.Sequential(
            nn.ConvTranspose2d(nb_filters, c, 13, 1, 0),
            nn.Sigmoid()
        )
        self.apply(_weights_init)

    def forward(self, X):
        size = X.size()
        h = self.encode(X)
        h = self.sparsify(h)
        Xr = self.decode(h)
        return Xr
    
    def sparsify(self, h):
        if self.spatial:
            h = spatial_sparsity(h)
        if self.channel:
            h = strided_channel_sparsity(h, stride=self.channel_stride)
        return h

class DeepConvAE(nn.Module):

    def __init__(self, w=32, h=32, c=1, nb_filters=64, nb_layers=3, spatial=True, channel=True, channel_stride=4):
        super().__init__()
        self.spatial = spatial
        self.channel = channel
        self.channel_stride = channel_stride

        layers = [
            nn.Conv2d(c, nb_filters, 5, 1, 0),
            nn.ReLU(True),
        ]
        for _ in range(nb_layers - 1):
            layers.extend([
                nn.Conv2d(nb_filters, nb_filters, 5, 1, 0),
                nn.ReLU(True),
            ])
        self.encode = nn.Sequential(*layers)
        layers = []
        for _ in range(nb_layers - 1):
            layers.extend([
                nn.ConvTranspose2d(nb_filters, nb_filters, 5, 1, 0),
                nn.ReLU(True),
            ])
        layers.extend([
            nn.ConvTranspose2d(nb_filters, c, 5, 1, 0),
            nn.Sigmoid()
        ])
        self.decode = nn.Sequential(*layers)
        self.apply(_weights_init)

    def forward(self, X):
        size = X.size()
        h = self.encode(X)
        h = self.sparsify(h)
        Xr = self.decode(h)
        return Xr
    
    def sparsify(self, h):
        if self.spatial:
            h = spatial_sparsity(h)
        if self.channel:
            h = strided_channel_sparsity(h, stride=self.channel_stride)
        return h


def spatial_sparsity(x):
    maxes = x.amax(dim=(2,3), keepdims=True)
    return x * equals(x, maxes)

def equals(x, y, eps=1e-8):
    return torch.abs(x-y) <= eps

def strided_channel_sparsity(x, stride=1):
    B, F = x.shape[0:2]
    h, w = x.shape[2:]
    x_ = x.view(B, F, h // stride, stride, w // stride, stride)
    mask = equals(x_, x_.amax(axis=(1, 3, 5), keepdims=True))
    mask = mask.view(x.shape).float()
    return x * mask


def _weights_init(m):
    if hasattr(m, 'weight'):
        xavier_uniform(m.weight.data)
        if m.bias is not None:
            m.bias.data.fill_(0)