/
topology.py
2938 lines (2648 loc) · 124 KB
/
topology.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 -*-
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
import types as python_types
import warnings
import copy
import os
import inspect
from six.moves import zip
from .. import backend as K
from .. import initializations
from ..utils.io_utils import ask_to_proceed_with_overwrite
from ..utils.generic_utils import func_dump, func_load
def to_list(x):
'''This normalizes a list/tensor into a list.
If a tensor is passed, we return
a list of size 1 containing the tensor.
'''
if isinstance(x, list):
return x
return [x]
def object_list_uid(object_list):
object_list = to_list(object_list)
return ', '.join([str(abs(id(x))) for x in object_list])
class InputSpec(object):
'''This specifies the ndim, dtype and shape of every input to a layer.
Every layer should expose (if appropriate) an `input_spec` attribute:
a list of instances of InputSpec (one per input tensor).
A None entry in a shape is compatible with any dimension,
a None shape is compatible with any shape.
'''
def __init__(self, dtype=None, shape=None, ndim=None):
if isinstance(ndim, str):
if '+' not in ndim:
raise ValueError('When passing a str "ndim", '
'it should have the form "2+", "3+", etc.')
int_ndim = ndim[:ndim.find('+')]
if not int_ndim.isdigit():
raise ValueError('When passing a str "ndim", '
'it should have the form "2+", "3+", etc.')
if shape is not None:
self.ndim = len(shape)
else:
self.ndim = ndim
self.dtype = dtype
self.shape = shape
class Node(object):
'''A `Node` describes the connectivity between two layers.
Each time a layer is connected to some new input,
a node is added to `layer.inbound_nodes`.
Each time the output of a layer is used by another layer,
a node is added to `layer.outbound_nodes`.
# Attributes
outbound_layer: the layer that takes
`input_tensors` and turns them into `output_tensors`.
inbound_layers: a list of layers, the same length as `input_tensors`,
the layers from where `input_tensors` originate.
node_indices: a list of integers, the same length as `inbound_layers`.
`node_indices[i]` is the origin node of `input_tensors[i]`
(necessary since each inbound layer might have several nodes,
e.g. if the layer is being shared with a different data stream).
tensor_indices: a list of integers,
the same length as `inbound_layers`.
`tensor_indices[i]` is the index of `input_tensors[i]` within the
output of the inbound layer
(necessary since each inbound layer might
have multiple tensor outputs, with each one being
independently manipulable).
input_tensors: list of input tensors.
output_tensors: list of output tensors.
input_masks: list of input masks (a mask can be a tensor, or None).
output_masks: list of output masks (a mask can be a tensor, or None).
input_shapes: list of input shape tuples.
output_shapes: list of output shape tuples.
`node_indices` and `tensor_indices` are basically fine-grained coordinates
describing the origin of the `input_tensors`, verifying the following:
`input_tensors[i] == inbound_layers[i].inbound_nodes[node_indices[i]].output_tensors[tensor_indices[i]]`
A node from layer A to layer B is added to:
A.outbound_nodes
B.inbound_nodes
'''
def __init__(self, outbound_layer,
inbound_layers, node_indices, tensor_indices,
input_tensors, output_tensors,
input_masks, output_masks,
input_shapes, output_shapes):
# Layer instance (NOT a list).
# this is the layer that takes a list of input tensors
# and turns them into a list of output tensors.
# the current node will be added to
# the inbound_nodes of outbound_layer.
self.outbound_layer = outbound_layer
# The following 3 properties describe where
# the input tensors come from: which layers,
# and for each layer, which node and which
# tensor output of each node.
self.inbound_layers = inbound_layers # List of layer instances
self.node_indices = node_indices # List of integers, 1:1 mapping with inbound_layers.
self.tensor_indices = tensor_indices # List of integers, 1:1 mapping with inbound_layers.
# Tensor inputs and outputs of outbound_layer.
self.input_tensors = input_tensors # List of tensors. 1:1 mapping with inbound_layers.
self.output_tensors = output_tensors # List of tensors, created by outbound_layer.call().
# input and output masks
self.input_masks = input_masks # List of tensors, 1:1 mapping with input_tensor.
self.output_masks = output_masks # List of tensors, created by outbound_layer.compute_mask().
# input and output shapes
self.input_shapes = input_shapes # List of shape tuples, shapes of input_tensors.
self.output_shapes = output_shapes # List of shape tuples, shapes of output_tensors.
# Add nodes to all layers involved.
for layer in inbound_layers:
if layer is not None:
layer.outbound_nodes.append(self)
outbound_layer.inbound_nodes.append(self)
@classmethod
def create_node(cls, outbound_layer,
inbound_layers, node_indices=None, tensor_indices=None):
if not node_indices:
node_indices = [0 for _ in range(len(inbound_layers))]
else:
assert len(node_indices) == len(inbound_layers)
if not tensor_indices:
tensor_indices = [0 for _ in range(len(inbound_layers))]
input_tensors = []
input_masks = []
input_shapes = []
for inbound_layer, node_index, tensor_index in zip(inbound_layers, node_indices, tensor_indices):
inbound_node = inbound_layer.inbound_nodes[node_index]
input_tensors.append(inbound_node.output_tensors[tensor_index])
input_masks.append(inbound_node.output_masks[tensor_index])
input_shapes.append(inbound_node.output_shapes[tensor_index])
assert len(input_shapes) == len(input_tensors) == len(input_masks)
if len(input_tensors) == 1:
output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
output_masks = to_list(outbound_layer.compute_mask(input_tensors[0], input_masks[0]))
# TODO: try to auto-infer shape
# if exception is raised by get_output_shape_for.
output_shapes = to_list(outbound_layer.get_output_shape_for(input_shapes[0]))
else:
output_tensors = to_list(outbound_layer.call(input_tensors, mask=input_masks))
output_masks = to_list(outbound_layer.compute_mask(input_tensors, input_masks))
output_shapes = to_list(outbound_layer.get_output_shape_for(input_shapes))
if not output_tensors or output_tensors[0] is None:
raise TypeError('The `call` method of layer "' +
outbound_layer.name +
'" should return a tensor. Found: ' +
str(output_tensors[0]))
if len(output_tensors) != len(output_shapes):
raise ValueError('The `get_output_shape_for` method of layer "' +
outbound_layer.name +
'"" should return one shape tuple per '
'output tensor of the layer. Found: ' +
str(output_shapes))
if len(output_tensors) != len(output_masks):
raise ValueError('The `compute_mask` method of layer "' +
outbound_layer.name +
'" should return one mask tensor per '
'output tensor of the layer. Found: ' +
str(output_masks))
for i in range(len(output_tensors)):
output_tensors[i]._keras_shape = output_shapes[i]
output_tensors[i]._uses_learning_phase = any([x._uses_learning_phase for x in input_tensors]) or outbound_layer.uses_learning_phase
output_tensors[i]._keras_history = (outbound_layer, len(outbound_layer.inbound_nodes), i)
return cls(outbound_layer,
inbound_layers, node_indices, tensor_indices,
input_tensors, output_tensors,
input_masks, output_masks,
input_shapes, output_shapes)
def get_config(self):
inbound_names = []
for layer in self.inbound_layers:
if layer:
inbound_names.append(layer.name)
else:
inbound_names.append(None)
return {'outbound_layer': self.outbound_layer.name if self.outbound_layer else None,
'inbound_layers': inbound_names,
'node_indices': self.node_indices,
'tensor_indices': self.tensor_indices}
class Layer(object):
'''Abstract base layer class.
# Properties
name: String, must be unique within a model.
input_spec: List of InputSpec class instances
each entry describes one required input:
- ndim
- dtype
A layer with `n` input tensors must have
an `input_spec` of length `n`.
trainable: Boolean, whether the layer weights
will be updated during training.
uses_learning_phase: Whether any operation
of the layer uses `K.in_training_phase()`
or `K.in_test_phase()`.
input_shape: Shape tuple. Provided for convenience,
but note that there may be cases in which this
attribute is ill-defined (e.g. a shared layer
with multiple input shapes), in which case
requesting `input_shape` will raise an Exception.
Prefer using `layer.get_input_shape_for(input_shape)`,
or `layer.get_input_shape_at(node_index)`.
output_shape: Shape tuple. See above.
inbound_nodes: List of nodes.
outbound_nodes: List of nodes.
supports_masking: Boolean.
input, output: Input/output tensor(s). Note that if the layer is used
more than once (shared layer), this is ill-defined
and will raise an exception. In such cases, use
`layer.get_input_at(node_index)`.
input_mask, output_mask: Same as above, for masks.
trainable_weights: List of variables.
non_trainable_weights: List of variables.
weights: The concatenation of the lists trainable_weights and
non_trainable_weights (in this order).
constraints: Dict mapping weights to constraints.
# Methods
call(x, mask=None): Where the layer's logic lives.
__call__(x, mask=None): Wrapper around the layer logic (`call`).
If x is a Keras tensor:
- Connect current layer with last layer from tensor:
`self.add_inbound_node(last_layer)`
- Add layer to tensor history
If layer is not built:
- Build from x._keras_shape
get_weights()
set_weights(weights)
get_config()
count_params()
get_output_shape_for(input_shape)
compute_mask(x, mask)
get_input_at(node_index)
get_output_at(node_index)
get_input_shape_at(node_index)
get_output_shape_at(node_index)
get_input_mask_at(node_index)
get_output_mask_at(node_index)
# Class Methods
from_config(config)
# Internal methods:
build(input_shape)
add_inbound_node(layer, index=0)
create_input_layer()
assert_input_compatibility()
'''
def __init__(self, **kwargs):
# These properties should have been set
# by the child class, as appropriate.
if not hasattr(self, 'input_spec'):
self.input_spec = None
if not hasattr(self, 'supports_masking'):
self.supports_masking = False
if not hasattr(self, 'uses_learning_phase'):
self.uses_learning_phase = False
# These lists will be filled via successive calls
# to self.add_inbound_node().
self.inbound_nodes = []
self.outbound_nodes = []
# These properties will be set upon call of self.build(),
# which itself will be called upon self.add_inbound_node if necessary.
if not hasattr(self, '_trainable_weights'):
self._trainable_weights = []
if not hasattr(self, '_non_trainable_weights'):
self._non_trainable_weights = []
if not hasattr(self, 'losses'):
self.losses = []
if not hasattr(self, 'constraints'):
self.constraints = {} # dict {tensor: constraint instance}
self.built = False
# These properties should be set by the user via keyword arguments.
# note that 'input_dtype', 'input_shape' and 'batch_input_shape'
# are only applicable to input layers: do not pass these keywords
# to non-input layers.
allowed_kwargs = {'input_shape',
'batch_input_shape',
'input_dtype',
'name',
'trainable'}
for kwarg in kwargs.keys():
if kwarg not in allowed_kwargs:
raise TypeError('Keyword argument not understood:', kwarg)
name = kwargs.get('name')
if not name:
prefix = self.__class__.__name__.lower()
name = prefix + '_' + str(K.get_uid(prefix))
self.name = name
self.trainable = kwargs.get('trainable', True)
if 'batch_input_shape' in kwargs or 'input_shape' in kwargs:
# In this case we will create an input layer
# to insert before the current layer
if 'batch_input_shape' in kwargs:
batch_input_shape = tuple(kwargs['batch_input_shape'])
elif 'input_shape' in kwargs:
batch_input_shape = (None,) + tuple(kwargs['input_shape'])
self.batch_input_shape = batch_input_shape
input_dtype = kwargs.get('input_dtype', K.floatx())
self.input_dtype = input_dtype
@property
def trainable_weights(self):
trainable = getattr(self, 'trainable', True)
if trainable:
return self._trainable_weights
else:
return []
@trainable_weights.setter
def trainable_weights(self, weights):
self._trainable_weights = weights
@property
def non_trainable_weights(self):
trainable = getattr(self, 'trainable', True)
if not trainable:
return self._trainable_weights + self._non_trainable_weights
else:
return self._non_trainable_weights
@non_trainable_weights.setter
def non_trainable_weights(self, weights):
self._non_trainable_weights = weights
@property
def regularizers(self):
warnings.warn('The `regularizers` property of '
'layers/models is deprecated. '
'Regularization losses are now managed via the `losses` '
'layer/model property.')
return []
@regularizers.setter
def regularizers(self, _):
warnings.warn('The `regularizers` property of layers/models '
'is deprecated. '
'Regularization losses are now managed via the `losses` '
'layer/model property.')
def create_input_layer(self, batch_input_shape,
input_dtype=None, name=None):
if not name:
prefix = self.__class__.__name__.lower() + '_input_'
name = prefix + str(K.get_uid(prefix))
if not input_dtype:
input_dtype = K.floatx()
self.batch_input_shape = batch_input_shape
self.input_dtype = input_dtype
# Instantiate the input layer.
x = Input(batch_shape=batch_input_shape,
dtype=input_dtype, name=name)
# This will build the current layer
# and create the node connecting the current layer
# to the input layer we just created.
self(x)
def add_weight(self, shape, initializer, name=None,
trainable=True,
regularizer=None,
constraint=None):
'''Adds a weight variable to the layer.
# Arguments:
shape: The shape tuple of the weight.
initializer: An Initializer instance (callable).
trainable: A boolean, whether the weight should
be trained via backprop or not (assuming
that the layer itself is also trainable).
regularizer: An optional Regularizer instance.
'''
initializer = initializations.get(initializer)
weight = initializer(shape, name=name)
if regularizer is not None:
self.add_loss(regularizer(weight))
if constraint is not None:
self.constraints[weight] = constraint
if trainable:
self._trainable_weights.append(weight)
else:
self._non_trainable_weights.append(weight)
return weight
def assert_input_compatibility(self, input):
'''This checks that the tensor(s) `input`
verify the input assumptions of the layer
(if any). If not, exceptions are raised.
'''
if not self.input_spec:
return True
if not isinstance(self.input_spec, list):
raise TypeError('input_spec must be a list of '
'InputSpec instances. Found: ' +
str(self.input_spec))
inputs = to_list(input)
if len(self.input_spec) > 1:
if len(inputs) != len(self.input_spec):
raise ValueError('Layer ' + self.name + ' expects ' +
str(len(self.input_spec)) + ' inputs, '
'but it received ' + str(len(inputs)) +
' input tensors. Input received: ' +
str(input))
for input_index, (x, spec) in enumerate(zip(inputs, self.input_spec)):
if spec is None:
continue
# Check ndim.
if spec.ndim is not None:
if isinstance(spec.ndim, str):
int_ndim = spec.ndim[:spec.ndim.find('+')]
ndim = int(int_ndim)
if K.ndim(x) < ndim:
raise ValueError('Input ' + str(input_index) +
' is incompatible with layer ' +
self.name + ': expected ndim >= ' +
str(ndim) + ', found ndim=' +
str(K.ndim(x)))
else:
if K.ndim(x) != spec.ndim:
raise ValueError('Input ' + str(input_index) +
' is incompatible with layer ' +
self.name + ': expected ndim=' +
str(spec.ndim) + ', found ndim=' +
str(K.ndim(x)))
if spec.dtype is not None:
if K.dtype(x) != spec.dtype:
raise ValueError('Input ' + str(input_index) +
' is incompatible with layer ' +
self.name + ': expected dtype=' +
str(spec.dtype) + ', found dtype=' +
str(K.dtype(x)))
if spec.shape is not None:
if hasattr(x, '_keras_shape'):
x_shape = x._keras_shape
elif hasattr(K, 'int_shape'):
# Tensorflow shape inference.
x_shape = K.int_shape(x)
else:
continue
for spec_dim, dim in zip(spec.shape, x_shape):
if spec_dim is not None:
if spec_dim != dim:
raise ValueError(
'Input ' + str(input_index) +
' is incompatible with layer ' +
self.name + ': expected shape=' +
str(spec.shape) + ', found shape=' +
str(x_shape))
def call(self, x, mask=None):
'''This is where the layer's logic lives.
# Arguments
x: input tensor, or list/tuple of input tensors.
mask: a masking tensor (or list of tensors). Used mainly in RNNs.
# Returns:
A tensor or list/tuple of tensors.
'''
return x
def __call__(self, x, mask=None):
'''Wrapper around self.call(), for handling
internal Keras references.
If a Keras tensor is passed:
- We call self.add_inbound_node().
- If necessary, we `build` the layer to match
the _keras_shape of the input(s).
- We update the _keras_shape of every input tensor with
its new shape (obtained via self.get_output_shape_for).
This is done as part of add_inbound_node().
- We update the _keras_history of the output tensor(s)
with the current layer.
This is done as part of add_inbound_node().
# Arguments
x: Can be a tensor or list/tuple of tensors.
mask: Tensor or list/tuple of tensors.
'''
if not self.built:
# Raise exceptions in case the input is not compatible
# with the input_spec specified in the layer constructor.
self.assert_input_compatibility(x)
# Collect input shapes to build layer.
input_shapes = []
for x_elem in to_list(x):
if hasattr(x_elem, '_keras_shape'):
input_shapes.append(x_elem._keras_shape)
elif hasattr(K, 'int_shape'):
input_shapes.append(K.int_shape(x_elem))
else:
raise ValueError('You tried to call layer "' + self.name +
'". This layer has no information'
' about its expected input shape, '
'and thus cannot be built. '
'You can build it manually via: '
'`layer.build(batch_input_shape)`')
if len(input_shapes) == 1:
self.build(input_shapes[0])
else:
self.build(input_shapes)
self.built = True
# Raise exceptions in case the input is not compatible
# with the input_spec set at build time.
self.assert_input_compatibility(x)
input_tensors = to_list(x)
inbound_layers = []
node_indices = []
tensor_indices = []
for input_tensor in input_tensors:
if hasattr(input_tensor, '_keras_history') and input_tensor._keras_history:
# This is a Keras tensor.
previous_layer, node_index, tensor_index = input_tensor._keras_history
inbound_layers.append(previous_layer)
node_indices.append(node_index)
tensor_indices.append(tensor_index)
else:
inbound_layers = None
break
if inbound_layers:
# This will call layer.build() if necessary.
self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
# Outputs were already computed when calling self.add_inbound_node.
outputs = self.inbound_nodes[-1].output_tensors
else:
# This case appears if the input was not a Keras tensor.
outputs = to_list(self.call(x, mask))
# Apply activity regularizer if any:
if hasattr(self, 'activity_regularizer') and self.activity_regularizer is not None:
regularization_losses = [self.activity_regularizer(x) for x in outputs]
self.add_loss(regularization_losses, input_tensors)
# If single output tensor: return it,
# else return a list (at least 2 elements).
if len(outputs) == 1:
return outputs[0]
else:
return outputs
def add_inbound_node(self, inbound_layers,
node_indices=None, tensor_indices=None):
'''
# Arguments
inbound_layers: Can be a layer instance
or a list/tuple of layer instances.
node_indices: Integer (or list of integers).
The input layer might have a number of
parallel output streams;
this is the index of the stream (in the input layer)
where to connect the current layer.
tensor_indices: Integer or list of integers.
The output of the inbound node might be a list/tuple
of tensor, and we might only be interested in
one specific entry.
This index allows you to specify the index of
the entry in the output list
(if applicable). "None" means that we take all outputs
(as a list).
'''
inbound_layers = to_list(inbound_layers)
if not node_indices:
node_indices = [0 for _ in range(len(inbound_layers))]
else:
node_indices = to_list(node_indices)
assert len(node_indices) == len(inbound_layers)
if not tensor_indices:
tensor_indices = [0 for _ in range(len(inbound_layers))]
else:
tensor_indices = to_list(tensor_indices)
if not self.built:
# collect input_shapes for call to build()
input_shapes = []
for layer, node_index, tensor_index in zip(inbound_layers, node_indices, tensor_indices):
input_shapes.append(layer.inbound_nodes[node_index].output_shapes[tensor_index])
# call build()
if len(input_shapes) == 1:
self.build(input_shape=input_shapes[0])
else:
self.build(input_shape=input_shapes)
self.built = True
# creating the node automatically updates self.inbound_nodes
# as well as outbound_nodes on inbound layers.
Node.create_node(self, inbound_layers, node_indices, tensor_indices)
def get_output_shape_for(self, input_shape):
'''Computes the output shape of the layer given
an input shape (assumes that the layer will be built
to match that input shape).
# Arguments
input_shape: Shape tuple (tuple of integers)
or list of shape tuples (one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
'''
return input_shape
def compute_mask(self, input, input_mask=None):
'''Computes an output masking tensor, given an input tensor
(or list thereof) and an input mask (or list thereof).
# Arguments
input: Tensor or list of tensors.
input_mask: Tensor or list of tensors.
# Returns
None or a tensor (or list of tensors,
one per output tensor of the layer).
'''
if not hasattr(self, 'supports_masking') or not self.supports_masking:
if input_mask is not None:
if isinstance(input_mask, list):
if any(input_mask):
raise ValueError('Layer ' + self.name +
' does not support masking, '
'but was passed an input_mask: ' +
str(input_mask))
else:
raise ValueError('Layer ' + self.name +
' does not support masking, '
'but was passed an input_mask: ' +
str(input_mask))
# masking not explicitly supported: return None as mask
return None
# if masking is explictly supported, by default
# carry over the input mask
return input_mask
def build(self, input_shape):
'''Creates the layer weights.
Must be implemented on all layers that have weights.
# Arguments
input_shape: Keras tensor (future input to layer)
or list/tuple of Keras tensors to reference
for weight shape computations.
'''
self.built = True
def _get_node_attribute_at_index(self, node_index, attr, attr_name):
'''Retrieves an attribute (e.g. input_tensors) from a node.
# Arguments
node_index: Integer index of the node from which
to retrieve the attribute.
attr: Exact node attribute name.
attr_name: Human-readable attribute name, for error messages.
'''
if not self.inbound_nodes:
raise RuntimeError('The layer has never been called '
'and thus has no defined ' + attr_name + '.')
if not len(self.inbound_nodes) > node_index:
raise ValueError('Asked to get ' + attr_name +
' at node ' + str(node_index) +
', but the layer has only ' +
str(len(self.inbound_nodes)) + ' inbound nodes.')
values = getattr(self.inbound_nodes[node_index], attr)
if len(values) == 1:
return values[0]
else:
return values
def get_input_shape_at(self, node_index):
'''Retrieves the input shape(s) of a layer at a given node.
'''
return self._get_node_attribute_at_index(node_index,
'input_shapes',
'input shape')
def get_output_shape_at(self, node_index):
'''Retrieves the output shape(s) of a layer at a given node.
'''
return self._get_node_attribute_at_index(node_index,
'output_shapes',
'output shape')
def get_input_at(self, node_index):
'''Retrieves the input tensor(s) of a layer at a given node.
'''
return self._get_node_attribute_at_index(node_index,
'input_tensors',
'input')
def get_output_at(self, node_index):
'''Retrieves the output tensor(s) of a layer at a given node.
'''
return self._get_node_attribute_at_index(node_index,
'output_tensors',
'output')
def get_input_mask_at(self, node_index):
'''Retrieves the input mask tensor(s) of a layer at a given node.
'''
return self._get_node_attribute_at_index(node_index,
'input_masks',
'input mask')
def get_output_mask_at(self, node_index):
'''Retrieves the output mask tensor(s) of a layer at a given node.
'''
return self._get_node_attribute_at_index(node_index,
'output_masks',
'output mask')
@property
def input(self):
'''Retrieves the input tensor(s) of a layer (only applicable if
the layer has exactly one inbound node, i.e. if it is connected
to one incoming layer).
'''
if len(self.inbound_nodes) > 1:
raise AttributeError('Layer ' + self.name +
' has multiple inbound nodes, '
'hence the notion of "layer input" '
'is ill-defined. '
'Use `get_input_at(node_index)` instead.')
elif not self.inbound_nodes:
raise AttributeError('Layer ' + self.name +
' is not connected, no input to return.')
return self._get_node_attribute_at_index(0, 'input_tensors',
'input')
@property
def output(self):
'''Retrieves the output tensor(s) of a layer (only applicable if
the layer has exactly one inbound node, i.e. if it is connected
to one incoming layer).
'''
if len(self.inbound_nodes) == 0:
raise AttributeError('Layer ' + self.name +
' has no inbound nodes.')
if len(self.inbound_nodes) > 1:
raise AttributeError('Layer ' + self.name +
' has multiple inbound nodes, '
'hence the notion of "layer output" '
'is ill-defined. '
'Use `get_output_at(node_index)` instead.')
return self._get_node_attribute_at_index(0, 'output_tensors',
'output')
@property
def input_mask(self):
'''Retrieves the input mask tensor(s) of a layer (only applicable if
the layer has exactly one inbound node, i.e. if it is connected
to one incoming layer).
'''
if len(self.inbound_nodes) != 1:
raise AttributeError('Layer ' + self.name +
' has multiple inbound nodes, ' +
'hence the notion of "layer input mask" '
'is ill-defined. '
'Use `get_input_mask_at(node_index)` instead.')
return self._get_node_attribute_at_index(0, 'input_masks',
'input mask')
@property
def output_mask(self):
'''Retrieves the output mask tensor(s) of a layer (only applicable if
the layer has exactly one inbound node, i.e. if it is connected
to one incoming layer).
'''
if len(self.inbound_nodes) != 1:
raise AttributeError('Layer ' + self.name +
' has multiple inbound nodes, '
'hence the notion of "layer output mask" '
'is ill-defined. '
'Use `get_output_mask_at(node_index)` '
'instead.')
return self._get_node_attribute_at_index(0, 'output_masks',
'output mask')
@property
def input_shape(self):
'''Retrieves the input shape tuple(s) of a layer. Only applicable
if the layer has one inbound node,
or if all inbound nodes have the same input shape.
'''
if not self.inbound_nodes:
raise AttributeError('The layer has never been called '
'and thus has no defined input shape.')
all_input_shapes = set([str(node.input_shapes) for node in self.inbound_nodes])
if len(all_input_shapes) == 1:
input_shapes = self.inbound_nodes[0].input_shapes
if len(input_shapes) == 1:
return input_shapes[0]
else:
return input_shapes
else:
raise AttributeError('The layer "' + str(self.name) +
' has multiple inbound nodes, '
'with different input shapes. Hence '
'the notion of "input shape" is '
'ill-defined for the layer. '
'Use `get_input_shape_at(node_index)` '
'instead.')
@property
def output_shape(self):
'''Retrieves the output shape tuple(s) of a layer. Only applicable
if the layer has one inbound node,
or if all inbound nodes have the same output shape.
'''
if not self.inbound_nodes:
raise AttributeError('The layer has never been called '
'and thus has no defined output shape.')
all_output_shapes = set([str(node.output_shapes) for node in self.inbound_nodes])
if len(all_output_shapes) == 1:
output_shapes = self.inbound_nodes[0].output_shapes
if len(output_shapes) == 1:
return output_shapes[0]
else:
return output_shapes
else:
raise AttributeError('The layer "' + str(self.name) +
' has multiple inbound nodes, '
'with different output shapes. Hence '
'the notion of "output shape" is '
'ill-defined for the layer. '
'Use `get_output_shape_at(node_index)` '
'instead.')
def add_loss(self, losses, inputs=None):
if losses is None:
return
# Update self.losses
losses = to_list(losses)
if not hasattr(self, 'losses'):
self.losses = []
try:
self.losses += losses
except AttributeError:
# In case self.losses isn't settable
# (i.e. it's a getter method).
# In that case the `losses` property is
# auto-computed and shouldn't be set.
pass
# Update self._per_input_updates
if not hasattr(self, '_per_input_losses'):
self._per_input_losses = {}
if inputs is not None:
inputs_hash = object_list_uid(inputs)
else:
# Updates indexed by None are unconditional
# rather than input-dependent
inputs_hash = None
if inputs_hash not in self._per_input_losses:
self._per_input_losses[inputs_hash] = []
self._per_input_losses[inputs_hash] += losses
def add_update(self, updates, inputs=None):
if updates is None:
return
# Update self.updates
updates = to_list(updates)
if not hasattr(self, 'updates'):
self.updates = []
try:
self.updates += updates
except AttributeError:
# In case self.updates isn't settable
# (i.e. it's a getter method).
# In that case the `updates` property is
# auto-computed and shouldn't be set.
pass
# Update self._per_input_updates
if not hasattr(self, '_per_input_updates'):
self._per_input_updates = {}
if inputs is not None:
inputs_hash = object_list_uid(inputs)
else:
# Updates indexed by None are unconditional
# rather than input-dependent
inputs_hash = None
if inputs_hash not in self._per_input_updates:
self._per_input_updates[inputs_hash] = []
self._per_input_updates[inputs_hash] += updates
def get_updates_for(self, inputs):
if not hasattr(self, '_per_input_updates'):
return []
if inputs is not None:
inputs_hash = object_list_uid(inputs)
else:
inputs_hash = None
if inputs_hash in self._per_input_updates:
return self._per_input_updates[inputs_hash]
return []
def get_losses_for(self, inputs):
if not hasattr(self, '_per_input_losses'):
return []
if inputs is not None:
inputs_hash = object_list_uid(inputs)
else:
inputs_hash = None
if inputs_hash in self._per_input_losses:
return self._per_input_losses[inputs_hash]
return []
@property
def weights(self):
return self.trainable_weights + self.non_trainable_weights
def set_weights(self, weights):
'''Sets the weights of the layer, from Numpy arrays.
# Arguments
weights: a list of Numpy arrays. The number
of arrays and their shape must match
number of the dimensions of the weights
of the layer (i.e. it should match the
output of `get_weights`).
'''
params = self.weights
if len(params) != len(weights):
raise ValueError('You called `set_weights(weights)` on layer "' +
self.name +
'" with a weight list of length ' +
str(len(weights)) +
', but the layer was expecting ' +
str(len(params)) +
' weights. Provided weights: ' +
str(weights)[:50] + '...')
if not params:
return
weight_value_tuples = []
param_values = K.batch_get_value(params)
for pv, p, w in zip(param_values, params, weights):
if pv.shape != w.shape:
raise ValueError('Layer weight shape ' +
str(pv.shape) +
' not compatible with '
'provided weight shape ' + str(w.shape))
weight_value_tuples.append((p, w))
K.batch_set_value(weight_value_tuples)
def get_weights(self):
'''Returns the current weights of the layer,
as a list of numpy arrays.
'''
params = self.weights
return K.batch_get_value(params)
def get_config(self):
'''Returns a Python dictionary (serializable)
containing the configuration of a layer.
The same layer can be reinstantiated later
(without its trained weights) from this configuration.
The config of a layer does not include connectivity
information, nor the layer class name. These are handled