-
Notifications
You must be signed in to change notification settings - Fork 23
/
gaussian_readout_models.py
783 lines (644 loc) · 33 KB
/
gaussian_readout_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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
from collections import OrderedDict, Iterable
import numpy as np
import torch
import warnings
from torch import nn as nn
from torch.nn import Parameter
from torch.nn import functional as F
from torch.nn import ModuleDict
from mlutils.constraints import positive
from mlutils.layers.cores import DepthSeparableConv2d, Core2d, Stacked2dCore
from ..utility.nn_helpers import get_io_dims, get_module_output, set_random_seed, get_dims_for_loader_dict
from mlutils import regularizers
from mlutils.layers.readouts import PointPooled2d, Gaussian2d
from .pretrained_models import TransferLearningCore
# Squeeze and Excitation Block
class SQ_EX_Block(nn.Module):
def __init__(self, in_ch, reduction=16):
super(SQ_EX_Block, self).__init__()
self.se = nn.Sequential(
GlobalAvgPool(),
nn.Linear(in_ch, in_ch // reduction),
nn.ReLU(inplace=True),
nn.Linear(in_ch // reduction, in_ch),
nn.Sigmoid()
)
def forward(self, x):
se_weight = self.se(x).unsqueeze(-1).unsqueeze(-1)
return x.mul(se_weight)
class GlobalAvgPool(nn.Module):
def __init__(self):
super(GlobalAvgPool, self).__init__()
def forward(self, x):
return x.view(*(x.shape[:-2]), -1).mean(-1)
class SE2dCore(Core2d, nn.Module):
def __init__(
self,
input_channels,
hidden_channels,
input_kern,
hidden_kern,
layers=3,
gamma_input=0.0,
skip=0,
final_nonlinearity=True,
bias=False,
momentum=0.1,
pad_input=True,
batch_norm=True,
hidden_dilation=1,
laplace_padding=None,
input_regularizer="LaplaceL2norm",
stack=None,
se_reduction=32,
n_se_blocks=1,
depth_separable=False,
):
"""
Args:
input_channels: Integer, number of input channels as in
hidden_channels: Number of hidden channels (i.e feature maps) in each hidden layer
input_kern: kernel size of the first layer (i.e. the input layer)
hidden_kern: kernel size of each hidden layer's kernel
layers: number of layers
gamma_input: regularizer factor for the input weights (default: LaplaceL2, see mlutils.regularizers)
skip: Adds a skip connection
final_nonlinearity: Boolean, if true, appends an ELU layer after the last BatchNorm (if BN=True)
bias: Adds a bias layer. Note: bias and batch_norm can not both be true
momentum: BN momentum
pad_input: Boolean, if True, applies zero padding to all convolutions
batch_norm: Boolean, if True appends a BN layer after each convolutional layer
hidden_dilation: If set to > 1, will apply dilated convs for all hidden layers
laplace_padding: Padding size for the laplace convolution. If padding = None, it defaults to half of
the kernel size (recommended). Setting Padding to 0 is not recommended and leads to artefacts,
zero is the default however to recreate backwards compatibility.
normalize_laplace_regularizer: Boolean, if set to True, will use the LaplaceL2norm function from
mlutils.regularizers, which returns the regularizer as |laplace(filters)| / |filters|
input_regularizer: String that must match one of the regularizers in ..regularizers
stack: Int or iterable. Selects which layers of the core should be stacked for the readout.
default value will stack all layers on top of each other.
stack = -1 will only select the last layer as the readout layer
stack = 0 will only readout from the first layer
se_reduction: Int. Reduction of Channels for Global Pooling of the Squeeze and Excitation Block.
"""
super().__init__()
assert not bias or not batch_norm, "bias and batch_norm should not both be true"
regularizer_config = (
dict(padding=laplace_padding, kernel=input_kern)
if input_regularizer == "GaussianLaplaceL2"
else dict(padding=laplace_padding)
)
self._input_weights_regularizer = regularizers.__dict__[input_regularizer](**regularizer_config)
self.layers = layers
self.gamma_input = gamma_input
self.input_channels = input_channels
self.hidden_channels = hidden_channels
self.skip = skip
self.features = nn.Sequential()
self.n_se_blocks = n_se_blocks
if stack is None:
self.stack = range(self.layers)
else:
self.stack = [*range(self.layers)[stack:]] if isinstance(stack, int) else stack
# --- first layer
layer = OrderedDict()
layer["conv"] = nn.Conv2d(
input_channels, hidden_channels, input_kern, padding=input_kern // 2 if pad_input else 0, bias=bias
)
if batch_norm:
layer["norm"] = nn.BatchNorm2d(hidden_channels, momentum=momentum)
if layers > 1 or final_nonlinearity:
layer["nonlin"] = nn.ELU(inplace=True)
self.features.add_module("layer0", nn.Sequential(layer))
if not isinstance(hidden_kern, Iterable):
hidden_kern = [hidden_kern] * (self.layers - 1)
# --- other layers
for l in range(1, self.layers):
layer = OrderedDict()
hidden_padding = ((hidden_kern[l - 1] - 1) * hidden_dilation + 1) // 2
if depth_separable:
layer["ds_conv"] = DepthSeparableConv2d(hidden_channels, hidden_channels, kernel_size=hidden_kern[l - 1],
dilation=hidden_dilation, padding=hidden_padding, bias=False,
stride=1)
else:
layer["conv"] = nn.Conv2d(
hidden_channels if not skip > 1 else min(skip, l) * hidden_channels,
hidden_channels,
hidden_kern[l - 1],
padding=hidden_padding,
bias=bias,
dilation=hidden_dilation,
)
if batch_norm:
layer["norm"] = nn.BatchNorm2d(hidden_channels, momentum=momentum)
if final_nonlinearity or l < self.layers - 1:
layer["nonlin"] = nn.ELU(inplace=True)
if (self.layers - l) <= self.n_se_blocks:
layer["seg_ex_block"] = SQ_EX_Block(in_ch=hidden_channels, reduction=se_reduction)
self.features.add_module("layer{}".format(l), nn.Sequential(layer))
self.apply(self.init_conv)
def forward(self, input_):
ret = []
for l, feat in enumerate(self.features):
do_skip = l >= 1 and self.skip > 1
input_ = feat(input_ if not do_skip else torch.cat(ret[-min(self.skip, l) :], dim=1))
if l in self.stack:
ret.append(input_)
return torch.cat(ret, dim=1)
def laplace(self):
return self._input_weights_regularizer(self.features[0].conv.weight)
def regularizer(self):
return self.gamma_input * self.laplace()
@property
def outchannels(self):
return len(self.features) * self.hidden_channels
class DepthSeparableCore(Core2d, nn.Module):
def __init__(
self,
input_channels,
hidden_channels,
input_kern,
hidden_kern,
layers=3,
gamma_input=0.0,
skip=0,
final_nonlinearity=True,
bias=False,
momentum=0.1,
pad_input=True,
batch_norm=True,
hidden_dilation=1,
laplace_padding=None,
input_regularizer="LaplaceL2norm",
stack=None,
):
"""
Args:
input_channels: Integer, number of input channels as in
hidden_channels: Number of hidden channels (i.e feature maps) in each hidden layer
input_kern: kernel size of the first layer (i.e. the input layer)
hidden_kern: kernel size of each hidden layer's kernel
layers: number of layers
gamma_input: regularizer factor for the input weights (default: LaplaceL2, see mlutils.regularizers)
skip: Adds a skip connection
final_nonlinearity: Boolean, if true, appends an ELU layer after the last BatchNorm (if BN=True)
bias: Adds a bias layer. Note: bias and batch_norm can not both be true
momentum: BN momentum
pad_input: Boolean, if True, applies zero padding to all convolutions
batch_norm: Boolean, if True appends a BN layer after each convolutional layer
hidden_dilation: If set to > 1, will apply dilated convs for all hidden layers
laplace_padding: Padding size for the laplace convolution. If padding = None, it defaults to half of
the kernel size (recommended). Setting Padding to 0 is not recommended and leads to artefacts,
zero is the default however to recreate backwards compatibility.
normalize_laplace_regularizer: Boolean, if set to True, will use the LaplaceL2norm function from
mlutils.regularizers, which returns the regularizer as |laplace(filters)| / |filters|
input_regularizer: String that must match one of the regularizers in ..regularizers
stack: Int or iterable. Selects which layers of the core should be stacked for the readout.
default value will stack all layers on top of each other.
stack = -1 will only select the last layer as the readout layer
stack = 0 will only readout from the first layer
"""
super().__init__()
assert not bias or not batch_norm, "bias and batch_norm should not both be true"
regularizer_config = (
dict(padding=laplace_padding, kernel=input_kern)
if input_regularizer == "GaussianLaplaceL2"
else dict(padding=laplace_padding)
)
self._input_weights_regularizer = regularizers.__dict__[input_regularizer](**regularizer_config)
self.layers = layers
self.gamma_input = gamma_input
self.input_channels = input_channels
self.hidden_channels = hidden_channels
self.skip = skip
self.features = nn.Sequential()
if stack is None:
self.stack = range(self.layers)
else:
self.stack = [*range(self.layers)[stack:]] if isinstance(stack, int) else stack
# --- first layer
layer = OrderedDict()
layer["conv"] = nn.Conv2d(
input_channels, hidden_channels, input_kern, padding=input_kern // 2 if pad_input else 0, bias=bias
)
if batch_norm:
layer["norm"] = nn.BatchNorm2d(hidden_channels, momentum=momentum)
if layers > 1 or final_nonlinearity:
layer["nonlin"] = nn.ELU(inplace=True)
self.features.add_module("layer0", nn.Sequential(layer))
# def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=True):
if not isinstance(hidden_kern, Iterable):
hidden_kern = [hidden_kern] * (self.layers - 1)
# --- other layers
for l in range(1, self.layers):
layer = OrderedDict()
hidden_padding = ((hidden_kern[l - 1] - 1) * hidden_dilation + 1) // 2
layer["ds_conv"] = DepthSeparableConv2d(hidden_channels, hidden_channels, kernel_size=hidden_kern[l-1], dilation=hidden_dilation, padding=hidden_padding, bias=False, stride=1)
if batch_norm:
layer["norm"] = nn.BatchNorm2d(hidden_channels, momentum=momentum)
if final_nonlinearity or l < self.layers - 1:
layer["nonlin"] = nn.ELU(inplace=True)
self.features.add_module("layer{}".format(l), nn.Sequential(layer))
self.apply(self.init_conv)
def forward(self, input_):
ret = []
for l, feat in enumerate(self.features):
do_skip = l >= 1 and self.skip > 1
input_ = feat(input_ if not do_skip else torch.cat(ret[-min(self.skip, l) :], dim=1))
if l in self.stack:
ret.append(input_)
return torch.cat(ret, dim=1)
def laplace(self):
return self._input_weights_regularizer(self.features[0].conv.weight)
def regularizer(self):
return self.gamma_input * self.laplace()
@property
def outchannels(self):
return len(self.features) * self.hidden_channels
class MultiplePointPooled2d(nn.ModuleDict):
def __init__(self, core, in_shape_dict, n_neurons_dict, pool_steps, pool_kern, bias, init_range, gamma_readout):
# super init to get the _module attribute
super(MultiplePointPooled2d, self).__init__()
for k in n_neurons_dict:
in_shape = get_module_output(core, in_shape_dict[k])[1:]
n_neurons = n_neurons_dict[k]
self.add_module(k, PointPooled2d(
in_shape,
n_neurons,
pool_steps=pool_steps,
pool_kern=pool_kern,
bias=bias,
init_range=init_range)
)
self.gamma_readout = gamma_readout
def forward(self, *args, data_key=None, **kwargs):
if data_key is None and len(self) == 1:
data_key = list(self.keys())[0]
return self[data_key](*args, **kwargs)
def regularizer(self, data_key):
return self[data_key].feature_l1(average=False) * self.gamma_readout
class MultipleGaussian2d(nn.ModuleDict):
def __init__(self, core, in_shape_dict, n_neurons_dict, init_mu_range, init_sigma_range, bias, gamma_readout):
# super init to get the _module attribute
super(MultipleGaussian2d, self).__init__()
for k in n_neurons_dict:
in_shape = get_module_output(core, in_shape_dict[k])[1:]
n_neurons = n_neurons_dict[k]
self.add_module(k, Gaussian2d(
in_shape=in_shape,
outdims=n_neurons,
init_mu_range=init_mu_range,
init_sigma_range=init_sigma_range,
bias=bias)
)
self.gamma_readout = gamma_readout
def forward(self, *args, data_key=None, **kwargs):
if data_key is None and len(self) == 1:
data_key = list(self.keys())[0]
return self[data_key](*args, **kwargs)
def regularizer(self, data_key):
return self[data_key].feature_l1(average=False) * self.gamma_readout
def se_core_gauss_readout(dataloaders, seed, hidden_channels=32, input_kern=13, # core args
hidden_kern=3, layers=3, gamma_input=15.5,
skip=0, final_nonlinearity=True, momentum=0.9,
pad_input=False, batch_norm=True, hidden_dilation=1,
laplace_padding=None, input_regularizer='LaplaceL2norm',
init_mu_range=0.2, init_sigma_range=0.5, readout_bias=True, # readout args,
gamma_readout=4, elu_offset=0, stack=None, se_reduction=32, n_se_blocks=1,
depth_separable=False,
):
"""
Model class of a stacked2dCore (from mlutils) and a pointpooled (spatial transformer) readout
Args:
dataloaders: a dictionary of dataloaders, one loader per session
in the format {'data_key': dataloader object, .. }
seed: random seed
elu_offset: Offset for the output non-linearity [F.elu(x + self.offset)]
all other args: See Documentation of Stacked2dCore in mlutils.layers.cores and
PointPooled2D in mlutils.layers.readouts
Returns: An initialized model which consists of model.core and model.readout
"""
if "train" in dataloaders.keys():
dataloaders = dataloaders["train"]
# Obtain the named tuple fields from the first entry of the first dataloader in the dictionary
in_name, out_name = next(iter(list(dataloaders.values())[0]))._fields
session_shape_dict = get_dims_for_loader_dict(dataloaders)
n_neurons_dict = {k: v[out_name][1] for k, v in session_shape_dict.items()}
in_shapes_dict = {k: v[in_name] for k, v in session_shape_dict.items()}
input_channels = [v[in_name][1] for v in session_shape_dict.values()]
class Encoder(nn.Module):
def __init__(self, core, readout, elu_offset):
super().__init__()
self.core = core
self.readout = readout
self.offset = elu_offset
def forward(self, x, data_key=None, **kwargs):
x = self.core(x)
sample = kwargs["sample"] if 'sample' in kwargs else None
x = self.readout(x, data_key=data_key, sample=sample)
return F.elu(x + self.offset) + 1
def regularizer(self, data_key):
return self.core.regularizer() + self.readout.regularizer(data_key=data_key)
set_random_seed(seed)
# get a stacked2D core from mlutils
core = SE2dCore(input_channels=input_channels[0],
hidden_channels=hidden_channels,
input_kern=input_kern,
hidden_kern=hidden_kern,
layers=layers,
gamma_input=gamma_input,
skip=skip,
final_nonlinearity=final_nonlinearity,
bias=False,
momentum=momentum,
pad_input=pad_input,
batch_norm=batch_norm,
hidden_dilation=hidden_dilation,
laplace_padding=laplace_padding,
input_regularizer=input_regularizer,
stack=stack,
se_reduction=se_reduction,
n_se_blocks=n_se_blocks,
depth_separable=depth_separable)
readout = MultipleGaussian2d(core, in_shape_dict=in_shapes_dict,
n_neurons_dict=n_neurons_dict,
init_mu_range=init_mu_range,
bias=readout_bias,
init_sigma_range=init_sigma_range,
gamma_readout=gamma_readout)
# initializing readout bias to mean response
if readout_bias:
for k in dataloaders:
readout[k].bias.data = dataloaders[k].dataset[:][1].mean(0)
model = Encoder(core, readout, elu_offset)
return model
def ds_core_gauss_readout(dataloaders, seed, hidden_channels=32, input_kern=13, # core args
hidden_kern=3, layers=3, gamma_input=0.1,
skip=0, final_nonlinearity=True, momentum=0.9,
pad_input=False, batch_norm=True, hidden_dilation=1,
laplace_padding=None, input_regularizer='LaplaceL2norm',
init_mu_range=0.2, init_sigma_range=0.5, readout_bias=True, # readout args,
gamma_readout=4, elu_offset=0, stack=None,
):
"""
Model class of a stacked2dCore (from mlutils) and a pointpooled (spatial transformer) readout
Args:
dataloaders: a dictionary of dataloaders, one loader per session
in the format {'data_key': dataloader object, .. }
seed: random seed
elu_offset: Offset for the output non-linearity [F.elu(x + self.offset)]
all other args: See Documentation of Stacked2dCore in mlutils.layers.cores and
PointPooled2D in mlutils.layers.readouts
Returns: An initialized model which consists of model.core and model.readout
"""
if "train" in dataloaders.keys():
dataloaders = dataloaders["train"]
# Obtain the named tuple fields from the first entry of the first dataloader in the dictionary
in_name, out_name = next(iter(list(dataloaders.values())[0]))._fields
session_shape_dict = get_dims_for_loader_dict(dataloaders)
n_neurons_dict = {k: v[out_name][1] for k, v in session_shape_dict.items()}
in_shapes_dict = {k: v[in_name] for k, v in session_shape_dict.items()}
input_channels = [v[in_name][1] for v in session_shape_dict.values()]
class Encoder(nn.Module):
def __init__(self, core, readout, elu_offset):
super().__init__()
self.core = core
self.readout = readout
self.offset = elu_offset
def forward(self, x, data_key=None, **kwargs):
x = self.core(x)
sample = kwargs["sample"] if 'sample' in kwargs else None
x = self.readout(x, data_key=data_key, sample=sample)
return F.elu(x + self.offset) + 1
def regularizer(self, data_key):
return self.core.regularizer() + self.readout.regularizer(data_key=data_key)
set_random_seed(seed)
# get a stacked2D core from mlutils
core = DepthSeparableCore(input_channels=input_channels[0],
hidden_channels=hidden_channels,
input_kern=input_kern,
hidden_kern=hidden_kern,
layers=layers,
gamma_input=gamma_input,
skip=skip,
final_nonlinearity=final_nonlinearity,
bias=False,
momentum=momentum,
pad_input=pad_input,
batch_norm=batch_norm,
hidden_dilation=hidden_dilation,
laplace_padding=laplace_padding,
input_regularizer=input_regularizer,
stack=stack)
readout = MultipleGaussian2d(core, in_shape_dict=in_shapes_dict,
n_neurons_dict=n_neurons_dict,
init_mu_range=init_mu_range,
bias=readout_bias,
init_sigma_range=init_sigma_range,
gamma_readout=gamma_readout)
# initializing readout bias to mean response
if readout_bias:
for k in dataloaders:
readout[k].bias.data = dataloaders[k].dataset[:][1].mean(0)
model = Encoder(core, readout, elu_offset)
return model
def ds_core_point_readout(dataloaders, seed, hidden_channels=32, input_kern=13, # core args
hidden_kern=3, layers=3, gamma_input=0.1,
skip=0, final_nonlinearity=True, core_bias=False, momentum=0.9,
pad_input=False, batch_norm=True, hidden_dilation=1,
laplace_padding=None, input_regularizer='LaplaceL2norm',
pool_steps=2, pool_kern=3, readout_bias=True, # readout args,
init_range=0.2, gamma_readout=0.1, elu_offset=0, stack=None,
):
"""
Model class of a stacked2dCore (from mlutils) and a pointpooled (spatial transformer) readout
Args:
dataloaders: a dictionary of dataloaders, one loader per session
in the format {'data_key': dataloader object, .. }
seed: random seed
elu_offset: Offset for the output non-linearity [F.elu(x + self.offset)]
all other args: See Documentation of Stacked2dCore in mlutils.layers.cores and
PointPooled2D in mlutils.layers.readouts
Returns: An initialized model which consists of model.core and model.readout
"""
if "train" in dataloaders.keys():
dataloaders = dataloaders["train"]
# Obtain the named tuple fields from the first entry of the first dataloader in the dictionary
in_name, out_name = next(iter(list(dataloaders.values())[0]))._fields
session_shape_dict = get_dims_for_loader_dict(dataloaders)
n_neurons_dict = {k: v[out_name][1] for k, v in session_shape_dict.items()}
in_shapes_dict = {k: v[in_name] for k, v in session_shape_dict.items()}
input_channels = [v[in_name][1] for v in session_shape_dict.values()]
class Encoder(nn.Module):
def __init__(self, core, readout, elu_offset):
super().__init__()
self.core = core
self.readout = readout
self.offset = elu_offset
def forward(self, x, data_key=None, **kwargs):
x = self.core(x)
x = self.readout(x, data_key=data_key, **kwargs)
return F.elu(x + self.offset) + 1
def regularizer(self, data_key):
return self.core.regularizer() + self.readout.regularizer(data_key=data_key)
set_random_seed(seed)
# get a stacked2D core from mlutils
core = DepthSeparableCore(input_channels=input_channels[0],
hidden_channels=hidden_channels,
input_kern=input_kern,
hidden_kern=hidden_kern,
layers=layers,
gamma_input=gamma_input,
skip=skip,
final_nonlinearity=final_nonlinearity,
bias=core_bias,
momentum=momentum,
pad_input=pad_input,
batch_norm=batch_norm,
hidden_dilation=hidden_dilation,
laplace_padding=laplace_padding,
input_regularizer=input_regularizer,
stack=stack)
readout = MultiplePointPooled2d(core, in_shape_dict=in_shapes_dict,
n_neurons_dict=n_neurons_dict,
pool_steps=pool_steps,
pool_kern=pool_kern,
bias=readout_bias,
gamma_readout=gamma_readout,
init_range=init_range)
if readout_bias:
for k in dataloaders:
readout[k].bias.data = dataloaders[k].dataset[:][1].mean(0)
model = Encoder(core, readout, elu_offset)
return model
def stacked2d_core_gaussian_readout(dataloaders, seed, hidden_channels=32, input_kern=13, # core args
hidden_kern=3, layers=3, gamma_hidden=0, gamma_input=0.1,
skip=0, final_nonlinearity=True, core_bias=False, momentum=0.9,
pad_input=False, batch_norm=True, hidden_dilation=1,
laplace_padding=None, input_regularizer='LaplaceL2norm',
readout_bias=True, init_mu_range=0.2, init_sigma_range=0.5, # readout args,
gamma_readout=0.1, elu_offset=0, stack=None,
):
"""
Model class of a stacked2dCore (from mlutils) and a pointpooled (spatial transformer) readout
Args:
dataloaders: a dictionary of dataloaders, one loader per session
in the format {'data_key': dataloader object, .. }
seed: random seed
elu_offset: Offset for the output non-linearity [F.elu(x + self.offset)]
all other args: See Documentation of Stacked2dCore in mlutils.layers.cores and
PointPooled2D in mlutils.layers.readouts
Returns: An initialized model which consists of model.core and model.readout
"""
if "train" in dataloaders.keys():
dataloaders = dataloaders["train"]
in_name, out_name = next(iter(list(dataloaders.values())[0]))._fields
session_shape_dict = get_dims_for_loader_dict(dataloaders)
n_neurons_dict = {k: v[out_name][1] for k, v in session_shape_dict.items()}
in_shapes_dict = {k: v[in_name] for k, v in session_shape_dict.items()}
input_channels = [v[in_name][1] for v in session_shape_dict.values()]
assert np.unique(input_channels).size == 1, "all input channels must be of equal size"
class Encoder(nn.Module):
def __init__(self, core, readout, elu_offset):
super().__init__()
self.core = core
self.readout = readout
self.offset = elu_offset
def forward(self, x, data_key=None, **kwargs):
x = self.core(x)
x = self.readout(x, data_key=data_key, **kwargs)
return F.elu(x + self.offset) + 1
def regularizer(self, data_key):
return self.core.regularizer() + self.readout.regularizer(data_key=data_key)
set_random_seed(seed)
# get a stacked2D core from mlutils
core = Stacked2dCore(input_channels=input_channels[0],
hidden_channels=hidden_channels,
input_kern=input_kern,
hidden_kern=hidden_kern,
layers=layers,
gamma_hidden=gamma_hidden,
gamma_input=gamma_input,
skip=skip,
final_nonlinearity=final_nonlinearity,
bias=core_bias,
momentum=momentum,
pad_input=pad_input,
batch_norm=batch_norm,
hidden_dilation=hidden_dilation,
laplace_padding=laplace_padding,
input_regularizer=input_regularizer,
stack=stack)
readout = MultipleGaussian2d(core, in_shape_dict=in_shapes_dict,
n_neurons_dict=n_neurons_dict,
init_mu_range=init_mu_range,
init_sigma_range=init_sigma_range,
bias=readout_bias,
gamma_readout=gamma_readout)
if readout_bias:
for k in dataloaders:
readout[k].bias.data = dataloaders[k].dataset[:][1].mean(0)
model = Encoder(core, readout, elu_offset)
return model
def vgg_core_gauss_readout(dataloaders, seed,
input_channels=1, tr_model_fn='vgg16', # begin of core args
model_layer=11, momentum=0.1, final_batchnorm=True,
final_nonlinearity=True, bias=False,
init_mu_range=0.4, init_sigma_range=0.6, readout_bias=True, # begin or readout args
gamma_readout=0.002, elu_offset=-1):
"""
A Model class of a predefined core (using models from torchvision.models). Can be initialized pretrained or random.
Can also be set to be trainable or not, independent of initialization.
Args:
dataloaders: a dictionary of train-dataloaders, one loader per session
in the format {'data_key': dataloader object, .. }
seed: ..
pool_steps:
pool_kern:
readout_bias:
init_range:
gamma_readout:
Returns:
"""
if "train" in dataloaders.keys():
dataloaders = dataloaders["train"]
in_name, out_name = next(iter(list(dataloaders.values())[0]))._fields
session_shape_dict = get_dims_for_loader_dict(dataloaders)
n_neurons_dict = {k: v[out_name][1] for k, v in session_shape_dict.items()}
in_shapes_dict = {k: v[in_name] for k, v in session_shape_dict.items()}
input_channels = [v[in_name][1] for v in session_shape_dict.values()]
assert np.unique(input_channels).size == 1, "all input channels must be of equal size"
class Encoder(nn.Module):
"""
helper nn class that combines the core and readout into the final model
"""
def __init__(self, core, readout, elu_offset):
super().__init__()
self.core = core
self.readout = readout
self.offset = elu_offset
def forward(self, x, data_key=None, **kwargs):
x = self.core(x)
x = self.readout(x, data_key=data_key)
return F.elu(x + self.offset) + 1
def regularizer(self, data_key):
return self.readout.regularizer(data_key=data_key) + self.core.regularizer()
set_random_seed(seed)
core = TransferLearningCore(input_channels=input_channels[0],
tr_model_fn=tr_model_fn,
model_layer=model_layer,
momentum=momentum,
final_batchnorm=final_batchnorm,
final_nonlinearity=final_nonlinearity,
bias=bias)
readout = MultipleGaussian2d(core, in_shape_dict=in_shapes_dict,
n_neurons_dict=n_neurons_dict,
init_mu_range=init_mu_range,
bias=readout_bias,
init_sigma_range=init_sigma_range,
gamma_readout=gamma_readout)
if readout_bias:
for k in dataloaders:
readout[k].bias.data = dataloaders[k].dataset[:][1].mean(0)
model = Encoder(core, readout, elu_offset)
return model