-
Notifications
You must be signed in to change notification settings - Fork 800
/
Copy pathlayers.py
1850 lines (1559 loc) · 75.1 KB
/
layers.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
# -*- coding: utf-8 -*-
import functools
import numpy as np
import math
import tensorflow as tf
from tensorflow.python.training import moving_averages
from collections import OrderedDict
from collections import deque
from itertools import chain
from inspect import getargspec
from difflib import get_close_matches
from warnings import warn
class G(object):
pass
G._n_layers = 0
def create_param(spec, shape, name, trainable=True, regularizable=True):
if not hasattr(spec, '__call__'):
assert isinstance(spec, (tf.Tensor, tf.Variable))
return spec
assert hasattr(spec, '__call__')
if regularizable:
# use the default regularizer
regularizer = None
else:
# do not regularize this variable
regularizer = lambda _: tf.constant(0.)
return tf.get_variable(
name=name, shape=shape, initializer=spec, trainable=trainable,
regularizer=regularizer, dtype=tf.float32
)
def as_tuple(x, N, t=None):
try:
X = tuple(x)
except TypeError:
X = (x,) * N
if (t is not None) and not all(isinstance(v, t) for v in X):
raise TypeError("expected a single value or an iterable "
"of {0}, got {1} instead".format(t.__name__, x))
if len(X) != N:
raise ValueError("expected a single value or an iterable "
"with length {0}, got {1} instead".format(N, x))
return X
def conv_output_length(input_length, filter_size, stride, pad=0):
"""Helper function to compute the output size of a convolution operation
This function computes the length along a single axis, which corresponds
to a 1D convolution. It can also be used for convolutions with higher
dimensionalities by using it individually for each axis.
Parameters
----------
input_length : int or None
The size of the input.
filter_size : int
The size of the filter.
stride : int
The stride of the convolution operation.
pad : int, 'full' or 'same' (default: 0)
By default, the convolution is only computed where the input and the
filter fully overlap (a valid convolution). When ``stride=1``, this
yields an output that is smaller than the input by ``filter_size - 1``.
The `pad` argument allows you to implicitly pad the input with zeros,
extending the output size.
A single integer results in symmetric zero-padding of the given size on
both borders.
``'full'`` pads with one less than the filter size on both sides. This
is equivalent to computing the convolution wherever the input and the
filter overlap by at least one position.
``'same'`` pads with half the filter size on both sides (one less on
the second side for an even filter size). When ``stride=1``, this
results in an output size equal to the input size.
Returns
-------
int or None
The output size corresponding to the given convolution parameters, or
``None`` if `input_size` is ``None``.
Raises
------
ValueError
When an invalid padding is specified, a `ValueError` is raised.
"""
if input_length is None:
return None
if pad == 'valid':
output_length = input_length - filter_size + 1
elif pad == 'full':
output_length = input_length + filter_size - 1
elif pad == 'same':
output_length = input_length
elif isinstance(pad, int):
output_length = input_length + 2 * pad - filter_size + 1
else:
raise ValueError('Invalid pad: {0}'.format(pad))
# This is the integer arithmetic equivalent to
# np.ceil(output_length / stride)
output_length = (output_length + stride - 1) // stride
return output_length
class Layer(object):
def __init__(self, incoming, name=None, variable_reuse=None, weight_normalization=False, **kwargs):
if isinstance(incoming, tuple):
self.input_shape = incoming
self.input_layer = None
else:
self.input_shape = incoming.output_shape
self.input_layer = incoming
self.params = OrderedDict()
self.weight_normalization = weight_normalization
if name is None:
name = "%s_%d" % (type(self).__name__, G._n_layers)
G._n_layers += 1
self.name = name
self.variable_reuse = variable_reuse
self.get_output_kwargs = []
if any(d is not None and d <= 0 for d in self.input_shape):
raise ValueError((
"Cannot create Layer with a non-positive input_shape "
"dimension. input_shape=%r, self.name=%r") % (
self.input_shape, self.name))
@property
def output_shape(self):
shape = self.get_output_shape_for(self.input_shape)
if any(isinstance(s, (tf.Variable, tf.Tensor)) for s in shape):
raise ValueError("%s returned a symbolic output shape from its "
"get_output_shape_for() method: %r. This is not "
"allowed; shapes must be tuples of integers for "
"fixed-size dimensions and Nones for variable "
"dimensions." % (self.__class__.__name__, shape))
return shape
def get_output_shape_for(self, input_shape):
raise NotImplementedError
def get_output_for(self, input, **kwargs):
raise NotImplementedError
def add_param_plain(self, spec, shape, name, **tags):
with tf.variable_scope(self.name, reuse=self.variable_reuse):
tags['trainable'] = tags.get('trainable', True)
tags['regularizable'] = tags.get('regularizable', True)
param = create_param(spec, shape, name, **tags)
self.params[param] = set(tag for tag, value in list(tags.items()) if value)
return param
def add_param(self, spec, shape, name, **kwargs):
param = self.add_param_plain(spec, shape, name, **kwargs)
if name is not None and name.startswith("W") and self.weight_normalization:
# Hacky: check if the parameter is a weight matrix. If so, apply weight normalization
if len(param.get_shape()) == 2:
v = param
g = self.add_param_plain(tf.ones_initializer(), (shape[1],), name=name + "_wn/g")
param = v * (tf.reshape(g, (1, -1)) / tf.sqrt(tf.reduce_sum(tf.square(v), 0, keep_dims=True)))
elif len(param.get_shape()) == 4:
v = param
g = self.add_param_plain(tf.ones_initializer(), (shape[3],), name=name + "_wn/g")
param = v * (tf.reshape(g, (1, 1, 1, -1)) / tf.sqrt(tf.reduce_sum(tf.square(v), [0, 1, 2],
keep_dims=True)))
else:
raise NotImplementedError
return param
def get_params(self, **tags):
result = list(self.params.keys())
only = set(tag for tag, value in list(tags.items()) if value)
if only:
# retain all parameters that have all of the tags in `only`
result = [param for param in result
if not (only - self.params[param])]
exclude = set(tag for tag, value in list(tags.items()) if not value)
if exclude:
# retain all parameters that have none of the tags in `exclude`
result = [param for param in result
if not (self.params[param] & exclude)]
return result
class InputLayer(Layer):
def __init__(self, shape, input_var=None, **kwargs):
super(InputLayer, self).__init__(shape, **kwargs)
self.shape = shape
if input_var is None:
if self.name is not None:
with tf.variable_scope(self.name):
input_var = tf.placeholder(tf.float32, shape=shape, name="input")
else:
input_var = tf.placeholder(tf.float32, shape=shape, name="input")
self.input_var = input_var
@Layer.output_shape.getter
def output_shape(self):
return self.shape
class MergeLayer(Layer):
def __init__(self, incomings, name=None, **kwargs):
self.input_shapes = [incoming if isinstance(incoming, tuple)
else incoming.output_shape
for incoming in incomings]
self.input_layers = [None if isinstance(incoming, tuple)
else incoming
for incoming in incomings]
self.name = name
self.params = OrderedDict()
self.get_output_kwargs = []
@Layer.output_shape.getter
def output_shape(self):
shape = self.get_output_shape_for(self.input_shapes)
if any(isinstance(s, (tf.Variable, tf.Tensor)) for s in shape):
raise ValueError("%s returned a symbolic output shape from its "
"get_output_shape_for() method: %r. This is not "
"allowed; shapes must be tuples of integers for "
"fixed-size dimensions and Nones for variable "
"dimensions." % (self.__class__.__name__, shape))
return shape
def get_output_shape_for(self, input_shapes):
raise NotImplementedError
def get_output_for(self, inputs, **kwargs):
raise NotImplementedError
class ConcatLayer(MergeLayer):
"""
Concatenates multiple inputs along the specified axis. Inputs should have
the same shape except for the dimension specified in axis, which can have
different sizes.
Parameters
-----------
incomings : a list of :class:`Layer` instances or tuples
The layers feeding into this layer, or expected input shapes
axis : int
Axis which inputs are joined over
"""
def __init__(self, incomings, axis=1, **kwargs):
super(ConcatLayer, self).__init__(incomings, **kwargs)
self.axis = axis
def get_output_shape_for(self, input_shapes):
# Infer the output shape by grabbing, for each axis, the first
# input size that is not `None` (if there is any)
output_shape = [next((s for s in sizes if s is not None), None)
for sizes in zip(*input_shapes)]
def match(shape1, shape2):
return (len(shape1) == len(shape2) and
all(i == self.axis or s1 is None or s2 is None or s1 == s2
for i, (s1, s2) in enumerate(zip(shape1, shape2))))
# Check for compatibility with inferred output shape
if not all(match(shape, output_shape) for shape in input_shapes):
raise ValueError("Mismatch: input shapes must be the same except "
"in the concatenation axis")
# Infer output shape on concatenation axis and return
sizes = [input_shape[self.axis] for input_shape in input_shapes]
concat_size = None if any(s is None for s in sizes) else sum(sizes)
output_shape[self.axis] = concat_size
return tuple(output_shape)
def get_output_for(self, inputs, **kwargs):
dtypes = [x.dtype.as_numpy_dtype for x in inputs]
if len(set(dtypes)) > 1:
# need to convert to common data type
common_dtype = np.core.numerictypes.find_common_type([], dtypes)
inputs = [tf.cast(x, common_dtype) for x in inputs]
return tf.concat(axis=self.axis, values=inputs)
concat = ConcatLayer # shortcut
class XavierUniformInitializer(object):
def __call__(self, shape, dtype=tf.float32, *args, **kwargs):
if len(shape) == 2:
n_inputs, n_outputs = shape
else:
receptive_field_size = np.prod(shape[:2])
n_inputs = shape[-2] * receptive_field_size
n_outputs = shape[-1] * receptive_field_size
init_range = math.sqrt(6.0 / (n_inputs + n_outputs))
return tf.random_uniform_initializer(-init_range, init_range, dtype=dtype)(shape)
class HeUniformInitializer(object):
def __call__(self, shape, dtype=tf.float32, *args, **kwargs):
if len(shape) == 2:
n_inputs, _ = shape
else:
receptive_field_size = np.prod(shape[:2])
n_inputs = shape[-2] * receptive_field_size
init_range = math.sqrt(1.0 / n_inputs)
return tf.random_uniform_initializer(-init_range, init_range, dtype=dtype)(shape)
def py_ortho_init(scale):
def _init(shape):
u, s, v = np.linalg.svd(np.random.uniform(size=shape))
return np.cast['float32'](u * scale)
return _init
class OrthogonalInitializer(object):
def __init__(self, scale=1.1):
self.scale = scale
def __call__(self, shape, dtype=tf.float32, *args, **kwargs):
result, = tf.py_func(py_ortho_init(self.scale), [shape], [tf.float32])
result.set_shape(shape)
return result
class ParamLayer(Layer):
def __init__(self, incoming, num_units, param=tf.zeros_initializer(),
trainable=True, **kwargs):
super(ParamLayer, self).__init__(incoming, **kwargs)
self.num_units = num_units
self.param = self.add_param(
param,
(num_units,),
name="param",
trainable=trainable
)
def get_output_shape_for(self, input_shape):
return input_shape[:-1] + (self.num_units,)
def get_output_for(self, input, **kwargs):
ndim = input.get_shape().ndims
reshaped_param = tf.reshape(self.param, (1,) * (ndim - 1) + (self.num_units,))
tile_arg = tf.concat(axis=0, values=[tf.shape(input)[:ndim - 1], [1]])
tiled = tf.tile(reshaped_param, tile_arg)
return tiled
class OpLayer(MergeLayer):
def __init__(self, incoming, op,
shape_op=lambda x: x, extras=None, **kwargs):
if extras is None:
extras = []
incomings = [incoming] + extras
super(OpLayer, self).__init__(incomings, **kwargs)
self.op = op
self.shape_op = shape_op
self.incomings = incomings
def get_output_shape_for(self, input_shapes):
return self.shape_op(*input_shapes)
def get_output_for(self, inputs, **kwargs):
return self.op(*inputs)
class DenseLayer(Layer):
def __init__(self, incoming, num_units, nonlinearity=None, W=XavierUniformInitializer(), b=tf.zeros_initializer(),
**kwargs):
super(DenseLayer, self).__init__(incoming, **kwargs)
self.nonlinearity = tf.identity if nonlinearity is None else nonlinearity
self.num_units = num_units
num_inputs = int(np.prod(self.input_shape[1:]))
self.W = self.add_param(W, (num_inputs, num_units), name="W")
if b is None:
self.b = None
else:
self.b = self.add_param(b, (num_units,), name="b", regularizable=False)
def get_output_shape_for(self, input_shape):
return (input_shape[0], self.num_units)
def get_output_for(self, input, **kwargs):
if input.get_shape().ndims > 2:
# if the input has more than two dimensions, flatten it into a
# batch of feature vectors.
input = tf.reshape(input, tf.stack([tf.shape(input)[0], -1]))
activation = tf.matmul(input, self.W)
if self.b is not None:
activation = activation + tf.expand_dims(self.b, 0)
return self.nonlinearity(activation)
class BaseConvLayer(Layer):
def __init__(self, incoming, num_filters, filter_size, stride=1, pad="VALID",
untie_biases=False,
W=XavierUniformInitializer(), b=tf.zeros_initializer(),
nonlinearity=tf.nn.relu, n=None, **kwargs):
"""
Input is assumed to be of shape batch*height*width*channels
"""
super(BaseConvLayer, self).__init__(incoming, **kwargs)
if nonlinearity is None:
self.nonlinearity = tf.identity
else:
self.nonlinearity = nonlinearity
if n is None:
n = len(self.input_shape) - 2
elif n != len(self.input_shape) - 2:
raise ValueError("Tried to create a %dD convolution layer with "
"input shape %r. Expected %d input dimensions "
"(batchsize, channels, %d spatial dimensions)." %
(n, self.input_shape, n + 2, n))
self.n = n
self.num_filters = num_filters
self.filter_size = as_tuple(filter_size, n, int)
self.stride = as_tuple(stride, n, int)
self.untie_biases = untie_biases
self.pad = pad
if pad == 'SAME':
if any(s % 2 == 0 for s in self.filter_size):
raise NotImplementedError(
'`same` padding requires odd filter size.')
self.W = self.add_param(W, self.get_W_shape(), name="W")
if b is None:
self.b = None
else:
if self.untie_biases:
biases_shape = self.output_shape[1:3] + (num_filters,) # + self.output_shape[2:]
else:
biases_shape = (num_filters,)
self.b = self.add_param(b, biases_shape, name="b",
regularizable=False)
def get_W_shape(self):
"""Get the shape of the weight matrix `W`.
Returns
-------
tuple of int
The shape of the weight matrix.
"""
num_input_channels = self.input_shape[-1]
return self.filter_size + (num_input_channels, self.num_filters)
def get_output_shape_for(self, input_shape):
if self.pad == 'SAME':
pad = ('same',) * self.n
elif self.pad == 'VALID':
pad = (0,) * self.n
else:
import ipdb;
ipdb.set_trace()
raise NotImplementedError
# pad = self.pad if isinstance(self.pad, tuple) else (self.pad,) * self.n
batchsize = input_shape[0]
return ((batchsize,) +
tuple(conv_output_length(input, filter, stride, p)
for input, filter, stride, p
in zip(input_shape[1:3], self.filter_size,
self.stride, pad))) + (self.num_filters,)
def get_output_for(self, input, **kwargs):
conved = self.convolve(input, **kwargs)
if self.b is None:
activation = conved
elif self.untie_biases:
# raise NotImplementedError
activation = conved + tf.expand_dims(self.b, 0)
else:
activation = conved + tf.reshape(self.b, (1, 1, 1, self.num_filters))
return self.nonlinearity(activation)
def convolve(self, input, **kwargs):
"""
Symbolically convolves `input` with ``self.W``, producing an output of
shape ``self.output_shape``. To be implemented by subclasses.
Parameters
----------
input : Theano tensor
The input minibatch to convolve
**kwargs
Any additional keyword arguments from :meth:`get_output_for`
Returns
-------
Theano tensor
`input` convolved according to the configuration of this layer,
without any bias or nonlinearity applied.
"""
raise NotImplementedError("BaseConvLayer does not implement the "
"convolve() method. You will want to "
"use a subclass such as Conv2DLayer.")
class Conv2DLayer(BaseConvLayer):
def __init__(self, incoming, num_filters, filter_size, stride=(1, 1),
pad="VALID", untie_biases=False,
W=XavierUniformInitializer(), b=tf.zeros_initializer(),
nonlinearity=tf.nn.relu,
convolution=tf.nn.conv2d, **kwargs):
super(Conv2DLayer, self).__init__(incoming=incoming, num_filters=num_filters, filter_size=filter_size,
stride=stride, pad=pad, untie_biases=untie_biases, W=W, b=b,
nonlinearity=nonlinearity, n=2, **kwargs)
self.convolution = convolution
def convolve(self, input, **kwargs):
conved = self.convolution(input, self.W, strides=(1,) + self.stride + (1,), padding=self.pad)
return conved
def pool_output_length(input_length, pool_size, stride, pad):
if input_length is None or pool_size is None:
return None
if pad == "SAME":
return int(np.ceil(float(input_length) / float(stride)))
return int(np.ceil(float(input_length - pool_size + 1) / float(stride)))
class Pool2DLayer(Layer):
def __init__(self, incoming, pool_size, stride=None, pad="VALID", mode='max', **kwargs):
super(Pool2DLayer, self).__init__(incoming, **kwargs)
self.pool_size = as_tuple(pool_size, 2)
if len(self.input_shape) != 4:
raise ValueError("Tried to create a 2D pooling layer with "
"input shape %r. Expected 4 input dimensions "
"(batchsize, 2 spatial dimensions, channels)."
% (self.input_shape,))
if stride is None:
self.stride = self.pool_size
else:
self.stride = as_tuple(stride, 2)
self.pad = pad
self.mode = mode
def get_output_shape_for(self, input_shape):
output_shape = list(input_shape) # copy / convert to mutable list
output_shape[1] = pool_output_length(input_shape[1],
pool_size=self.pool_size[0],
stride=self.stride[0],
pad=self.pad,
)
output_shape[2] = pool_output_length(input_shape[2],
pool_size=self.pool_size[1],
stride=self.stride[1],
pad=self.pad,
)
return tuple(output_shape)
def get_output_for(self, input, **kwargs):
assert self.mode == "max"
pooled = tf.nn.max_pool(
input,
ksize=(1,) + self.pool_size + (1,),
strides=(1,) + self.stride + (1,),
padding=self.pad,
)
return pooled
def spatial_expected_softmax(x, temp=1):
assert len(x.get_shape()) == 4
vals = []
for dim in [0, 1]:
dim_val = x.get_shape()[dim + 1].value
lin = tf.linspace(-1.0, 1.0, dim_val)
lin = tf.expand_dims(lin, 1 - dim)
lin = tf.expand_dims(lin, 0)
lin = tf.expand_dims(lin, 3)
m = tf.reduce_max(x, [1, 2], keep_dims=True)
e = tf.exp((x - m) / temp) + 1e-5
val = tf.reduce_sum(e * lin, [1, 2]) / (tf.reduce_sum(e, [1, 2]))
vals.append(tf.expand_dims(val, 2))
return tf.reshape(tf.concat(axis=2, values=vals), [-1, x.get_shape()[-1].value * 2])
class SpatialExpectedSoftmaxLayer(Layer):
"""
Computes the softmax across a spatial region, separately for each channel, followed by an expectation operation.
"""
def __init__(self, incoming, **kwargs):
super().__init__(incoming, **kwargs)
# self.temp = self.add_param(tf.ones_initializer, shape=(), name="temperature")
def get_output_shape_for(self, input_shape):
return (input_shape[0], input_shape[-1] * 2)
def get_output_for(self, input, **kwargs):
return spatial_expected_softmax(input)#, self.temp)
# max_ = tf.reduce_max(input, reduction_indices=[1, 2], keep_dims=True)
# exp = tf.exp(input - max_) + 1e-5
# vals = []
#
# for dim in [0, 1]:
# dim_val = input.get_shape()[dim + 1].value
# lin = tf.linspace(-1.0, 1.0, dim_val)
# lin = tf.expand_dims(lin, 1 - dim)
# lin = tf.expand_dims(lin, 0)
# lin = tf.expand_dims(lin, 3)
# m = tf.reduce_max(input, [1, 2], keep_dims=True)
# e = tf.exp(input - m) + 1e-5
# val = tf.reduce_sum(e * lin, [1, 2]) / (tf.reduce_sum(e, [1, 2]))
# vals.append(tf.expand_dims(val, 2))
#
# return tf.reshape(tf.concat(2, vals), [-1, input.get_shape()[-1].value * 2])
# import ipdb; ipdb.set_trace()
# input.get_shape()
# exp / tf.reduce_sum(exp, reduction_indices=[1, 2], keep_dims=True)
# import ipdb;
# ipdb.set_trace()
# spatial softmax?
# for dim in range(2):
# val = obs.get_shape()[dim + 1].value
# lin = tf.linspace(-1.0, 1.0, val)
# lin = tf.expand_dims(lin, 1 - dim)
# lin = tf.expand_dims(lin, 0)
# lin = tf.expand_dims(lin, 3)
# m = tf.reduce_max(e, [1, 2], keep_dims=True)
# e = tf.exp(e - m) + 1e-3
# val = tf.reduce_sum(e * lin, [1, 2]) / (tf.reduce_sum(e, [1, 2]))
class DropoutLayer(Layer):
def __init__(self, incoming, p=0.5, rescale=True, **kwargs):
super(DropoutLayer, self).__init__(incoming, **kwargs)
self.p = p
self.rescale = rescale
def get_output_for(self, input, deterministic=False, **kwargs):
"""
Parameters
----------
input : tensor
output from the previous layer
deterministic : bool
If true dropout and scaling is disabled, see notes
"""
if deterministic or self.p == 0:
return input
else:
# Using theano constant to prevent upcasting
# one = T.constant(1)
retain_prob = 1. - self.p
if self.rescale:
input /= retain_prob
# use nonsymbolic shape for dropout mask if possible
return tf.nn.dropout(input, keep_prob=retain_prob)
def get_output_shape_for(self, input_shape):
return input_shape
# TODO: add Conv3DLayer
class FlattenLayer(Layer):
"""
A layer that flattens its input. The leading ``outdim-1`` dimensions of
the output will have the same shape as the input. The remaining dimensions
are collapsed into the last dimension.
Parameters
----------
incoming : a :class:`Layer` instance or a tuple
The layer feeding into this layer, or the expected input shape.
outdim : int
The number of dimensions in the output.
See Also
--------
flatten : Shortcut
"""
def __init__(self, incoming, outdim=2, **kwargs):
super(FlattenLayer, self).__init__(incoming, **kwargs)
self.outdim = outdim
if outdim < 1:
raise ValueError('Dim must be >0, was %i', outdim)
def get_output_shape_for(self, input_shape):
to_flatten = input_shape[self.outdim - 1:]
if any(s is None for s in to_flatten):
flattened = None
else:
flattened = int(np.prod(to_flatten))
return input_shape[:self.outdim - 1] + (flattened,)
def get_output_for(self, input, **kwargs):
# total_entries = tf.reduce_prod(tf.shape(input))
pre_shape = tf.shape(input)[:self.outdim - 1]
to_flatten = tf.reduce_prod(tf.shape(input)[self.outdim - 1:])
return tf.reshape(input, tf.concat(axis=0, values=[pre_shape, tf.stack([to_flatten])]))
flatten = FlattenLayer # shortcut
class ReshapeLayer(Layer):
def __init__(self, incoming, shape, **kwargs):
super(ReshapeLayer, self).__init__(incoming, **kwargs)
shape = tuple(shape)
for s in shape:
if isinstance(s, int):
if s == 0 or s < - 1:
raise ValueError("`shape` integers must be positive or -1")
elif isinstance(s, list):
if len(s) != 1 or not isinstance(s[0], int) or s[0] < 0:
raise ValueError("`shape` input references must be "
"single-element lists of int >= 0")
elif isinstance(s, (tf.Tensor, tf.Variable)): # T.TensorVariable):
raise NotImplementedError
# if s.ndim != 0:
# raise ValueError(
# "A symbolic variable in a shape specification must be "
# "a scalar, but had %i dimensions" % s.ndim)
else:
raise ValueError("`shape` must be a tuple of int and/or [int]")
if sum(s == -1 for s in shape) > 1:
raise ValueError("`shape` cannot contain multiple -1")
self.shape = shape
# try computing the output shape once as a sanity check
self.get_output_shape_for(self.input_shape)
def get_output_shape_for(self, input_shape, **kwargs):
# Initialize output shape from shape specification
output_shape = list(self.shape)
# First, replace all `[i]` with the corresponding input dimension, and
# mask parts of the shapes thus becoming irrelevant for -1 inference
masked_input_shape = list(input_shape)
masked_output_shape = list(output_shape)
for dim, o in enumerate(output_shape):
if isinstance(o, list):
if o[0] >= len(input_shape):
raise ValueError("specification contains [%d], but input "
"shape has %d dimensions only" %
(o[0], len(input_shape)))
output_shape[dim] = input_shape[o[0]]
masked_output_shape[dim] = input_shape[o[0]]
if (input_shape[o[0]] is None) \
and (masked_input_shape[o[0]] is None):
# first time we copied this unknown input size: mask
# it, we have a 1:1 correspondence between out[dim] and
# in[o[0]] and can ignore it for -1 inference even if
# it is unknown.
masked_input_shape[o[0]] = 1
masked_output_shape[dim] = 1
# Secondly, replace all symbolic shapes with `None`, as we cannot
# infer their size here.
for dim, o in enumerate(output_shape):
if isinstance(o, (tf.Tensor, tf.Variable)): # T.TensorVariable):
raise NotImplementedError
# output_shape[dim] = None
# masked_output_shape[dim] = None
# From the shapes, compute the sizes of the input and output tensor
input_size = (None if any(x is None for x in masked_input_shape)
else np.prod(masked_input_shape))
output_size = (None if any(x is None for x in masked_output_shape)
else np.prod(masked_output_shape))
del masked_input_shape, masked_output_shape
# Finally, infer value for -1 if needed
if -1 in output_shape:
dim = output_shape.index(-1)
if (input_size is None) or (output_size is None):
output_shape[dim] = None
output_size = None
else:
output_size *= -1
output_shape[dim] = input_size // output_size
output_size *= output_shape[dim]
# Sanity check
if (input_size is not None) and (output_size is not None) \
and (input_size != output_size):
raise ValueError("%s cannot be reshaped to specification %s. "
"The total size mismatches." %
(input_shape, self.shape))
return tuple(output_shape)
def get_output_for(self, input, **kwargs):
# Replace all `[i]` with the corresponding input dimension
output_shape = list(self.shape)
for dim, o in enumerate(output_shape):
if isinstance(o, list):
output_shape[dim] = tf.shape(input)[o[0]]
# Everything else is handled by Theano
return tf.reshape(input, tf.stack(output_shape))
reshape = ReshapeLayer # shortcut
class SliceLayer(Layer):
def __init__(self, incoming, indices, axis=-1, **kwargs):
super(SliceLayer, self).__init__(incoming, **kwargs)
self.slice = indices
self.axis = axis
def get_output_shape_for(self, input_shape):
output_shape = list(input_shape)
if isinstance(self.slice, int):
del output_shape[self.axis]
elif input_shape[self.axis] is not None:
output_shape[self.axis] = len(
list(range(*self.slice.indices(input_shape[self.axis]))))
else:
output_shape[self.axis] = None
return tuple(output_shape)
def get_output_for(self, input, **kwargs):
axis = self.axis
ndims = input.get_shape().ndims
if axis < 0:
axis += ndims
if isinstance(self.slice, int) and self.slice < 0:
return tf.reverse(input, [self.axis + 1])[
(slice(None),) * axis + (-1 - self.slice,) + (slice(None),) * (ndims - axis - 1)
]
# import ipdb; ipdb.set_trace()
return input[(slice(None),) * axis + (self.slice,) + (slice(None),) * (ndims - axis - 1)]
class DimshuffleLayer(Layer):
def __init__(self, incoming, pattern, **kwargs):
super(DimshuffleLayer, self).__init__(incoming, **kwargs)
# Sanity check the pattern
used_dims = set()
for p in pattern:
if isinstance(p, int):
# Dimension p
if p in used_dims:
raise ValueError("pattern contains dimension {0} more "
"than once".format(p))
used_dims.add(p)
elif p == 'x':
# Broadcast
pass
else:
raise ValueError("pattern should only contain dimension"
"indices or 'x', not {0}".format(p))
self.pattern = pattern
# try computing the output shape once as a sanity check
self.get_output_shape_for(self.input_shape)
def get_output_shape_for(self, input_shape):
# Build output shape while keeping track of the dimensions that we are
# attempting to collapse, so we can ensure that they are broadcastable
output_shape = []
dims_used = [False] * len(input_shape)
for p in self.pattern:
if isinstance(p, int):
if p < 0 or p >= len(input_shape):
raise ValueError("pattern contains {0}, but input shape "
"has {1} dimensions "
"only".format(p, len(input_shape)))
# Dimension p
o = input_shape[p]
dims_used[p] = True
elif p == 'x':
# Broadcast; will be of size 1
o = 1
output_shape.append(o)
for i, (dim_size, used) in enumerate(zip(input_shape, dims_used)):
if not used and dim_size != 1 and dim_size is not None:
raise ValueError(
"pattern attempted to collapse dimension "
"{0} of size {1}; dimensions with size != 1/None are not"
"broadcastable and cannot be "
"collapsed".format(i, dim_size))
return tuple(output_shape)
def get_output_for(self, input, **kwargs):
return tf.transpose(input, self.pattern)
dimshuffle = DimshuffleLayer # shortcut
def apply_ln(layer):
def _normalize(x, prefix):
EPS = 1e-5
dim = x.get_shape()[-1].value
bias_name = prefix + "_ln/bias"
scale_name = prefix + "_ln/scale"
if bias_name not in layer.norm_params:
layer.norm_params[bias_name] = layer.add_param(
tf.zeros_initializer(), (dim,), name=bias_name, regularizable=False)
if scale_name not in layer.norm_params:
layer.norm_params[scale_name] = layer.add_param(
tf.ones_initializer(), (dim,), name=scale_name)
bias = layer.norm_params[bias_name]
scale = layer.norm_params[scale_name]
mean, var = tf.nn.moments(x, axes=[1], keep_dims=True)
x_normed = (x - mean) / tf.sqrt(var + EPS)
return x_normed * scale + bias
return _normalize
class GRULayer(Layer):
"""
A gated recurrent unit implements the following update mechanism:
Reset gate: r(t) = f_r(x(t) @ W_xr + h(t-1) @ W_hr + b_r)
Update gate: u(t) = f_u(x(t) @ W_xu + h(t-1) @ W_hu + b_u)
Cell gate: c(t) = f_c(x(t) @ W_xc + r(t) * (h(t-1) @ W_hc) + b_c)
New hidden state: h(t) = (1 - u(t)) * h(t-1) + u_t * c(t)
Note that the reset, update, and cell vectors must have the same dimension as the hidden state
"""
def __init__(self, incoming, num_units, hidden_nonlinearity,
gate_nonlinearity=tf.nn.sigmoid, W_x_init=XavierUniformInitializer(), W_h_init=OrthogonalInitializer(),
b_init=tf.zeros_initializer(), hidden_init=tf.zeros_initializer(), hidden_init_trainable=False,
layer_normalization=False, **kwargs):
if hidden_nonlinearity is None:
hidden_nonlinearity = tf.identity
if gate_nonlinearity is None:
gate_nonlinearity = tf.identity
super(GRULayer, self).__init__(incoming, **kwargs)
input_shape = self.input_shape[2:]
input_dim = np.prod(input_shape)
self.layer_normalization = layer_normalization
# Weights for the initial hidden state
self.h0 = self.add_param(hidden_init, (num_units,), name="h0", trainable=hidden_init_trainable,
regularizable=False)
# Weights for the reset gate
self.W_xr = self.add_param(W_x_init, (input_dim, num_units), name="W_xr")
self.W_hr = self.add_param(W_h_init, (num_units, num_units), name="W_hr")
self.b_r = self.add_param(b_init, (num_units,), name="b_r", regularizable=False)
# Weights for the update gate
self.W_xu = self.add_param(W_x_init, (input_dim, num_units), name="W_xu")
self.W_hu = self.add_param(W_h_init, (num_units, num_units), name="W_hu")
self.b_u = self.add_param(b_init, (num_units,), name="b_u", regularizable=False)
# Weights for the cell gate
self.W_xc = self.add_param(W_x_init, (input_dim, num_units), name="W_xc")
self.W_hc = self.add_param(W_h_init, (num_units, num_units), name="W_hc")
self.b_c = self.add_param(b_init, (num_units,), name="b_c", regularizable=False)
self.W_x_ruc = tf.concat(axis=1, values=[self.W_xr, self.W_xu, self.W_xc])
self.W_h_ruc = tf.concat(axis=1, values=[self.W_hr, self.W_hu, self.W_hc])
self.W_x_ru = tf.concat(axis=1, values=[self.W_xr, self.W_xu])
self.W_h_ru = tf.concat(axis=1, values=[self.W_hr, self.W_hu])
self.b_ruc = tf.concat(axis=0, values=[self.b_r, self.b_u, self.b_c])
self.gate_nonlinearity = gate_nonlinearity
self.num_units = num_units
self.nonlinearity = hidden_nonlinearity
self.norm_params = dict()
# pre-run the step method to initialize the normalization parameters
h_dummy = tf.placeholder(dtype=tf.float32, shape=(None, num_units), name="h_dummy")
x_dummy = tf.placeholder(dtype=tf.float32, shape=(None, input_dim), name="x_dummy")