forked from Lab41/cyphercat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
440 lines (363 loc) · 14.2 KB
/
models.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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import os.path
def new_size_conv(size, kernel, stride=1, padding=0):
return np.floor((size + 2*padding - (kernel -1)-1)/stride +1)
def new_size_max_pool(size, kernel, stride=None, padding=0):
if stride == None:
stride = kernel
return np.floor((size + 2*padding - (kernel -1)-1)/stride +1)
def calc_alexnet_size(size):
x = new_size_conv(size, 6,3,2)
x = new_size_max_pool(x,3,2)
x = new_size_conv(x,5,1,2)
x = new_size_max_pool(x,3,2)
x = new_size_conv(x,3,1,1)
x = new_size_conv(x,3,1,1)
x = new_size_conv(x,3,1,1)
out = new_size_max_pool(x,2,2)
return out
class AlexNet(nn.Module):
def __init__(self, n_classes, size=32):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=6, stride=3, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2),
)
out_feat_size = calc_alexnet_size(size)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * out_feat_size * out_feat_size, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, n_classes),
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
class tiny_cnn(nn.Module):
def __init__(self, n_in=3, n_out=10, n_hidden=64, size=64):
super(tiny_cnn, self).__init__()
self.size = size
self.n_hidden = n_hidden
self.conv_block_1 = nn.Sequential(
nn.Conv2d(n_in, n_hidden, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(n_hidden),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.conv_block_2 = nn.Sequential(
nn.Conv2d(n_hidden, 2*n_hidden, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(2*n_hidden),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.fc = nn.Linear(2*n_hidden * (self.size//4) * (self.size//4), 2*n_hidden)
self.output = nn.Linear(2*n_hidden, n_out)
def forward(self, x):
x = self.conv_block_1(x)
x = self.conv_block_2(x)
x = x.view(x.size(0), -1)
#x = x.view(-1, 2*self.n_hidden * (self.size//4) * (self.size//4))
x = self.fc(x)
out = self.output(x)
return out
def calc_mlleaks_cnn_size(size):
x = new_size_conv(size, 5,1,2)
x = new_size_max_pool(x,2,2)
x = new_size_conv(x,5,1,2)
out = new_size_max_pool(x,2,2)
return out
class mlleaks_cnn(nn.Module):
def __init__(self, n_in=3, n_out=10, n_hidden=64, size=32):
super(mlleaks_cnn, self).__init__()
self.n_hidden = n_hidden
self.conv_block_1 = nn.Sequential(
nn.Conv2d(n_in, n_hidden, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(n_hidden),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.conv_block_2 = nn.Sequential(
nn.Conv2d(n_hidden, 2*n_hidden, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(2*n_hidden),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
fc_feature_size = calc_mlleaks_cnn_size(size)
self.fc = nn.Linear(int(2*n_hidden * fc_feature_size * fc_feature_size), 128)
self.output = nn.Linear(2*n_hidden, n_out)
def forward(self, x):
x = self.conv_block_1(x)
x = self.conv_block_2(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
out = self.output(x)
return out
class ConvBlock(nn.Module):
#for audio_CNN_classifier
def __init__(self, n_input, n_out, kernel_size):
super(ConvBlock, self).__init__()
self.cnn_block = nn.Sequential(
nn.Conv1d(n_input, n_out, kernel_size, padding=1),
nn.BatchNorm1d(n_out),
nn.ReLU(),
nn.MaxPool1d(kernel_size=4, stride=4)
)
def forward(self, x):
return self.cnn_block(x)
class audio_CNN_classifier(nn.Module):
def __init__(self, in_size, n_hidden, n_classes):
super(audio_CNN_classifier, self).__init__()
self.down_path = nn.ModuleList()
self.down_path.append(ConvBlock(in_size, 2*in_size, 3))
self.down_path.append(ConvBlock(2*in_size, 4*in_size, 3))
self.down_path.append(ConvBlock(4*in_size, 8*in_size, 3))
self.fc = nn.Sequential(
nn.Linear(8*in_size, n_hidden),
nn.ReLU()
)
self.out = nn.Linear(n_hidden, n_classes)
def forward(self, x):
for down in self.down_path:
x = down(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return self.out(x)
class STFT_CNN_classifier(nn.Module):
def __init__(self, in_size, n_hidden, n_classes):
super(STFT_CNN_classifier, self).__init__()
self.down_path = nn.ModuleList()
self.down_path.append(ConvBlock(in_size, in_size, 7))
self.down_path.append(ConvBlock(in_size, in_size*2, 7))
self.down_path.append(ConvBlock(in_size*2, in_size*4, 7))
self.fc = nn.Sequential(
nn.Linear(5264, n_hidden),
nn.ReLU()
)
self.out = nn.Linear(n_hidden, n_classes)
def forward(self, x):
for down in self.down_path:
x = down(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return self.out(x)
class mlleaks_mlp(nn.Module):
def __init__(self, n_in=3, n_out=1, n_hidden=64):
super(mlleaks_mlp, self).__init__()
self.hidden = nn.Linear(n_in, n_hidden)
#self.bn = nn.BatchNorm1d(n_hidden)
self.output = nn.Linear(n_hidden, n_out)
def forward(self, x):
x = F.sigmoid(self.hidden(x))
#x = self.bn(x)
out = self.output(x)
#out = F.sigmoid(self.output(x))
return out
class cnn(nn.Module):
def __init__(self, in_channels, out_channels, n_filters):
super(cnn, self).__init__()
self.n_filters = n_filters
self.conv_block_1 = nn.Sequential(
nn.Conv2d(in_channels, n_filters, kernel_size=3, padding=1),
nn.BatchNorm2d(n_filters),
nn.ReLU(inplace=True),
nn.MaxPool2d(2)
)
# shape = [Batch_size, n_filters, height/2, width/2]
self.conv_block_2 = nn.Sequential(
nn.Conv2d(n_filters, n_filters*2, kernel_size=3, padding=1),
nn.BatchNorm2d(n_filters*2),
nn.ReLU(inplace=True),
nn.MaxPool2d(2)
)
# shape = [Batch_size, n_filters*2, height/4, width/4]
self.dense_block_1 = nn.Sequential(
##nn.Linear(n_filters * 2 * 8 * 8, 64),
nn.Linear(n_filters*2 * 8 * 8, 128),
##nn.BatchNorm1d(64),
##nn.ReLU(inplace=True)
)
# shape = [Batch_size, 64]
self.dense_block_2 = nn.Sequential(
nn.Linear(64, 32),
nn.BatchNorm1d(32),
nn.ReLU(inplace=True)
)
# shape = [Batch_size, 32]
self.dense_block_3 = nn.Sequential(
nn.Linear(32, out_channels),
nn.BatchNorm1d(out_channels)
)
# shape = [Batch_size, 10]
def forward(self, x):
x = self.conv_block_1(x)
x = self.conv_block_2(x)
x = x.view(-1, self.n_filters*2 * 8 * 8)
x = self.dense_block_1(x)
x = self.dense_block_2(x)
out = self.dense_block_3(x)
return out
class mlp(nn.Module):
def __init__(self, in_channels, out_channels, n_filters):
super(mlp, self).__init__()
self.n_filters = n_filters
# shape = [Batch_size, k (top k posteriors)]
self.dense_block_1 = nn.Sequential(
nn.Linear(in_channels, n_filters*2),
#nn.BatchNorm1d(n_filters*2),
nn.ReLU(inplace=True)
)
# shape = [Batch_size, n_filters*2]
self.dense_block_2 = nn.Sequential(
nn.Linear(n_filters*2, n_filters*2),
#nn.BatchNorm1d(n_filters*2),
nn.ReLU(inplace=True)
)
# shape = [Batch_size, 32]
self.dense_block_3 = nn.Sequential(
nn.Linear(n_filters*2, out_channels),
#nn.BatchNorm1d(out_channels),
nn.Sigmoid()
)
# shape = [Batch_size, 10]
def forward(self, x):
x = self.dense_block_1(x)
x = self.dense_block_2(x)
out = self.dense_block_3(x)
return out
class audio_cnn_block(nn.Module):
'''
1D convolution block used to build audio cnn classifiers
Args:
input: input channels
output: output channels
kernel_size: convolution kernel size
'''
def __init__(self, n_input, n_out, kernel_size):
super(audio_cnn_block, self).__init__()
self.cnn_block = nn.Sequential(
nn.Conv1d(n_input, n_out, kernel_size, padding=1),
nn.BatchNorm1d(n_out),
nn.ReLU(),
nn.MaxPool1d(kernel_size=4, stride=4)
)
def forward(self, x):
return self.cnn_block(x)
class audio_tiny_cnn(nn.Module):
'''
Template for convolutional audio classifiers.
'''
def __init__(self, cnn_sizes, n_hidden, kernel_size, n_classes):
'''
Init
Args:
cnn_sizes: List of sizes for the convolution blocks
n_hidden: number of hidden units in the first fully connected layer
kernel_size: convolution kernel size
n_classes: number of speakers to classify
'''
super(audio_tiny_cnn, self).__init__()
self.down_path = nn.ModuleList()
self.down_path.append(audio_cnn_block(cnn_sizes[0], cnn_sizes[1],
kernel_size,))
self.down_path.append(audio_cnn_block(cnn_sizes[1], cnn_sizes[2],
kernel_size,))
self.down_path.append(audio_cnn_block(cnn_sizes[2], cnn_sizes[3],
kernel_size,))
self.fc = nn.Sequential(
nn.Linear(cnn_sizes[4], n_hidden),
nn.ReLU()
)
self.out = nn.Linear(n_hidden, n_classes)
def forward(self, x):
for down in self.down_path:
x = down(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return self.out(x)
def MFCC_cnn_classifier(n_classes):
'''
Builds speaker classifier that ingests MFCC's
'''
in_size = 20
n_hidden = 512
sizes_list = [in_size, 2*in_size, 4*in_size, 8*in_size, 8*in_size]
return audio_tiny_cnn(cnn_sizes=sizes_list, n_hidden=n_hidden,
kernel_size=3, n_classes=125)
def ft_cnn_classifer(n_classes):
'''
Builds speaker classifier that ingests the abs value of fourier transforms
'''
in_size = 94
n_hidden = 512
sizes_list = [in_size, in_size, 2*in_size, 4*in_size, 14*4*in_size]
return audio_tiny_cnn(cnn_sizes=sizes_list, n_hidden=n_hidden,
kernel_size=7, n_classes=125)
class RNN(torch.nn.Module):
'''
Bidirectional LSTM for sentiment analysis
'''
def __init__(self, vocab_size, embedding_size, hidden_size, output_size, n_layers=2, bidirectional=True, dropout=0.5):
super(RNN, self).__init__()
self.embedding = torch.nn.Embedding(vocab_size, embedding_size)
self.rnn = torch.nn.LSTM(embedding_size, hidden_size, num_layers=n_layers, bidirectional=bidirectional, dropout=dropout)
self.fc = torch.nn.Linear(hidden_size*2, output_size)
self.dropout = torch.nn.Dropout(dropout)
def forward(self, x):
embedded = self.dropout(self.embedding(x))
output, (hidden, cell) = self.rnn(embedded)
hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1))
return self.fc(hidden.squeeze(0))
def weights_init(m):
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight.data)
nn.init.constant_(m.bias, 0)
def save_checkpoint(model=None, optimizer=None, epoch=None,
data_descriptor=None, loss=None, accuracy=None, path='./',
filename='checkpoint', ext='.pth.tar'):
state = {
'epoch': epoch,
'arch': str(model.type),
'state_dict': model.state_dict(),
'optimizer' : optimizer.state_dict(),
'loss': loss,
'accuracy': accuracy,
'dataset': data_descriptor
}
torch.save(state, path+filename+ext)
def load_checkpoint(model=None, optimizer=None, checkpoint=None):
assert os.path.isfile(checkpoint), 'Checkpoint not found, aborting load'
chpt = torch.load(checkpoint)
assert str(model.type) == chpt['arch'], 'Model arquitecture mismatch,\
aborting load'
model.load_state_dict(chpt['state_dict'])
if optimizer is not None:
optimizer.load_state_dict['optimizer']
print('Succesfully loaded checkpoint \nDataset: %s \nEpoch: %s \nLoss: %s\
\nAccuracy: %s' % (chpt['dataset'], chpt['epoch'], chpt['loss'],
chpt['accuracy']))