/
abstract_conv.py
3157 lines (2744 loc) · 139 KB
/
abstract_conv.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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Abstract conv interface
"""
from __future__ import absolute_import, print_function, division
import logging
from six import reraise, integer_types
import sys
try:
from math import gcd
except ImportError:
from fractions import gcd
import theano
from theano.tensor import as_tensor_variable, patternbroadcast
from theano.tensor import get_scalar_constant_value, NotScalarConstantError
from theano.tensor.opt import Assert
from theano.gof import Apply, Op
from six.moves import xrange
import warnings
import numpy as np
try:
from scipy.signal.signaltools import _valfrommode, _bvalfromboundary, convolve
from scipy.signal.sigtools import _convolve2d
imported_scipy_signal = True
except ImportError:
imported_scipy_signal = False
__docformat__ = "restructuredtext en"
_logger = logging.getLogger("theano.tensor.nnet.abstract_conv")
def get_conv_output_shape(image_shape, kernel_shape,
border_mode, subsample,
filter_dilation=None):
"""
This function compute the output shape of convolution operation.
Parameters
----------
image_shape: tuple of int (symbolic or numeric) corresponding to the input
image shape. Its four (or five) element must correspond respectively
to: batch size, number of input channels, height and width (and
possibly depth) of the image. None where undefined.
kernel_shape: tuple of int (symbolic or numeric) corresponding to the
kernel shape. For a normal convolution, its four (for 2D convolution)
or five (for 3D convolution) elements must correspond respectively to :
number of output channels, number of input channels, height and width
(and possibly depth) of the kernel.
For an unshared 2D convolution, its six channels must correspond to :
number of output channels, height and width of the output, number of
input channels, height and width of the kernel.
None where undefined.
border_mode: string, int (symbolic or numeric) or tuple of int (symbolic
or numeric) or pairs of ints. If it is a string, it must be 'valid',
'half' or 'full'. If it is a tuple, its two (or three) elements respectively
correspond to the padding on height and width (and possibly depth)
axis. For asymmetric padding, provide a pair of ints for each dimension.
subsample: tuple of int (symbolic or numeric). Its two or three elements
espectively correspond to the subsampling on height and width (and
possibly depth) axis.
filter_dilation: tuple of int (symbolic or numeric). Its two or three
elements correspond respectively to the dilation on height and width axis.
Note - The shape of the convolution output does not depend on the 'unshared'
or the 'num_groups' parameters.
Returns
-------
output_shape: tuple of int corresponding to the output image shape. Its
four element must correspond respectively to: batch size, number of
output channels, height and width of the image. None where undefined.
"""
bsize, imshp = image_shape[0], image_shape[2:]
convdim = len(image_shape) - 2
nkern, kshp = kernel_shape[0], kernel_shape[-convdim:]
if filter_dilation is None:
filter_dilation = np.ones(len(subsample), dtype='int')
if isinstance(border_mode, tuple):
out_shp = tuple(get_conv_shape_1axis(
imshp[i], kshp[i], border_mode[i],
subsample[i], filter_dilation[i]) for i in range(len(subsample)))
else:
out_shp = tuple(get_conv_shape_1axis(
imshp[i], kshp[i], border_mode,
subsample[i], filter_dilation[i]) for i in range(len(subsample)))
return (bsize, nkern) + out_shp
# filter dilation set by default to 1
# for compatibility with other tests.
def get_conv_shape_1axis(image_shape, kernel_shape, border_mode,
subsample, dilation=1):
"""
This function compute the output shape of convolution operation.
Parameters
----------
image_shape: int or None. Corresponds to the input image shape on a
given axis. None if undefined.
kernel_shape: int or None. Corresponds to the kernel shape on a given
axis. None if undefined.
border_mode: string, int or tuple of 2 ints. If it is a string, it must be
'valid', 'half' or 'full'. If it is an integer, it must correspond to
the padding on the considered axis. If it is a tuple, its two elements
must correspond to the asymmetric padding (e.g., left and right) on
the considered axis.
subsample: int. It must correspond to the subsampling on the
considered axis.
dilation: int. It must correspond to the dilation on the
considered axis.
Returns
-------
out_shp: int corresponding to the output image shape on the
considered axis. None if undefined.
"""
if None in [image_shape, kernel_shape, border_mode,
subsample, dilation]:
return None
# Implicit dilated kernel shape
dil_kernel_shape = (kernel_shape - 1) * dilation + 1
if border_mode == "half":
pad_l = pad_r = dil_kernel_shape // 2
elif border_mode == "full":
pad_l = pad_r = dil_kernel_shape - 1
elif border_mode == "valid":
pad_l = pad_r = 0
else:
if isinstance(border_mode, tuple):
pad_l, pad_r = border_mode
else:
pad_l = pad_r = border_mode
if pad_l < 0 or pad_r < 0:
raise ValueError("border_mode must be >= 0")
# In case of symbolic shape, we want to build the smallest graph
# (image_shape + 2 * pad - dil_kernel_shape) // subsample + 1
out_shp = (image_shape - dil_kernel_shape)
if pad_l != 0:
out_shp += pad_l
if pad_r != 0:
out_shp += pad_r
if subsample != 1:
out_shp = out_shp // subsample
out_shp = out_shp + 1
return out_shp
def get_conv_gradweights_shape(image_shape, top_shape,
border_mode, subsample,
filter_dilation=None,
num_groups=1, unshared=False):
"""
This function tries to compute the kernel shape of convolution gradWeights.
The weights shape can only be computed exactly when subsample is 1 and
border_mode is not 'half'. If subsample is not 1 or border_mode is 'half',
this function will return None.
Parameters
----------
image_shape: tuple of int corresponding to the input image shape. Its
four (or five) elements must correspond respectively to: batch size,
number of output channels, height and width of the image. None where
undefined.
top_shape: tuple of int (symbolic or numeric) corresponding to the top
image shape. Its four (or five) element must correspond respectively
to: batch size, number of output channels, height and width (and
possibly depth) of the image. None where undefined.
border_mode: string, int (symbolic or numeric) or tuple of int (symbolic
or numeric) or pairs of ints. If it is a string, it must be 'valid',
'half' or 'full'. If it is a tuple, its two (or three) elements respectively
correspond to the padding on height and width (and possibly depth)
axis. For asymmetric padding, provide a pair of ints for each dimension.
subsample: tuple of int (symbolic or numeric). Its two or three elements
respectively correspond to the subsampling on height and width (and
possibly depth) axis.
filter_dilation: tuple of int (symbolic or numeric). Its two or three
elements correspond respectively to the dilation on height and
width axis.
num_groups: An int which specifies the number of separate groups to
be divided into.
unshared: Boolean value. If true, unshared convolution will be performed,
where a different filter is applied to each area of the input.
Returns
-------
kernel_shape: tuple of int (symbolic or numeric) corresponding to the
kernel shape. Its four (or five) elements correspond respectively
to: number of output channels, number of input channels, height and
width (and possibly depth) of the kernel. None where undefined.
"""
nkern, imshp = image_shape[1], image_shape[2:]
nchan, topshp = top_shape[1], top_shape[2:]
if filter_dilation is None:
filter_dilation = np.ones(len(subsample), dtype='int')
if num_groups > 1:
nchan = nchan // num_groups
if isinstance(border_mode, tuple):
out_shp = tuple(get_conv_gradweights_shape_1axis(
imshp[i], topshp[i], border_mode[i],
subsample[i], filter_dilation[i]) for i in range(len(subsample)))
else:
out_shp = tuple(get_conv_gradweights_shape_1axis(
imshp[i], topshp[i], border_mode,
subsample[i], filter_dilation[i]) for i in range(len(subsample)))
if unshared:
return (nchan,) + top_shape[2:] + (nkern,) + out_shp
else:
return (nchan, nkern) + out_shp
def get_conv_gradweights_shape_1axis(image_shape, top_shape, border_mode,
subsample, dilation):
"""
This function tries to compute the image shape of convolution gradWeights.
The weights shape can only be computed exactly when subsample is 1 and
border_mode is not 'half'. If subsample is not 1 or border_mode is 'half',
this function will return None.
Parameters
----------
image_shape: int or None. Corresponds to the input image shape on a
given axis. None if undefined.
top_shape: int or None. Corresponds to the top shape on a given axis.
None if undefined.
border_mode: string, int or tuple of 2 ints. If it is a string, it must be
'valid', 'half' or 'full'. If it is an integer, it must correspond to
the padding on the considered axis. If it is a tuple, its two elements
must correspond to the asymmetric padding (e.g., left and right) on
the considered axis.
subsample: int. It must correspond to the subsampling on the
considered axis.
dilation: int. It must correspond to the dilation on the
considered axis.
Returns
-------
kernel_shape: int or None. Corresponds to the kernel shape on a given
axis. None if undefined.
"""
if None in [image_shape, top_shape, border_mode,
subsample, dilation]:
return None
if subsample != 1 or border_mode == "half":
return None
if border_mode == "full":
kernel_shape = top_shape - image_shape
elif border_mode == "valid":
kernel_shape = image_shape - top_shape
else:
if isinstance(border_mode, tuple):
pad_l, pad_r = border_mode
else:
pad_l = pad_r = border_mode
if pad_l < 0 or pad_r < 0:
raise ValueError("border_mode must be >= 0")
kernel_shape = (image_shape + pad_l + pad_r - top_shape)
if dilation > 1:
kernel_shape = kernel_shape / dilation
return kernel_shape + 1
def get_conv_gradinputs_shape(kernel_shape, top_shape,
border_mode, subsample,
filter_dilation=None,
num_groups=1):
"""
This function tries to compute the image shape of convolution gradInputs.
The image shape can only be computed exactly when subsample is 1.
If subsample for a dimension is not 1, this function will return None for
that dimension.
Parameters
----------
kernel_shape: tuple of int (symbolic or numeric) corresponding to the
kernel shape. Its four (or five) elements must correspond respectively
to: number of output channels, number of input channels, height and
width (and possibly depth) of the kernel. None where undefined.
top_shape: tuple of int (symbolic or numeric) corresponding to the top
image shape. Its four (or five) element must correspond respectively
to: batch size, number of output channels, height and width (and
possibly depth) of the image. None where undefined.
border_mode: string, int (symbolic or numeric) or tuple of int (symbolic
or numeric) or pairs of ints. If it is a string, it must be 'valid',
'half' or 'full'. If it is a tuple, its two (or three) elements respectively
correspond to the padding on height and width (and possibly depth)
axis. For asymmetric padding, provide a pair of ints for each dimension.
subsample: tuple of int (symbolic or numeric). Its two or three elements
respectively correspond to the subsampling on height and width (and
possibly depth) axis.
filter_dilation: tuple of int (symbolic or numeric). Its two or three
elements correspond respectively to the dilation on height and
width axis.
num_groups: An int which specifies the number of separate groups to
be divided into.
Note - The shape of the convolution output does not depend on the 'unshared'
parameter.
Returns
-------
image_shape: tuple of int corresponding to the input image shape. Its
four element must correspond respectively to: batch size, number of
output channels, height and width of the image. None where undefined.
"""
bsize, topshp = top_shape[0], top_shape[2:]
convdim = len(top_shape) - 2
nkern, kshp = kernel_shape[1], kernel_shape[-convdim:]
if filter_dilation is None:
filter_dilation = np.ones(len(subsample), dtype='int')
if num_groups > 1:
nkern = nkern * num_groups
if isinstance(border_mode, tuple):
out_shp = tuple(get_conv_gradinputs_shape_1axis(
kshp[i], topshp[i], border_mode[i],
subsample[i], filter_dilation[i]) for i in range(len(subsample)))
else:
out_shp = tuple(get_conv_gradinputs_shape_1axis(
kshp[i], topshp[i], border_mode,
subsample[i], filter_dilation[i]) for i in range(len(subsample)))
return (bsize, nkern) + out_shp
def get_conv_gradinputs_shape_1axis(kernel_shape, top_shape, border_mode,
subsample, dilation):
"""
This function tries to compute the image shape of convolution gradInputs.
The image shape can only be computed exactly when subsample is 1.
If subsample is not 1, this function will return None.
Parameters
----------
kernel_shape: int or None. Corresponds to the kernel shape on a given
axis. None if undefined.
top_shape: int or None. Corresponds to the top shape on a given axis.
None if undefined.
border_mode: string, int or tuple of 2 ints. If it is a string, it must be
'valid', 'half' or 'full'. If it is an integer, it must correspond to
the padding on the considered axis. If it is a tuple, its two elements
must correspond to the asymmetric padding (e.g., left and right) on
the considered axis.
subsample: int. It must correspond to the subsampling on the
considered axis.
dilation: int. It must correspond to the dilation on the
considered axis.
Returns
-------
image_shape: int or None. Corresponds to the input image shape on a
given axis. None if undefined.
"""
if None in [kernel_shape, top_shape, border_mode,
subsample, dilation]:
return None
if subsample != 1:
return None
# Implicit dilated kernel shape
dil_kernel_shape = (kernel_shape - 1) * dilation + 1
if border_mode == "half":
pad_l = pad_r = dil_kernel_shape // 2
elif border_mode == "full":
pad_l = pad_r = dil_kernel_shape - 1
elif border_mode == "valid":
pad_l = pad_r = 0
else:
if isinstance(border_mode, tuple):
pad_l, pad_r = border_mode
else:
pad_l = pad_r = border_mode
if pad_l < 0 or pad_r < 0:
raise ValueError("border_mode must be >= 0")
# In case of symbolic shape, we want to build the smallest graph
# image_shape = (top_shape - 1) * s - 2 * pad + dil_kernel_shape + a
# where 0 <= a < subsample, but we have checked that subsample == 1
image_shape = (top_shape + dil_kernel_shape - 1)
if pad_l > 0:
image_shape -= pad_l
if pad_r > 0:
image_shape -= pad_r
return image_shape
def check_conv_gradinputs_shape(image_shape, kernel_shape, output_shape,
border_mode, subsample,
filter_dilation=None):
"""
This function checks if the given image shapes are consistent.
Parameters
----------
image_shape: tuple of int (symbolic or numeric) corresponding to the input
image shape. Its four (or five) element must correspond respectively
to: batch size, number of input channels, height and width (and
possibly depth) of the image. None where undefined.
kernel_shape: tuple of int (symbolic or numeric) corresponding to the
kernel shape. Its four (or five) elements must correspond respectively
to: number of output channels, number of input channels, height and
width (and possibly depth) of the kernel. None where undefined.
output_shape: tuple of int (symbolic or numeric) corresponding to the
output shape. Its four (or five) elements must correspond respectively
to: batch size, number of output channels, height and width
(and possibly depth) of the output. None where undefined.
border_mode: string, int (symbolic or numeric) or tuple of int (symbolic
or numeric) or pairs of ints. If it is a string, it must be 'valid',
'half' or 'full'. If it is a tuple, its two (or three) elements respectively
correspond to the padding on height and width (and possibly depth)
axis. For asymmetric padding, provide a pair of ints for each dimension.
subsample: tuple of int (symbolic or numeric). Its two or three elements
respectively correspond to the subsampling on height and width (and
possibly depth) axis.
filter_dilation: tuple of int (symbolic or numeric). Its two or three
elements correspond respectively to the dilation on height and
width axis.
Returns
-------
Returns False if a convolution with the given input shape, kernel shape
and parameters would not have produced the given output shape.
Returns True in all other cases: if the given output shape matches the
computed output shape, but also if the shape could not be checked because
because the shape contains symbolic values.
"""
image_shape = tuple(image_shape)
kernel_shape = tuple(kernel_shape)
output_shape = tuple(output_shape)
if len(image_shape) != len(kernel_shape) or len(image_shape) != len(output_shape):
return False
if len(image_shape) - 2 != len(subsample):
return False
if filter_dilation is not None and len(image_shape) - 2 != len(filter_dilation):
return False
# compute the predicted output shape
computed_output_shape = get_conv_output_shape(
image_shape, kernel_shape, border_mode, subsample, filter_dilation)
# check if the given output shape matches the computed shape
def check_dim(given, computed):
if given is None or computed is None:
return True
try:
given = get_scalar_constant_value(given)
computed = get_scalar_constant_value(computed)
return int(given) == int(computed)
except NotScalarConstantError:
# no answer possible, accept for now
return True
return all(check_dim(given, computed)
for (given, computed) in zip(output_shape, computed_output_shape))
def assert_conv_shape(shape):
"""This function adds Assert nodes that check if shape is a valid convolution shape.
The first two dimensions should be larger than or equal to zero. The convolution
dimensions should be larger than zero.
Parameters
----------
shape: tuple of int (symbolic or numeric) corresponding to the input, output or
kernel shape of a convolution. For input and output, the first elements should
should be the batch size and number of channels. For kernels, the first and
second elements should contain the number of input and output channels.
The remaining dimensions are the convolution dimensions.
Returns
-------
Returns a tuple similar to the given `shape`. For constant elements in `shape`,
the function checks the value and raises a `ValueError` if the dimension is invalid.
The elements that are not constant are wrapped in an `Assert` op that checks the
dimension at run time.
"""
out_shape = []
for i, n in enumerate(shape):
try:
const_n = get_scalar_constant_value(n)
if i < 2:
if const_n < 0:
raise ValueError('The convolution would produce an invalid shape (dim[%d]: %d < 0).' % (i, const_n))
else:
if const_n <= 0:
raise ValueError('The convolution would produce an invalid shape (dim[%d]: %d <= 0).' % (i, const_n))
out_shape.append(n)
except NotScalarConstantError:
if i < 2:
assert_shp = Assert('The convolution would produce an invalid shape (dim[%d] < 0).' % i)
out_shape.append(assert_shp(n, theano.tensor.ge(n, 0)))
else:
assert_shp = Assert('The convolution would produce an invalid shape (dim[%d] <= 0).' % i)
out_shape.append(assert_shp(n, theano.tensor.gt(n, 0)))
return tuple(out_shape)
def assert_shape(x, expected_shape, msg='Unexpected shape.'):
"""Wraps `x` in an `Assert` to check its shape.
Parameters
----------
x : Tensor
x will be wrapped in an `Assert`.
expected_shape : tuple or list
The expected shape of `x`. The size of a dimension can be None,
which means it will not be checked.
msg : str
The error message of the `Assert`.
Returns
-------
Tensor
`x` wrapped in an `Assert`. At execution time, this will throw an
AssertionError if the shape of `x` does not match `expected_shape`.
If `expected_shape` is None or contains only Nones, the function
will return `x` directly.
"""
if expected_shape is None or not theano.config.conv.assert_shape:
return x
shape = x.shape
tests = []
for i in range(x.ndim):
if expected_shape[i] is not None:
tests.append(theano.tensor.eq(shape[i], expected_shape[i]))
if tests:
return Assert(msg)(x, *tests)
else:
return x
def border_mode_to_pad(mode, convdim, kshp):
"""
Computes a tuple for padding given the border_mode parameter
Parameters
----------
mode : int or tuple
One of "valid", "full", "half", an integer, or a tuple where each
member is either an integer or a tuple of 2 positive integers.
convdim : int
The dimensionality of the convolution.
kshp : List/tuple of length 'convdim', indicating the size of the
kernel in the spatial dimensions.
Returns
-------
A tuple containing 'convdim' elements, each of which is a tuple of
two positive integers corresponding to the padding on the left
and the right sides respectively.
"""
if isinstance(mode, tuple):
if len(mode) != convdim:
raise ValueError(
'invalid border_mode {} which must be a '
'tuple of length {}'.format(mode, convdim))
border = ()
for m in mode:
if isinstance(m, integer_types) and m >= 0:
border += ((m, m),)
elif isinstance(m, tuple) and min(m) >= 0 and \
all(isinstance(b, integer_types) for b in m):
if len(m) != 2:
raise NotImplementedError(
'Asymmetric padding not implemented '
'for {}d'.format(len(m)))
border += ((m[0], m[1]),)
else:
raise ValueError(
'invalid border mode {}. The tuple can only contain '
'integers or tuples of length 2'.format(mode))
pad = border
elif mode == 'full':
pad = tuple((kshp[i] - 1,) * 2 for i in range(convdim))
elif mode == 'half':
pad = tuple((kshp[i] // 2,) * 2 for i in range(convdim))
elif mode == 'valid':
pad = ((0, 0),) * convdim
else:
raise ValueError(
'invalid border_mode {}, which must be either '
'"valid", "full", "half", an integer or a tuple '
'of length {}'.format(mode, convdim))
return pad
def conv2d(input,
filters,
input_shape=None,
filter_shape=None,
border_mode='valid',
subsample=(1, 1),
filter_flip=True,
filter_dilation=(1, 1),
num_groups=1,
unshared=False):
"""This function will build the symbolic graph for convolving a mini-batch of a
stack of 2D inputs with a set of 2D filters. The implementation is modelled
after Convolutional Neural Networks (CNN).
Refer to :func:`nnet.conv2d <theano.tensor.nnet.conv2d>` for a more detailed documentation.
"""
input = as_tensor_variable(input)
filters = as_tensor_variable(filters)
conv_op = AbstractConv2d(imshp=input_shape,
kshp=filter_shape,
border_mode=border_mode,
subsample=subsample,
filter_flip=filter_flip,
filter_dilation=filter_dilation,
num_groups=num_groups,
unshared=unshared)
return conv_op(input, filters)
def separable_conv2d(input,
depthwise_filters,
pointwise_filters,
num_channels,
input_shape=None,
depthwise_filter_shape=None,
pointwise_filter_shape=None,
border_mode='valid',
subsample=(1, 1),
filter_flip=True,
filter_dilation=(1, 1)):
"""
This function will build the symbolic graph for depthwise
convolutions which act separately on the input channels followed by
pointwise convolution which mixes channels.
Parameters
----------
input: symbolic 4D tensor
Mini-batch of feature map stacks, of shape
(batch size, input channels, input rows, input columns).
See the optional parameter ``input_shape``.
depthwise_filters: symbolic 4D tensor
Set of filters used depthwise convolution layer of shape
(depthwise output channels, 1, filter rows, filter columns).
pointwise_filters: symbolic 4D tensor
Set of filters used pointwise convolution layer of shape
(output channels, depthwise output channels, 1, 1).
num_channels: int
The number of channels of the input. Required for depthwise
convolutions.
input_shape: None, tuple/list of len 4 of int or Constant variable
The shape of the input parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
depthwise_filter_shape: None, tuple/list of len 4 of int or Constant variable
The shape of the depthwise filters parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
pointwise_filter_shape: None, tuple/list of len 4 of int or Constant variable
The shape of the pointwise filters parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
border_mode: str, int or tuple of two int
This applies only to depthwise convolutions
Either of the following:
``'valid'``: apply filter wherever it completely overlaps with the
input. Generates output of shape: input shape - filter shape + 1
``'full'``: apply filter wherever it partly overlaps with the input.
Generates output of shape: input shape + filter shape - 1
``'half'``: pad input with a symmetric border of ``filter rows // 2``
rows and ``filter columns // 2`` columns, then perform a valid
convolution. For filters with an odd number of rows and columns, this
leads to the output shape being equal to the input shape.
``int``: pad input with a symmetric border of zeros of the given
width, then perform a valid convolution.
``(int1, int2)``: pad input with a symmetric border of ``int1`` rows
and ``int2`` columns, then perform a valid convolution.
``(int1, (int2, int3))`` or ``((int1, int2), int3)``:
pad input with one symmetric border of `int1`` or ``int3``, and
one asymmetric border of ``(int2, int3)`` or ``(int1, int2)``.
``((int1, int2), (int3, int4))``: pad input with an asymmetric
border of ``(int1, int2)`` along one dimension and ``(int3, int4)``
along the second dimension.
subsample: tuple of len 2
Factor by which to subsample the output.
This applies only to depthwise convolutions
filter_flip: bool
If ``True``, will flip the filter rows and columns
before sliding them over the input. This operation is normally referred
to as a convolution, and this is the default. If ``False``, the filters
are not flipped and the operation is referred to as a cross-correlation.
filter_dilation: tuple of len 2
Factor by which to subsample (stride) the input.
This applies only to depthwise convolutions
Returns
-------
Symbolic 4D tensor
Set of feature maps generated by convolutional layer. Tensor is
of shape (batch size, output channels, output rows, output columns)
"""
input = as_tensor_variable(input)
depthwise_filters = as_tensor_variable(depthwise_filters)
conv_op = AbstractConv2d(imshp=input_shape,
kshp=depthwise_filter_shape,
border_mode=border_mode,
subsample=subsample,
filter_flip=filter_flip,
filter_dilation=filter_dilation,
num_groups=num_channels)
if input_shape is None or depthwise_filter_shape is None:
depthwise_op_shape = None
else:
depthwise_op_shape = conv_op.infer_shape(None, [input_shape, depthwise_filter_shape])[0]
depthwise_op = conv_op(input, depthwise_filters)
pointwise_op = conv2d(input=depthwise_op,
filters=pointwise_filters,
input_shape=depthwise_op_shape,
filter_shape=pointwise_filter_shape,
border_mode='valid',
subsample=(1, 1),
filter_flip=filter_flip,
filter_dilation=(1, 1),
num_groups=1)
return pointwise_op
def separable_conv3d(input,
depthwise_filters,
pointwise_filters,
num_channels,
input_shape=None,
depthwise_filter_shape=None,
pointwise_filter_shape=None,
border_mode='valid',
subsample=(1, 1, 1),
filter_flip=True,
filter_dilation=(1, 1, 1)):
"""
This function will build the symbolic graph for depthwise
convolutions which act separately on the input channels followed by
pointwise convolution which mixes channels.
Parameters
----------
input: symbolic 5D tensor
Mini-batch of feature map stacks, of shape
(batch size, input channels, input depth, input rows, input columns).
See the optional parameter ``input_shape``.
depthwise_filters: symbolic 5D tensor
Set of filters used depthwise convolution layer of shape
(depthwise output channels, 1, filter_depth, filter rows, filter columns).
pointwise_filters: symbolic 5D tensor
Set of filters used pointwise convolution layer of shape
(output channels, depthwise output channels, 1, 1, 1).
num_channels: int
The number of channels of the input. Required for depthwise
convolutions.
input_shape: None, tuple/list of len 5 of int or Constant variable
The shape of the input parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
depthwise_filter_shape: None, tuple/list of len 5 of int or Constant variable
The shape of the depthwise filters parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
pointwise_filter_shape: None, tuple/list of len 5 of int or Constant variable
The shape of the pointwise filters parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
border_mode: str, int or tuple of three int
This applies only to depthwise convolutions
Either of the following:
``'valid'``: apply filter wherever it completely overlaps with the
input. Generates output of shape: input shape - filter shape + 1
``'full'``: apply filter wherever it partly overlaps with the input.
Generates output of shape: input shape + filter shape - 1
``'half'``: pad input with a symmetric border of ``filter // 2``,
then perform a valid convolution. For filters with an odd
number of slices, rows and columns, this leads to the output
shape being equal to the input shape.
``int``: pad input with a symmetric border of zeros of the given
width, then perform a valid convolution.
``(int1, int2, int3)``
pad input with a symmetric border of ``int1``, ``int2`` and
``int3`` columns, then perform a valid convolution.
subsample: tuple of len 3
This applies only to depthwise convolutions
Factor by which to subsample the output.
Also called strides elsewhere.
filter_flip: bool
If ``True``, will flip the filter x, y and z dimensions before
sliding them over the input. This operation is normally
referred to as a convolution, and this is the default. If
``False``, the filters are not flipped and the operation is
referred to as a cross-correlation.
filter_dilation: tuple of len 3
Factor by which to subsample (stride) the input.
Also called dilation elsewhere.
Returns
-------
Symbolic 5D tensor
Set of feature maps generated by convolutional layer. Tensor is
of shape (batch size, output channels, output_depth,
output rows, output columns)
"""
input = as_tensor_variable(input)
depthwise_filters = as_tensor_variable(depthwise_filters)
conv_op = AbstractConv3d(imshp=input_shape,
kshp=depthwise_filter_shape,
border_mode=border_mode,
subsample=subsample,
filter_flip=filter_flip,
filter_dilation=filter_dilation,
num_groups=num_channels)
if input_shape is None or depthwise_filter_shape is None:
depthwise_op_shape = None
else:
depthwise_op_shape = conv_op.infer_shape(None, [input_shape, depthwise_filter_shape])[0]
depthwise_op = conv_op(input, depthwise_filters)
pointwise_op = conv3d(input=depthwise_op,
filters=pointwise_filters,
input_shape=depthwise_op_shape,
filter_shape=pointwise_filter_shape,
border_mode='valid',
subsample=(1, 1, 1),
filter_flip=filter_flip,
filter_dilation=(1, 1, 1),
num_groups=1)
return pointwise_op
def conv3d(input,
filters,
input_shape=None,
filter_shape=None,
border_mode='valid',
subsample=(1, 1, 1),
filter_flip=True,
filter_dilation=(1, 1, 1),
num_groups=1):
"""
This function will build the symbolic graph for convolving a mini-batch of a
stack of 3D inputs with a set of 3D filters. The implementation is modelled
after Convolutional Neural Networks (CNN).
Parameters
----------
input: symbolic 5D tensor
Mini-batch of feature map stacks, of shape
(batch size, input channels, input depth, input rows, input columns).
See the optional parameter ``input_shape``.
filters: symbolic 5D tensor
Set of filters used in CNN layer of shape
(output channels, input channels, filter depth, filter rows, filter columns).
See the optional parameter ``filter_shape``.
input_shape: None, tuple/list of len 5 of int or Constant variable
The shape of the input parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
filter_shape: None, tuple/list of len 5 of int or Constant variable
The shape of the filters parameter.
Optional, possibly used to choose an optimal implementation.
You can give ``None`` for any element of the list to specify that this
element is not known at compile time.
border_mode: str, int or tuple of three int
Either of the following:
``'valid'``: apply filter wherever it completely overlaps with the
input. Generates output of shape: input shape - filter shape + 1
``'full'``: apply filter wherever it partly overlaps with the input.
Generates output of shape: input shape + filter shape - 1
``'half'``: pad input with a symmetric border of ``filter // 2``,
then perform a valid convolution. For filters with an odd
number of slices, rows and columns, this leads to the output
shape being equal to the input shape.
``int``: pad input with a symmetric border of zeros of the given
width, then perform a valid convolution.
``(int1, int2, int3)``
pad input with a symmetric border of ``int1``, ``int2`` and
``int3`` columns, then perform a valid convolution.
subsample: tuple of len 3
Factor by which to subsample the output.
Also called strides elsewhere.
filter_flip: bool
If ``True``, will flip the filter x, y and z dimensions before
sliding them over the input. This operation is normally
referred to as a convolution, and this is the default. If
``False``, the filters are not flipped and the operation is
referred to as a cross-correlation.
filter_dilation: tuple of len 3
Factor by which to subsample (stride) the input.
Also called dilation elsewhere.
num_groups : int
Divides the image, kernel and output tensors into num_groups
separate groups. Each which carry out convolutions separately
Returns
-------
Symbolic 5D tensor
Set of feature maps generated by convolutional layer. Tensor is
is of shape (batch size, output channels, output depth,
output rows, output columns)
Notes
-----
If cuDNN is available, it will be used on the
GPU. Otherwise, it is the *Corr3dMM* convolution that will be used
"caffe style convolution".
This is only supported in Theano 0.8 or the development
version until it is released.
"""
input = as_tensor_variable(input)
filters = as_tensor_variable(filters)
conv_op = AbstractConv3d(imshp=input_shape,
kshp=filter_shape,
border_mode=border_mode,
subsample=subsample,
filter_flip=filter_flip,
filter_dilation=filter_dilation,
num_groups=num_groups)