keras 0.2.0__py2.7.egg

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. EGG-INFO/PKG-INFO +11 -0
  2. EGG-INFO/SOURCES.txt +51 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/requires.txt +6 -0
  5. EGG-INFO/top_level.txt +1 -0
  6. EGG-INFO/zip-safe +1 -0
  7. keras/__init__.py +15 -0
  8. keras/__init__.pyc +0 -0
  9. keras/activations.py +49 -0
  10. keras/activations.pyc +0 -0
  11. keras/backend/__init__.py +39 -0
  12. keras/backend/__init__.pyc +0 -0
  13. keras/backend/common.py +31 -0
  14. keras/backend/common.pyc +0 -0
  15. keras/backend/tensorflow_backend.py +602 -0
  16. keras/backend/tensorflow_backend.pyc +0 -0
  17. keras/backend/theano_backend.py +622 -0
  18. keras/backend/theano_backend.pyc +0 -0
  19. keras/callbacks.py +295 -0
  20. keras/callbacks.pyc +0 -0
  21. keras/constraints.py +45 -0
  22. keras/constraints.pyc +0 -0
  23. keras/datasets/__init__.py +0 -0
  24. keras/datasets/__init__.pyc +0 -0
  25. keras/datasets/cifar.py +22 -0
  26. keras/datasets/cifar.pyc +0 -0
  27. keras/datasets/cifar10.py +31 -0
  28. keras/datasets/cifar10.pyc +0 -0
  29. keras/datasets/cifar100.py +28 -0
  30. keras/datasets/cifar100.pyc +0 -0
  31. keras/datasets/data_utils.py +50 -0
  32. keras/datasets/data_utils.pyc +0 -0
  33. keras/datasets/imdb.py +66 -0
  34. keras/datasets/imdb.pyc +0 -0
  35. keras/datasets/mnist.py +23 -0
  36. keras/datasets/mnist.pyc +0 -0
  37. keras/datasets/reuters.py +148 -0
  38. keras/datasets/reuters.pyc +0 -0
  39. keras/initializations.py +86 -0
  40. keras/initializations.pyc +0 -0
  41. keras/layers/__init__.py +0 -0
  42. keras/layers/__init__.pyc +0 -0
  43. keras/layers/advanced_activations.py +156 -0
  44. keras/layers/advanced_activations.pyc +0 -0
  45. keras/layers/containers.py +405 -0
  46. keras/layers/containers.pyc +0 -0
  47. keras/layers/convolutional.py +505 -0
  48. keras/layers/convolutional.pyc +0 -0
  49. keras/layers/core.py +1428 -0
  50. keras/layers/core.pyc +0 -0
  51. keras/layers/embeddings.py +88 -0
  52. keras/layers/embeddings.pyc +0 -0
  53. keras/layers/noise.py +55 -0
  54. keras/layers/noise.pyc +0 -0
  55. keras/layers/normalization.py +123 -0
  56. keras/layers/normalization.pyc +0 -0
  57. keras/layers/ntm.py +326 -0
  58. keras/layers/ntm.pyc +0 -0
  59. keras/layers/recurrent.py +354 -0
  60. keras/layers/recurrent.pyc +0 -0
  61. keras/models.py +743 -0
  62. keras/models.pyc +0 -0
  63. keras/objectives.py +59 -0
  64. keras/objectives.pyc +0 -0
  65. keras/optimizers.py +229 -0
  66. keras/optimizers.pyc +0 -0
  67. keras/preprocessing/__init__.py +0 -0
  68. keras/preprocessing/__init__.pyc +0 -0
  69. keras/preprocessing/image.py +246 -0
  70. keras/preprocessing/image.pyc +0 -0
  71. keras/preprocessing/sequence.py +124 -0
  72. keras/preprocessing/sequence.pyc +0 -0
  73. keras/preprocessing/text.py +176 -0
  74. keras/preprocessing/text.pyc +0 -0
  75. keras/regularizers.py +86 -0
  76. keras/regularizers.pyc +0 -0
  77. keras/utils/__init__.py +0 -0
  78. keras/utils/__init__.pyc +0 -0
  79. keras/utils/generic_utils.py +133 -0
  80. keras/utils/generic_utils.pyc +0 -0
  81. keras/utils/io_utils.py +71 -0
  82. keras/utils/io_utils.pyc +0 -0
  83. keras/utils/layer_utils.py +93 -0
  84. keras/utils/layer_utils.pyc +0 -0
  85. keras/utils/np_utils.py +53 -0
  86. keras/utils/np_utils.pyc +0 -0
  87. keras/utils/test_utils.py +27 -0
  88. keras/utils/test_utils.pyc +0 -0
  89. keras/utils/theano_utils.py +44 -0
  90. keras/utils/theano_utils.pyc +0 -0
  91. keras/utils/visualize_util.py +41 -0
  92. keras/utils/visualize_util.pyc +0 -0
  93. keras/wrappers/__init__.py +0 -0
  94. keras/wrappers/__init__.pyc +0 -0
  95. keras/wrappers/scikit_learn.py +266 -0
  96. keras/wrappers/scikit_learn.pyc +0 -0
  97. tests/__init__.py +0 -0
  98. tests/__init__.pyc +0 -0
  99. tests/manual/__init__.py +0 -0
  100. tests/manual/__init__.pyc +0 -0
  101. tests/manual/check_autoencoder.py +134 -0
  102. tests/manual/check_autoencoder.pyc +0 -0
  103. tests/manual/check_callbacks.py +236 -0
  104. tests/manual/check_callbacks.pyc +0 -0
  105. tests/manual/check_constraints.py +100 -0
  106. tests/manual/check_constraints.pyc +0 -0
  107. tests/manual/check_masked_recurrent.py +130 -0
  108. tests/manual/check_masked_recurrent.pyc +0 -0
  109. tests/manual/check_model_utils.py +44 -0
  110. tests/manual/check_model_utils.pyc +0 -0
  111. tests/manual/check_save_weights.py +40 -0
  112. tests/manual/check_save_weights.pyc +0 -0
  113. tests/manual/check_wrappers.py +126 -0
  114. tests/manual/check_wrappers.pyc +0 -0
  115. tests/manual/check_yaml.py +101 -0
  116. tests/manual/check_yaml.pyc +0 -0
keras/layers/core.py ADDED
@@ -0,0 +1,1428 @@
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import absolute_import
3
+ from __future__ import division
4
+
5
+ import numpy as np
6
+
7
+ from collections import OrderedDict
8
+ import copy
9
+ from six.moves import zip
10
+
11
+ from .. import backend as K
12
+ from .. import activations, initializations, regularizers, constraints
13
+ from ..regularizers import ActivityRegularizer
14
+
15
+ import marshal
16
+ import types
17
+ import sys
18
+
19
+
20
+ class Layer(object):
21
+ def __init__(self, **kwargs):
22
+ for kwarg in kwargs:
23
+ assert kwarg in {'input_shape', 'trainable'}, "Keyword argument not understood: " + kwarg
24
+ if 'input_shape' in kwargs:
25
+ self.set_input_shape(kwargs['input_shape'])
26
+ if 'trainable' in kwargs:
27
+ self._trainable = kwargs['trainable']
28
+ if not hasattr(self, 'params'):
29
+ self.params = []
30
+
31
+ def set_previous(self, layer, connection_map={}):
32
+ assert self.nb_input == layer.nb_output == 1, "Cannot connect layers: input count and output count should be 1."
33
+ if hasattr(self, 'input_ndim'):
34
+ assert self.input_ndim == len(layer.output_shape), "Incompatible shapes: layer expected input with ndim=" +\
35
+ str(self.input_ndim) + " but previous layer has output_shape " + str(layer.output_shape)
36
+ if layer.get_output_mask() is not None:
37
+ assert self.supports_masked_input(), "Cannot connect non-masking layer to layer with masked output"
38
+ self.previous = layer
39
+ self.build()
40
+
41
+ def build(self):
42
+ '''Instantiation of layer weights.
43
+
44
+ Called after `set_previous`, or after `set_input_shape`,
45
+ once the layer has a defined input shape.
46
+ Must be implemented on all layers that have weights.
47
+ '''
48
+ pass
49
+
50
+ @property
51
+ def trainable(self):
52
+ if hasattr(self, '_trainable'):
53
+ return self._trainable
54
+ else:
55
+ return True
56
+
57
+ @trainable.setter
58
+ def trainable(self, value):
59
+ self._trainable = value
60
+
61
+ @property
62
+ def nb_input(self):
63
+ return 1
64
+
65
+ @property
66
+ def nb_output(self):
67
+ return 1
68
+
69
+ @property
70
+ def input_shape(self):
71
+ # if layer is not connected (e.g. input layer),
72
+ # input shape can be set manually via _input_shape attribute.
73
+ if hasattr(self, 'previous'):
74
+ return self.previous.output_shape
75
+ elif hasattr(self, '_input_shape'):
76
+ return self._input_shape
77
+ else:
78
+ raise Exception('Layer is not connected. Did you forget to set "input_shape"?')
79
+
80
+ def set_input_shape(self, input_shape):
81
+ if type(input_shape) not in [tuple, list]:
82
+ raise Exception('Invalid input shape - input_shape should be a tuple of int.')
83
+ input_shape = (None,) + tuple(input_shape)
84
+ if hasattr(self, 'input_ndim') and self.input_ndim:
85
+ if self.input_ndim != len(input_shape):
86
+ raise Exception('Invalid input shape - Layer expects input ndim=' +
87
+ str(self.input_ndim) + ', was provided with input shape ' + str(input_shape))
88
+ self._input_shape = input_shape
89
+ self.input = K.placeholder(shape=self._input_shape)
90
+ self.build()
91
+
92
+ @property
93
+ def output_shape(self):
94
+ # default assumption: tensor shape unchanged.
95
+ return self.input_shape
96
+
97
+ def get_output(self, train=False):
98
+ return self.get_input(train)
99
+
100
+ def get_input(self, train=False):
101
+ if hasattr(self, 'previous'):
102
+ return self.previous.get_output(train=train)
103
+ elif hasattr(self, 'input'):
104
+ return self.input
105
+ else:
106
+ raise Exception('Layer is not connected\
107
+ and is not an input layer.')
108
+
109
+ def supports_masked_input(self):
110
+ ''' Whether or not this layer respects the output mask of its previous layer in its calculations. If you try
111
+ to attach a layer that does *not* support masked_input to a layer that gives a non-None output_mask() that is
112
+ an error'''
113
+ return False
114
+
115
+ def get_output_mask(self, train=None):
116
+ '''
117
+ For some models (such as RNNs) you want a way of being able to mark some output data-points as
118
+ "masked", so they are not used in future calculations. In such a model, get_output_mask() should return a mask
119
+ of one less dimension than get_output() (so if get_output is (nb_samples, nb_timesteps, nb_dimensions), then the mask
120
+ is (nb_samples, nb_timesteps), with a one for every unmasked datapoint, and a zero for every masked one.
121
+
122
+ If there is *no* masking then it shall return None. For instance if you attach an Activation layer (they support masking)
123
+ to a layer with an output_mask, then that Activation shall also have an output_mask. If you attach it to a layer with no
124
+ such mask, then the Activation's get_output_mask shall return None.
125
+
126
+ Some layers have an output_mask even if their input is unmasked, notably Embedding which can turn the entry "0" into
127
+ a mask.
128
+ '''
129
+ return None
130
+
131
+ def set_weights(self, weights):
132
+ assert len(self.params) == len(weights), 'Provided weight array does not match layer weights (' + \
133
+ str(len(self.params)) + ' layer params vs. ' + str(len(weights)) + ' provided weights)'
134
+ for p, w in zip(self.params, weights):
135
+ if K.get_value(p).shape != w.shape:
136
+ raise Exception("Layer shape %s not compatible with weight shape %s." % (K.get_value(p).shape, w.shape))
137
+ K.set_value(p, w)
138
+
139
+ def get_weights(self):
140
+ weights = []
141
+ for p in self.params:
142
+ weights.append(K.get_value(p))
143
+ return weights
144
+
145
+ def get_config(self):
146
+ config = {"name": self.__class__.__name__}
147
+ if hasattr(self, '_input_shape'):
148
+ config['input_shape'] = self._input_shape[1:]
149
+ if hasattr(self, '_trainable'):
150
+ config['trainable'] = self._trainable
151
+ return config
152
+
153
+ def get_params(self):
154
+ consts = []
155
+ updates = []
156
+
157
+ if hasattr(self, 'regularizers'):
158
+ regularizers = self.regularizers
159
+ else:
160
+ regularizers = []
161
+
162
+ if hasattr(self, 'constraints') and len(self.constraints) == len(self.params):
163
+ for c in self.constraints:
164
+ if c:
165
+ consts.append(c)
166
+ else:
167
+ consts.append(constraints.identity())
168
+ elif hasattr(self, 'constraint') and self.constraint:
169
+ consts += [self.constraint for _ in range(len(self.params))]
170
+ else:
171
+ consts += [constraints.identity() for _ in range(len(self.params))]
172
+
173
+ if hasattr(self, 'updates') and self.updates:
174
+ updates += self.updates
175
+
176
+ return self.params, regularizers, consts, updates
177
+
178
+ def count_params(self):
179
+ return sum([K.count_params(p) for p in self.params])
180
+
181
+
182
+ class MaskedLayer(Layer):
183
+ '''
184
+ If your layer trivially supports masking
185
+ (by simply copying the input mask to the output),
186
+ then subclass MaskedLayer instead of Layer,
187
+ and make sure that you incorporate the input mask
188
+ into your calculation of get_output()
189
+ '''
190
+ def supports_masked_input(self):
191
+ return True
192
+
193
+ def get_input_mask(self, train=False):
194
+ if hasattr(self, 'previous'):
195
+ return self.previous.get_output_mask(train)
196
+ else:
197
+ return None
198
+
199
+ def get_output_mask(self, train=False):
200
+ ''' The default output mask is just the input mask unchanged.
201
+ Override this in your own implementations if,
202
+ for instance, you are reshaping the input'''
203
+ return self.get_input_mask(train)
204
+
205
+
206
+ class Masking(MaskedLayer):
207
+ """Mask an input sequence by using a mask value to identify padding.
208
+
209
+ This layer copies the input to the output layer with identified padding
210
+ replaced with 0s and creates an output mask in the process.
211
+
212
+ At each timestep, if the values all equal `mask_value`,
213
+ then the corresponding mask value for the timestep is 0 (skipped),
214
+ otherwise it is 1.
215
+
216
+ """
217
+ def __init__(self, mask_value=0., **kwargs):
218
+ super(Masking, self).__init__(**kwargs)
219
+ self.mask_value = mask_value
220
+ self.input = K.placeholder(ndim=3)
221
+
222
+ def get_output_mask(self, train=False):
223
+ if K._BACKEND == "tensorflow":
224
+ raise Exception("Masking is Theano-only for the time being.")
225
+ X = self.get_input(train)
226
+ return K.any(K.ones_like(X) * (1. - K.equal(X, self.mask_value)),
227
+ axis=-1)
228
+
229
+ def get_output(self, train=False):
230
+ X = self.get_input(train)
231
+ return X * K.any((1. - K.equal(X, self.mask_value)),
232
+ axis=-1, keepdims=True)
233
+
234
+ def get_config(self):
235
+ config = {"name": self.__class__.__name__,
236
+ "mask_value": self.mask_value}
237
+ base_config = super(Masking, self).get_config()
238
+ return dict(list(base_config.items()) + list(config.items()))
239
+
240
+
241
+ class TimeDistributedMerge(Layer):
242
+ '''Sum/multiply/average over the outputs of a TimeDistributed layer.
243
+ mode: {'sum', 'mul', 'ave'}
244
+ Tensor input dimensions: (nb_sample, time, features)
245
+ Tensor output dimensions: (nb_sample, features)
246
+ '''
247
+ input_ndim = 3
248
+
249
+ def __init__(self, mode='sum', **kwargs):
250
+ super(TimeDistributedMerge, self).__init__(**kwargs)
251
+ self.mode = mode
252
+ self.params = []
253
+ self.regularizers = []
254
+ self.constraints = []
255
+ self.updates = []
256
+
257
+ @property
258
+ def output_shape(self):
259
+ return (None, self.input_shape[2])
260
+
261
+ def get_output(self, train=False):
262
+ X = self.get_input(train)
263
+ if self.mode == 'ave':
264
+ s = K.mean(X, axis=1)
265
+ return s
266
+ if self.mode == 'sum':
267
+ s = K.sum(X, axis=1)
268
+ return s
269
+ elif self.mode == 'mul':
270
+ s = K.prod(X, axis=1)
271
+ return s
272
+ else:
273
+ raise Exception('Unknown merge mode')
274
+
275
+ def get_config(self):
276
+ config = {"name": self.__class__.__name__,
277
+ "mode": self.mode}
278
+ base_config = super(TimeDistributedMerge, self).get_config()
279
+ return dict(list(base_config.items()) + list(config.items()))
280
+
281
+
282
+ class Merge(Layer):
283
+ def __init__(self, layers, mode='sum', concat_axis=-1, dot_axes=-1):
284
+ ''' Merge the output of a list of layers or containers into a single tensor.
285
+ mode: {'sum', 'mul', 'concat', 'ave', 'join'}
286
+ '''
287
+ if len(layers) < 2:
288
+ raise Exception("Please specify two or more input layers (or containers) to merge")
289
+
290
+ if mode not in {'sum', 'mul', 'concat', 'ave', 'join', 'cos', 'dot'}:
291
+ raise Exception("Invalid merge mode: " + str(mode))
292
+
293
+ if mode in {'sum', 'mul', 'ave', 'cos'}:
294
+ input_shapes = set([l.output_shape for l in layers])
295
+ if len(input_shapes) > 1:
296
+ raise Exception("Only layers of same output shape can be merged using " + mode + " mode. " +
297
+ "Layer shapes: %s" % ([l.output_shape for l in layers]))
298
+ if mode in {'cos', 'dot'}:
299
+ if K._BACKEND != 'theano':
300
+ raise Exception('"' + mode + '" merge mode will only work with Theano.')
301
+
302
+ if len(layers) > 2:
303
+ raise Exception(mode + " merge takes exactly 2 layers")
304
+ shape1 = layers[0].output_shape
305
+ shape2 = layers[1].output_shape
306
+ n1 = len(shape1)
307
+ n2 = len(shape2)
308
+ if mode == 'dot':
309
+ if type(dot_axes) == int:
310
+ if dot_axes < 0:
311
+ dot_axes = [range(dot_axes % n1, n1), range(dot_axes % n2, n2)]
312
+ else:
313
+ dot_axes = [range(n1 - dot_axes, n2), range(1, dot_axes + 1)]
314
+ if type(dot_axes) not in [list, tuple]:
315
+ raise Exception("Invalid type for dot_axes - should be a list.")
316
+ if len(dot_axes) != 2:
317
+ raise Exception("Invalid format for dot_axes - should contain two elements.")
318
+ if type(dot_axes[0]) not in [list, tuple, range] or type(dot_axes[1]) not in [list, tuple, range]:
319
+ raise Exception("Invalid format for dot_axes - list elements should have type 'list' or 'tuple'.")
320
+ for i in range(len(dot_axes[0])):
321
+ if shape1[dot_axes[0][i]] != shape2[dot_axes[1][i]]:
322
+ raise Exception("Dimension incompatibility using dot mode: " +
323
+ "%s != %s. " % (shape1[dot_axes[0][i]], shape2[dot_axes[1][i]]) +
324
+ "Layer shapes: %s, %s" % (shape1, shape2))
325
+ elif mode == 'concat':
326
+ input_shapes = set()
327
+ for l in layers:
328
+ oshape = list(l.output_shape)
329
+ oshape.pop(concat_axis)
330
+ oshape = tuple(oshape)
331
+ input_shapes.add(oshape)
332
+ if len(input_shapes) > 1:
333
+ raise Exception("'concat' mode can only merge layers with matching " +
334
+ "output shapes except for the concat axis. " +
335
+ "Layer shapes: %s" % ([l.output_shape for l in layers]))
336
+
337
+ self.mode = mode
338
+ self.concat_axis = concat_axis
339
+ self.dot_axes = dot_axes
340
+ self.layers = layers
341
+ self.params = []
342
+ self.regularizers = []
343
+ self.constraints = []
344
+ self.updates = []
345
+ for l in self.layers:
346
+ params, regs, consts, updates = l.get_params()
347
+ self.regularizers += regs
348
+ self.updates += updates
349
+ # params and constraints have the same size
350
+ for p, c in zip(params, consts):
351
+ if p not in self.params:
352
+ self.params.append(p)
353
+ self.constraints.append(c)
354
+
355
+ @property
356
+ def output_shape(self):
357
+ input_shapes = [layer.output_shape for layer in self.layers]
358
+ if self.mode in ['sum', 'mul', 'ave']:
359
+ return input_shapes[0]
360
+ elif self.mode == 'concat':
361
+ output_shape = list(input_shapes[0])
362
+ for shape in input_shapes[1:]:
363
+ output_shape[self.concat_axis] += shape[self.concat_axis]
364
+ return tuple(output_shape)
365
+ elif self.mode == 'join':
366
+ return None
367
+ elif self.mode == 'dot':
368
+ shape1 = list(input_shapes[0])
369
+ shape2 = list(input_shapes[1])
370
+ dot_axes = []
371
+ for axes in self.dot_axes:
372
+ dot_axes.append([index-1 for index in axes])
373
+ tensordot_output = np.tensordot(np.zeros(tuple(shape1[1:])),
374
+ np.zeros(tuple(shape2[1:])),
375
+ axes=dot_axes)
376
+ if len(tensordot_output.shape) == 0:
377
+ shape = (1,)
378
+ else:
379
+ shape = tensordot_output.shape
380
+ return (shape1[0],) + shape
381
+ elif self.mode == 'cos':
382
+ return tuple(input_shapes[0][0], 1)
383
+
384
+ def get_params(self):
385
+ return self.params, self.regularizers, self.constraints, self.updates
386
+
387
+ def get_output(self, train=False):
388
+ if self.mode == 'sum' or self.mode == 'ave':
389
+ s = self.layers[0].get_output(train)
390
+ for i in range(1, len(self.layers)):
391
+ s += self.layers[i].get_output(train)
392
+ if self.mode == 'ave':
393
+ s /= len(self.layers)
394
+ return s
395
+ elif self.mode == 'concat':
396
+ inputs = [self.layers[i].get_output(train) for i in range(len(self.layers))]
397
+ return K.concatenate(inputs, axis=self.concat_axis)
398
+ elif self.mode == 'join':
399
+ inputs = OrderedDict()
400
+ for i in range(len(self.layers)):
401
+ X = self.layers[i].get_output(train)
402
+ if X.name is None:
403
+ raise ValueError("merge_mode='join' only works with named inputs")
404
+ else:
405
+ inputs[X.name] = X
406
+ return inputs
407
+ elif self.mode == 'mul':
408
+ s = self.layers[0].get_output(train)
409
+ for i in range(1, len(self.layers)):
410
+ s *= self.layers[i].get_output(train)
411
+ return s
412
+ elif self.mode == 'dot':
413
+ if K._BACKEND != 'theano':
414
+ raise Exception('"dot" merge mode will only work with Theano.')
415
+ from theano import tensor as T
416
+ l1 = self.layers[0].get_output(train)
417
+ l2 = self.layers[1].get_output(train)
418
+ output = T.batched_tensordot(l1, l2, self.dot_axes)
419
+ output_shape = list(self.output_shape)
420
+ output_shape[0] = l1.shape[0]
421
+ output = output.reshape(tuple(output_shape))
422
+ return output
423
+ elif self.mode == 'cos':
424
+ if K._BACKEND != 'theano':
425
+ raise Exception('"dot" merge mode will only work with Theano.')
426
+ import theano
427
+ l1 = self.layers[0].get_output(train)
428
+ l2 = self.layers[1].get_output(train)
429
+ output, _ = theano.scan(lambda v1, v2: K.dot(v1, v2) / K.sqrt(K.dot(v1, v1) * K.dot(v2, v2)),
430
+ sequences=[l1, l2],
431
+ outputs_info=None)
432
+ return output
433
+ else:
434
+ raise Exception('Unknown merge mode')
435
+
436
+ def get_input(self, train=False):
437
+ res = []
438
+ for i in range(len(self.layers)):
439
+ o = self.layers[i].get_input(train)
440
+ if not type(o) == list:
441
+ o = [o]
442
+ for output in o:
443
+ if output not in res:
444
+ res.append(output)
445
+ return res
446
+
447
+ @property
448
+ def input(self):
449
+ return self.get_input()
450
+
451
+ def supports_masked_input(self):
452
+ return False
453
+
454
+ def get_output_mask(self, train=None):
455
+ return None
456
+
457
+ def get_weights(self):
458
+ weights = []
459
+ for l in self.layers:
460
+ weights += l.get_weights()
461
+ return weights
462
+
463
+ def set_weights(self, weights):
464
+ for i in range(len(self.layers)):
465
+ nb_param = len(self.layers[i].params)
466
+ self.layers[i].set_weights(weights[:nb_param])
467
+ weights = weights[nb_param:]
468
+
469
+ def get_config(self):
470
+ config = {"name": self.__class__.__name__,
471
+ "layers": [l.get_config() for l in self.layers],
472
+ "mode": self.mode,
473
+ "concat_axis": self.concat_axis,
474
+ "dot_axes": self.dot_axes}
475
+ base_config = super(Merge, self).get_config()
476
+ return dict(list(base_config.items()) + list(config.items()))
477
+
478
+
479
+ class Dropout(MaskedLayer):
480
+ '''
481
+ Hinton's dropout.
482
+ '''
483
+ def __init__(self, p, **kwargs):
484
+ super(Dropout, self).__init__(**kwargs)
485
+ self.p = p
486
+
487
+ def get_output(self, train=False):
488
+ X = self.get_input(train)
489
+ if self.p > 0.:
490
+ if train:
491
+ X = K.dropout(X, level=self.p)
492
+ return X
493
+
494
+ def get_config(self):
495
+ config = {"name": self.__class__.__name__,
496
+ "p": self.p}
497
+ base_config = super(Dropout, self).get_config()
498
+ return dict(list(base_config.items()) + list(config.items()))
499
+
500
+
501
+ class Activation(MaskedLayer):
502
+ '''
503
+ Apply an activation function to an output.
504
+ '''
505
+ def __init__(self, activation, target=0, beta=0.1, **kwargs):
506
+ super(Activation, self).__init__(**kwargs)
507
+ self.activation = activations.get(activation)
508
+ self.target = target
509
+ self.beta = beta
510
+
511
+ def get_output(self, train=False):
512
+ X = self.get_input(train)
513
+ return self.activation(X)
514
+
515
+ def get_config(self):
516
+ config = {"name": self.__class__.__name__,
517
+ "activation": self.activation.__name__,
518
+ "target": self.target,
519
+ "beta": self.beta}
520
+ base_config = super(Activation, self).get_config()
521
+ return dict(list(base_config.items()) + list(config.items()))
522
+
523
+
524
+ class Reshape(Layer):
525
+ '''
526
+ Reshape an output to a certain shape.
527
+ Can't be used as first layer in a model (no fixed input!)
528
+ First dimension is assumed to be nb_samples.
529
+ '''
530
+ def __init__(self, dims, **kwargs):
531
+ super(Reshape, self).__init__(**kwargs)
532
+ self.dims = tuple(dims)
533
+
534
+ @property
535
+ def output_shape(self):
536
+ return (self.input_shape[0],) + self.dims
537
+
538
+ def get_output(self, train=False):
539
+ X = self.get_input(train)
540
+ return K.reshape(X, (-1,) + self.dims)
541
+
542
+ def get_config(self):
543
+ config = {"name": self.__class__.__name__,
544
+ "dims": self.dims}
545
+ base_config = super(Reshape, self).get_config()
546
+ return dict(list(base_config.items()) + list(config.items()))
547
+
548
+
549
+ class Permute(Layer):
550
+ '''
551
+ Permute the dimensions of the input according to the given tuple.
552
+ '''
553
+ def __init__(self, dims, **kwargs):
554
+ super(Permute, self).__init__(**kwargs)
555
+ self.dims = tuple(dims)
556
+
557
+ @property
558
+ def output_shape(self):
559
+ input_shape = list(self.input_shape)
560
+ output_shape = copy.copy(input_shape)
561
+ for i, dim in enumerate(self.dims):
562
+ target_dim = input_shape[dim]
563
+ output_shape[i+1] = target_dim
564
+ return tuple(output_shape)
565
+
566
+ def get_output(self, train=False):
567
+ X = self.get_input(train)
568
+ return K.permute_dimensions(X, (0,) + self.dims)
569
+
570
+ def get_config(self):
571
+ config = {"name": self.__class__.__name__,
572
+ "dims": self.dims}
573
+ base_config = super(Permute, self).get_config()
574
+ return dict(list(base_config.items()) + list(config.items()))
575
+
576
+
577
+ class Flatten(Layer):
578
+ '''
579
+ Reshape input to flat shape.
580
+ First dimension is assumed to be nb_samples.
581
+ '''
582
+ def __init__(self, **kwargs):
583
+ super(Flatten, self).__init__(**kwargs)
584
+
585
+ @property
586
+ def output_shape(self):
587
+ input_shape = self.input_shape
588
+ return (input_shape[0], np.prod(input_shape[1:]))
589
+
590
+ def get_output(self, train=False):
591
+ X = self.get_input(train)
592
+ return K.flatten(X)
593
+
594
+
595
+ class RepeatVector(Layer):
596
+ '''
597
+ Repeat input n times.
598
+
599
+ Dimensions of input are assumed to be (nb_samples, dim).
600
+ Return tensor of shape (nb_samples, n, dim).
601
+ '''
602
+ def __init__(self, n, **kwargs):
603
+ super(RepeatVector, self).__init__(**kwargs)
604
+ self.n = n
605
+
606
+ @property
607
+ def output_shape(self):
608
+ input_shape = self.input_shape
609
+ return (input_shape[0], self.n, input_shape[1])
610
+
611
+ def get_output(self, train=False):
612
+ X = self.get_input(train)
613
+ return K.repeat(X, self.n)
614
+
615
+ def get_config(self):
616
+ config = {"name": self.__class__.__name__,
617
+ "n": self.n}
618
+ base_config = super(RepeatVector, self).get_config()
619
+ return dict(list(base_config.items()) + list(config.items()))
620
+
621
+
622
+ class Dense(Layer):
623
+ '''
624
+ Just your regular fully connected NN layer.
625
+ '''
626
+ input_ndim = 2
627
+
628
+ def __init__(self, output_dim, init='glorot_uniform', activation='linear', weights=None,
629
+ W_regularizer=None, b_regularizer=None, activity_regularizer=None,
630
+ W_constraint=None, b_constraint=None, input_dim=None, **kwargs):
631
+ self.init = initializations.get(init)
632
+ self.activation = activations.get(activation)
633
+ self.output_dim = output_dim
634
+
635
+ self.W_regularizer = regularizers.get(W_regularizer)
636
+ self.b_regularizer = regularizers.get(b_regularizer)
637
+ self.activity_regularizer = regularizers.get(activity_regularizer)
638
+
639
+ self.W_constraint = constraints.get(W_constraint)
640
+ self.b_constraint = constraints.get(b_constraint)
641
+ self.constraints = [self.W_constraint, self.b_constraint]
642
+
643
+ self.initial_weights = weights
644
+
645
+ self.input_dim = input_dim
646
+ if self.input_dim:
647
+ kwargs['input_shape'] = (self.input_dim,)
648
+ self.input = K.placeholder(ndim=2)
649
+ super(Dense, self).__init__(**kwargs)
650
+
651
+ def build(self):
652
+ input_dim = self.input_shape[1]
653
+
654
+ self.W = self.init((input_dim, self.output_dim))
655
+ self.b = K.zeros((self.output_dim,))
656
+
657
+ self.params = [self.W, self.b]
658
+
659
+ self.regularizers = []
660
+ if self.W_regularizer:
661
+ self.W_regularizer.set_param(self.W)
662
+ self.regularizers.append(self.W_regularizer)
663
+
664
+ if self.b_regularizer:
665
+ self.b_regularizer.set_param(self.b)
666
+ self.regularizers.append(self.b_regularizer)
667
+
668
+ if self.activity_regularizer:
669
+ self.activity_regularizer.set_layer(self)
670
+ self.regularizers.append(self.activity_regularizer)
671
+
672
+ if self.initial_weights is not None:
673
+ self.set_weights(self.initial_weights)
674
+ del self.initial_weights
675
+
676
+ @property
677
+ def output_shape(self):
678
+ return (self.input_shape[0], self.output_dim)
679
+
680
+ def get_output(self, train=False):
681
+ X = self.get_input(train)
682
+ output = self.activation(K.dot(X, self.W) + self.b)
683
+ return output
684
+
685
+ def get_config(self):
686
+ config = {"name": self.__class__.__name__,
687
+ "output_dim": self.output_dim,
688
+ "init": self.init.__name__,
689
+ "activation": self.activation.__name__,
690
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
691
+ "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None,
692
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
693
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None,
694
+ "b_constraint": self.b_constraint.get_config() if self.b_constraint else None,
695
+ "input_dim": self.input_dim}
696
+ base_config = super(Dense, self).get_config()
697
+ return dict(list(base_config.items()) + list(config.items()))
698
+
699
+
700
+ class ActivityRegularization(Layer):
701
+ '''
702
+ Layer that passes through its input unchanged, but applies an update
703
+ to the cost function based on the activity.
704
+ '''
705
+ def __init__(self, l1=0., l2=0., **kwargs):
706
+ super(ActivityRegularization, self).__init__(**kwargs)
707
+ self.l1 = l1
708
+ self.l2 = l2
709
+
710
+ activity_regularizer = ActivityRegularizer(l1=l1, l2=l2)
711
+ activity_regularizer.set_layer(self)
712
+ self.regularizers = [activity_regularizer]
713
+
714
+ def get_output(self, train=False):
715
+ return self.get_input(train)
716
+
717
+ def get_config(self):
718
+ config = {"name": self.__class__.__name__,
719
+ "l1": self.l1,
720
+ "l2": self.l2}
721
+ base_config = super(ActivityRegularization, self).get_config()
722
+ return dict(list(base_config.items()) + list(config.items()))
723
+
724
+
725
+ class TimeDistributedDense(MaskedLayer):
726
+ '''
727
+ Apply a same Dense layer for each dimension[1] (time_dimension) input.
728
+ Especially useful after a recurrent network with 'return_sequence=True'.
729
+ Tensor input dimensions: (nb_sample, time_dimension, input_dim)
730
+ Tensor output dimensions: (nb_sample, time_dimension, output_dim)
731
+
732
+ '''
733
+ input_ndim = 3
734
+
735
+ def __init__(self, output_dim,
736
+ init='glorot_uniform', activation='linear', weights=None,
737
+ W_regularizer=None, b_regularizer=None, activity_regularizer=None,
738
+ W_constraint=None, b_constraint=None,
739
+ input_dim=None, input_length=None, **kwargs):
740
+ self.output_dim = output_dim
741
+ self.init = initializations.get(init)
742
+ self.activation = activations.get(activation)
743
+
744
+ self.W_regularizer = regularizers.get(W_regularizer)
745
+ self.b_regularizer = regularizers.get(b_regularizer)
746
+ self.activity_regularizer = regularizers.get(activity_regularizer)
747
+
748
+ self.W_constraint = constraints.get(W_constraint)
749
+ self.b_constraint = constraints.get(b_constraint)
750
+ self.constraints = [self.W_constraint, self.b_constraint]
751
+
752
+ self.initial_weights = weights
753
+
754
+ self.input_dim = input_dim
755
+ self.input_length = input_length
756
+ if self.input_dim:
757
+ kwargs['input_shape'] = (self.input_length, self.input_dim)
758
+ self.input = K.placeholder(ndim=3)
759
+ super(TimeDistributedDense, self).__init__(**kwargs)
760
+
761
+ def build(self):
762
+ input_dim = self.input_shape[2]
763
+
764
+ self.W = self.init((input_dim, self.output_dim))
765
+ self.b = K.zeros((self.output_dim))
766
+
767
+ self.params = [self.W, self.b]
768
+ self.regularizers = []
769
+
770
+ if self.W_regularizer:
771
+ self.W_regularizer.set_param(self.W)
772
+ self.regularizers.append(self.W_regularizer)
773
+
774
+ if self.b_regularizer:
775
+ self.b_regularizer.set_param(self.b)
776
+ self.regularizers.append(self.b_regularizer)
777
+
778
+ if self.activity_regularizer:
779
+ self.activity_regularizer.set_layer(self)
780
+ self.regularizers.append(self.activity_regularizer)
781
+
782
+ if self.initial_weights is not None:
783
+ self.set_weights(self.initial_weights)
784
+ del self.initial_weights
785
+
786
+ @property
787
+ def output_shape(self):
788
+ input_shape = self.input_shape
789
+ return (input_shape[0], input_shape[1], self.output_dim)
790
+
791
+ def get_output(self, train=False):
792
+ X = self.get_input(train)
793
+
794
+ def step(x, states):
795
+ output = K.dot(x, self.W) + self.b
796
+ return output, []
797
+
798
+ last_output, outputs, states = K.rnn(step, X, [], masking=False)
799
+ outputs = self.activation(outputs)
800
+ return outputs
801
+
802
+ def get_config(self):
803
+ config = {"name": self.__class__.__name__,
804
+ "output_dim": self.output_dim,
805
+ "init": self.init.__name__,
806
+ "activation": self.activation.__name__,
807
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
808
+ "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None,
809
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
810
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None,
811
+ "b_constraint": self.b_constraint.get_config() if self.b_constraint else None,
812
+ "input_dim": self.input_dim,
813
+ "input_length": self.input_length}
814
+ base_config = super(TimeDistributedDense, self).get_config()
815
+ return dict(list(base_config.items()) + list(config.items()))
816
+
817
+
818
+ class AutoEncoder(Layer):
819
+ '''A customizable autoencoder model.
820
+
821
+ Tensor input dimensions: same as encoder input
822
+ Tensor output dimensions:
823
+ if output_reconstruction:
824
+ same as encoder output
825
+ else:
826
+ same as decoder output
827
+ '''
828
+ def __init__(self, encoder, decoder, output_reconstruction=True, weights=None, **kwargs):
829
+ super(AutoEncoder, self).__init__(**kwargs)
830
+
831
+ self.output_reconstruction = output_reconstruction
832
+ self.encoder = encoder
833
+ self.decoder = decoder
834
+
835
+ self.decoder.set_previous(self.encoder)
836
+
837
+ self.params = []
838
+ self.regularizers = []
839
+ self.constraints = []
840
+ self.updates = []
841
+ for layer in [self.encoder, self.decoder]:
842
+ params, regularizers, constraints, updates = layer.get_params()
843
+ self.regularizers += regularizers
844
+ self.updates += updates
845
+ for p, c in zip(params, constraints):
846
+ if p not in self.params:
847
+ self.params.append(p)
848
+ self.constraints.append(c)
849
+
850
+ if weights is not None:
851
+ self.set_weights(weights)
852
+
853
+ def set_previous(self, node):
854
+ self.encoder.set_previous(node)
855
+
856
+ def get_weights(self):
857
+ weights = []
858
+ for layer in [self.encoder, self.decoder]:
859
+ weights += layer.get_weights()
860
+ return weights
861
+
862
+ def set_weights(self, weights):
863
+ nb_param = len(self.encoder.params)
864
+ self.encoder.set_weights(weights[:nb_param])
865
+ self.decoder.set_weights(weights[nb_param:])
866
+
867
+ def get_input(self, train=False):
868
+ return self.encoder.get_input(train)
869
+
870
+ @property
871
+ def input(self):
872
+ return self.encoder.input
873
+
874
+ def _get_hidden(self, train=False):
875
+ return self.encoder.get_output(train)
876
+
877
+ @property
878
+ def input_shape(self):
879
+ return self.encoder.input_shape
880
+
881
+ @property
882
+ def output_shape(self):
883
+ if self.output_reconstruction:
884
+ return self.encoder.previous.output_shape
885
+ else:
886
+ return self.decoder.previous.output_shape
887
+
888
+ def get_output(self, train=False):
889
+ if not train and not self.output_reconstruction:
890
+ return self.encoder.get_output(train)
891
+
892
+ return self.decoder.get_output(train)
893
+
894
+ def get_config(self):
895
+ return {"name": self.__class__.__name__,
896
+ "encoder_config": self.encoder.get_config(),
897
+ "decoder_config": self.decoder.get_config(),
898
+ "output_reconstruction": self.output_reconstruction}
899
+
900
+
901
+ class MaxoutDense(Layer):
902
+ '''
903
+ Max-out layer, nb_feature is the number of pieces in the piecewise linear approx.
904
+ Refer to http://arxiv.org/pdf/1302.4389.pdf
905
+ '''
906
+ input_ndim = 2
907
+
908
+ def __init__(self, output_dim, nb_feature=4, init='glorot_uniform', weights=None,
909
+ W_regularizer=None, b_regularizer=None, activity_regularizer=None,
910
+ W_constraint=None, b_constraint=None, input_dim=None, **kwargs):
911
+ self.output_dim = output_dim
912
+ self.nb_feature = nb_feature
913
+ self.init = initializations.get(init)
914
+
915
+ self.W_regularizer = regularizers.get(W_regularizer)
916
+ self.b_regularizer = regularizers.get(b_regularizer)
917
+ self.activity_regularizer = regularizers.get(activity_regularizer)
918
+
919
+ self.W_constraint = constraints.get(W_constraint)
920
+ self.b_constraint = constraints.get(b_constraint)
921
+ self.constraints = [self.W_constraint, self.b_constraint]
922
+
923
+ self.initial_weights = weights
924
+ self.input_dim = input_dim
925
+ if self.input_dim:
926
+ kwargs['input_shape'] = (self.input_dim,)
927
+ self.input = K.placeholder(ndim=2)
928
+ super(MaxoutDense, self).__init__(**kwargs)
929
+
930
+ def build(self):
931
+ input_dim = self.input_shape[1]
932
+
933
+ self.W = self.init((self.nb_feature, input_dim, self.output_dim))
934
+ self.b = K.zeros((self.nb_feature, self.output_dim))
935
+
936
+ self.params = [self.W, self.b]
937
+ self.regularizers = []
938
+
939
+ if self.W_regularizer:
940
+ self.W_regularizer.set_param(self.W)
941
+ self.regularizers.append(self.W_regularizer)
942
+
943
+ if self.b_regularizer:
944
+ self.b_regularizer.set_param(self.b)
945
+ self.regularizers.append(self.b_regularizer)
946
+
947
+ if self.activity_regularizer:
948
+ self.activity_regularizer.set_layer(self)
949
+ self.regularizers.append(self.activity_regularizer)
950
+
951
+ if self.initial_weights is not None:
952
+ self.set_weights(self.initial_weights)
953
+ del self.initial_weights
954
+
955
+ @property
956
+ def output_shape(self):
957
+ return (self.input_shape[0], self.output_dim)
958
+
959
+ def get_output(self, train=False):
960
+ X = self.get_input(train)
961
+ # -- don't need activation since it's just linear.
962
+ output = K.max(K.dot(X, self.W) + self.b, axis=1)
963
+ return output
964
+
965
+ def get_config(self):
966
+ config = {"name": self.__class__.__name__,
967
+ "output_dim": self.output_dim,
968
+ "init": self.init.__name__,
969
+ "nb_feature": self.nb_feature,
970
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
971
+ "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None,
972
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
973
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None,
974
+ "b_constraint": self.b_constraint.get_config() if self.b_constraint else None,
975
+ "input_dim": self.input_dim}
976
+ base_config = super(MaxoutDense, self).get_config()
977
+ return dict(list(base_config.items()) + list(config.items()))
978
+
979
+
980
+ class Lambda(Layer):
981
+ """Lambda layer for evaluating arbitrary function
982
+
983
+ Input shape
984
+ -----------
985
+ output_shape of previous layer
986
+
987
+ Output shape
988
+ ------------
989
+ Specified by output_shape argument
990
+
991
+ Arguments
992
+ ---------
993
+ function - The function to be evaluated. Takes one argument : output of previous layer
994
+ output_shape - Expected output shape from function. Could be a tuple or a function of the shape of the input
995
+ """
996
+
997
+ def __init__(self, function, output_shape=None, **kwargs):
998
+ super(Lambda, self).__init__(**kwargs)
999
+ py3 = sys.version_info[0] == 3
1000
+ if py3:
1001
+ self.function = marshal.dumps(function.__code__)
1002
+ else:
1003
+ self.function = marshal.dumps(function.func_code)
1004
+ if output_shape is None:
1005
+ self._output_shape = None
1006
+ elif type(output_shape) in {tuple, list} :
1007
+ self._output_shape = tuple(output_shape)
1008
+ else:
1009
+ if py3:
1010
+ self._output_shape = marshal.dumps(output_shape.__code__)
1011
+ else:
1012
+ self._output_shape = marshal.dumps(output_shape.func_code)
1013
+
1014
+ @property
1015
+ def output_shape(self):
1016
+ if self._output_shape is None:
1017
+ return self.input_shape
1018
+ elif type(self._output_shape) == tuple:
1019
+ return (self.input_shape[0], ) + self._output_shape
1020
+ else:
1021
+ output_shape_func = marshal.loads(self._output_shape)
1022
+ output_shape_func = types.FunctionType(output_shape_func, globals())
1023
+ shape = output_shape_func(self.previous.output_shape)
1024
+ if type(shape) not in {list, tuple}:
1025
+ raise Exception("output_shape function must return a tuple")
1026
+ return tuple(shape)
1027
+
1028
+ def get_output(self, train=False):
1029
+ func = marshal.loads(self.function)
1030
+ func = types.FunctionType(func, globals())
1031
+ if hasattr(self, 'previous'):
1032
+ return func(self.previous.get_output(train))
1033
+ else:
1034
+ return func(self.input)
1035
+
1036
+
1037
+ class MaskedLambda(MaskedLayer, Lambda):
1038
+ pass
1039
+
1040
+
1041
+ class LambdaMerge(Lambda):
1042
+ """LambdaMerge layer for evaluating arbitrary function over multiple inputs
1043
+
1044
+ Input shape
1045
+ -----------
1046
+ None
1047
+
1048
+ Output shape
1049
+ ------------
1050
+ Specified by output_shape argument
1051
+
1052
+ Arguments
1053
+ ---------
1054
+ layers - Input layers. Similar to layers argument of Merge
1055
+ function - The function to be evaluated. Takes one argument:
1056
+ list of outputs from input layers
1057
+ output_shape - Expected output shape from function.
1058
+ Could be a tuple or a function of list of input shapes
1059
+ """
1060
+ def __init__(self, layers, function, output_shape=None):
1061
+ if len(layers) < 2:
1062
+ raise Exception("Please specify two or more input layers (or containers) to merge")
1063
+ self.layers = layers
1064
+ self.params = []
1065
+ self.regularizers = []
1066
+ self.constraints = []
1067
+ self.updates = []
1068
+ for l in self.layers:
1069
+ params, regs, consts, updates = l.get_params()
1070
+ self.regularizers += regs
1071
+ self.updates += updates
1072
+ # params and constraints have the same size
1073
+ for p, c in zip(params, consts):
1074
+ if p not in self.params:
1075
+ self.params.append(p)
1076
+ self.constraints.append(c)
1077
+ py3 = sys.version_info[0] == 3
1078
+ if py3:
1079
+ self.function = marshal.dumps(function.__code__)
1080
+ else:
1081
+ self.function = marshal.dumps(function.func_code)
1082
+ if output_shape is None:
1083
+ self._output_shape = None
1084
+ elif type(output_shape) in {tuple, list}:
1085
+ self._output_shape = tuple(output_shape)
1086
+ else:
1087
+ if py3:
1088
+ self._output_shape = marshal.dumps(output_shape.__code__)
1089
+ else:
1090
+ self._output_shape = marshal.dumps(output_shape.func_code)
1091
+
1092
+ @property
1093
+ def output_shape(self):
1094
+ input_shapes = [layer.output_shape for layer in self.layers]
1095
+ if self._output_shape is None:
1096
+ return input_shapes[0]
1097
+ elif type(self._output_shape) == tuple:
1098
+ return (input_shapes[0][0], ) + self._output_shape
1099
+ else:
1100
+ output_shape_func = marshal.loads(self._output_shape)
1101
+ output_shape_func = types.FunctionType(output_shape_func, globals())
1102
+ shape = output_shape_func(input_shapes)
1103
+ if type(shape) not in {list, tuple}:
1104
+ raise Exception("output_shape function must return a tuple")
1105
+ return tuple(shape)
1106
+
1107
+ def get_params(self):
1108
+ return self.params, self.regularizers, self.constraints, self.updates
1109
+
1110
+ def get_output(self, train=False):
1111
+ func = marshal.loads(self.function)
1112
+ func = types.FunctionType(func, globals())
1113
+ inputs = [layer.get_output(train) for layer in self.layers]
1114
+ return func(inputs)
1115
+
1116
+ def get_input(self, train=False):
1117
+ res = []
1118
+ for i in range(len(self.layers)):
1119
+ o = self.layers[i].get_input(train)
1120
+ if not type(o) == list:
1121
+ o = [o]
1122
+ for output in o:
1123
+ if output not in res:
1124
+ res.append(output)
1125
+ return res
1126
+
1127
+ @property
1128
+ def input(self):
1129
+ return self.get_input()
1130
+
1131
+ def supports_masked_input(self):
1132
+ return False
1133
+
1134
+ def get_output_mask(self, train=None):
1135
+ return None
1136
+
1137
+ def get_weights(self):
1138
+ weights = []
1139
+ for l in self.layers:
1140
+ weights += l.get_weights()
1141
+ return weights
1142
+
1143
+ def set_weights(self, weights):
1144
+ for i in range(len(self.layers)):
1145
+ nb_param = len(self.layers[i].params)
1146
+ self.layers[i].set_weights(weights[:nb_param])
1147
+ weights = weights[nb_param:]
1148
+
1149
+ def get_config(self):
1150
+ config = {"name": self.__class__.__name__,
1151
+ "layers": [l.get_config() for l in self.layers],
1152
+ "function": self.function,
1153
+ "output_shape": self._output_shape
1154
+ }
1155
+ base_config = super(LambdaMerge, self).get_config()
1156
+ return dict(list(base_config.items()) + list(config.items()))
1157
+
1158
+
1159
+ class Siamese(Layer):
1160
+ '''Shared layer with multiple inputs
1161
+
1162
+ Output shape
1163
+ ------------
1164
+ Depends on merge_mode argument
1165
+
1166
+ Arguments
1167
+ ---------
1168
+ layer - The layer to be shared across multiple inputs
1169
+ inputs - inputs to the shared layer
1170
+ merge_mode - Similar to mode argument of Merge layer
1171
+ concat_axis - Similar to concat_axis argument of Merge layer
1172
+ dot_axes - Similar to dot_axes argument of Merge layer
1173
+ '''
1174
+ def __init__(self, layer, inputs, merge_mode='concat',
1175
+ concat_axis=1, dot_axes=-1):
1176
+ if merge_mode not in ['sum', 'mul', 'concat', 'ave',
1177
+ 'join', 'cos', 'dot', None]:
1178
+ raise Exception("Invalid merge mode: " + str(merge_mode))
1179
+
1180
+ if merge_mode in {'cos', 'dot'}:
1181
+ if len(inputs) > 2:
1182
+ raise Exception(merge_mode + " merge takes exactly 2 layers")
1183
+
1184
+ self.layer = layer
1185
+ self.inputs = inputs
1186
+ self.params = []
1187
+ self.merge_mode = merge_mode
1188
+ self.concat_axis = concat_axis
1189
+ self.dot_axes = dot_axes
1190
+ layer.set_previous(inputs[0])
1191
+ self.regularizers = []
1192
+ self.constraints = []
1193
+ self.updates = []
1194
+ layers = [layer]
1195
+ if merge_mode:
1196
+ layers += inputs
1197
+ for l in layers:
1198
+ params, regs, consts, updates = l.get_params()
1199
+ self.regularizers += regs
1200
+ self.updates += updates
1201
+ # params and constraints have the same size
1202
+ for p, c in zip(params, consts):
1203
+ if p not in self.params:
1204
+ self.params.append(p)
1205
+ self.constraints.append(c)
1206
+
1207
+ @property
1208
+ def output_shape(self):
1209
+ if self.merge_mode is None:
1210
+ return self.layer.output_shape
1211
+ input_shapes = [self.get_output_shape(i) for i in range(len(self.inputs))]
1212
+
1213
+ if self.merge_mode in ['sum', 'mul', 'ave']:
1214
+ return input_shapes[0]
1215
+
1216
+ elif self.merge_mode == 'concat':
1217
+ output_shape = list(input_shapes[0])
1218
+ for shape in input_shapes[1:]:
1219
+ output_shape[self.concat_axis] += shape[self.concat_axis]
1220
+ return tuple(output_shape)
1221
+
1222
+ elif self.merge_mode == 'join':
1223
+ return None
1224
+
1225
+ elif self.merge_mode == 'dot':
1226
+ shape1 = list(input_shapes[0])
1227
+ shape2 = list(input_shapes[1])
1228
+ for i in self.dot_axes[0]:
1229
+ shape1.pop(i)
1230
+ for i in self.dot_axes[1]:
1231
+ shape2.pop(i)
1232
+ shape = shape1 + shape2[1:]
1233
+ if len(shape) == 1:
1234
+ shape.append(1)
1235
+ return tuple(shape)
1236
+
1237
+ elif self.merge_mode == 'cos':
1238
+ return tuple(input_shapes[0][0], 1)
1239
+
1240
+ def get_params(self):
1241
+ return self.params, self.regularizers, self.constraints, self.updates
1242
+
1243
+ def set_layer_input(self, index):
1244
+ l = self.layer
1245
+ while not hasattr(l, 'previous'):
1246
+ l = l.layers[0]
1247
+ l.previous = self.inputs[index]
1248
+
1249
+ def get_output_at(self, head, train=False):
1250
+ self.set_layer_input(head)
1251
+ return self.layer.get_output(train)
1252
+
1253
+ def get_output_shape(self, head, train=False):
1254
+ self.set_layer_input(head)
1255
+ return self.layer.output_shape
1256
+
1257
+ def get_output_join(self, train=False):
1258
+ o = OrderedDict()
1259
+ for i in range(len(self.inputs)):
1260
+ X = self.get_output_at(i, train)
1261
+ if X.name is None:
1262
+ raise ValueError("merge_mode='join' only works with named inputs")
1263
+ o[X.name] = X
1264
+ return o
1265
+
1266
+ def get_output_sum(self, train=False):
1267
+ s = self.get_output_at(0, train)
1268
+ for i in range(1, len(self.inputs)):
1269
+ s += self.get_output_at(i, train)
1270
+ return s
1271
+
1272
+ def get_output_ave(self, train=False):
1273
+ n = len(self.inputs)
1274
+ s = self.get_output_at(0, train)
1275
+ for i in range(1, n):
1276
+ s += self.get_output_at(i, train)
1277
+ s /= n
1278
+ return s
1279
+
1280
+ def get_output_concat(self, train=False):
1281
+ inputs = [self.get_output_at(i, train) for i in range(len(self.inputs))]
1282
+ return K.concatenate(inputs, axis=self.concat_axis)
1283
+
1284
+ def get_output_mul(self, train=False):
1285
+ s = self.get_output_at(0, train)
1286
+ for i in range(1, len(self.inputs)):
1287
+ s *= self.get_output_at(i, train)
1288
+ return s
1289
+
1290
+ def get_output_dot(self, train=False):
1291
+ if K._BACKEND != 'theano':
1292
+ raise Exception('"dot" merge mode will only work with Theano.')
1293
+ from theano import tensor as T
1294
+ l1 = self.get_output_at(0, train)
1295
+ l2 = self.get_output_at(1, train)
1296
+ output = T.batched_tensordot(l1, l2, self.dot_axes)
1297
+ output = output.dimshuffle((0, 'x'))
1298
+ return output
1299
+
1300
+ def get_output_cos(self, train=False):
1301
+ if K._BACKEND != 'theano':
1302
+ raise Exception('"cos" merge mode will only work with Theano.')
1303
+ import theano
1304
+ from theano import tensor as T
1305
+ l1 = self.get_output_at(0, train)
1306
+ l2 = self.get_output_at(1, train)
1307
+ cos = lambda v1, v2: T.dot(v1, v2) / T.sqrt(T.dot(v1, v1) * T.dot(v2, v2))
1308
+ output, _ = theano.scan(cos, sequences=[l1, l2], outputs_info=None)
1309
+ output = output.dimshuffle((0, 'x'))
1310
+ return output
1311
+
1312
+ def get_output(self, train=False):
1313
+ mode = self.merge_mode
1314
+ if mode == 'join':
1315
+ return self.get_output_join(train)
1316
+ elif mode == 'concat':
1317
+ return self.get_output_concat(train)
1318
+ elif mode == 'sum':
1319
+ return self.get_output_sum(train)
1320
+ elif mode == 'ave':
1321
+ return self.get_output_ave(train)
1322
+ elif mode == 'mul':
1323
+ return self.get_output_mul(train)
1324
+ elif mode == 'dot':
1325
+ return self.get_output_dot(train)
1326
+ elif mode == 'cos':
1327
+ return self.get_output_dot(train)
1328
+
1329
+ def get_input(self, train=False):
1330
+ res = []
1331
+ for i in range(len(self.inputs)):
1332
+ o = self.inputs[i].get_input(train)
1333
+ if type(o) != list:
1334
+ o = [o]
1335
+ for output in o:
1336
+ if output not in res:
1337
+ res.append(output)
1338
+ return res
1339
+
1340
+ @property
1341
+ def input(self):
1342
+ return self.get_input()
1343
+
1344
+ def supports_masked_input(self):
1345
+ return False
1346
+
1347
+ def get_output_mask(self, train=None):
1348
+ return None
1349
+
1350
+ def get_weights(self):
1351
+ weights = self.layer.get_weights()
1352
+ if self.merge_mode:
1353
+ for m in self.inputs:
1354
+ weights += m.get_weights()
1355
+ return weights
1356
+
1357
+ def set_weights(self, weights):
1358
+ nb_param = len(self.layer.params)
1359
+ self.layer.set_weights(weights[:nb_param])
1360
+ weights = weights[nb_param:]
1361
+ if self.merge_mode:
1362
+ for i in range(len(self.inputs)):
1363
+ nb_param = len(self.inputs[i].params)
1364
+ self.inputs[i].set_weights(weights[:nb_param])
1365
+ weights = weights[nb_param:]
1366
+
1367
+ def get_config(self):
1368
+
1369
+ config = {"name": self.__class__.__name__,
1370
+ "layer": self.layer.get_config,
1371
+ "inputs": [m.get_config() for m in self.inputs],
1372
+ "merge_mode": self.merge_mode,
1373
+ "concat_axis": self.concat_axis,
1374
+ "dot_axes": self.dot_axes
1375
+ }
1376
+ base_config = super(Siamese, self).get_config()
1377
+ return dict(list(base_config.items()) + list(config.items()))
1378
+
1379
+
1380
+ class SiameseHead(Layer):
1381
+ '''This layer should be added only on top of a Siamese layer
1382
+ with merge_mode = None
1383
+
1384
+ Outputs the output of the Siamese layer at a given index,
1385
+ specified by the head argument
1386
+
1387
+ Arguments
1388
+ ---------
1389
+ head - The index at which the output of the Siamese layer
1390
+ should be obtained
1391
+ '''
1392
+ def __init__(self, head):
1393
+ self.head = head
1394
+ self.params = []
1395
+
1396
+ def get_output(self, train=False):
1397
+ return self.get_input(train)
1398
+
1399
+ @property
1400
+ def input_shape(self):
1401
+ return self.previous.get_output_shape(self.head)
1402
+
1403
+ def get_input(self, train=False):
1404
+ return self.previous.get_output_at(self.head, train)
1405
+
1406
+ def get_config(self):
1407
+
1408
+ config = {"name": self.__class__.__name__,
1409
+ "head": self.head}
1410
+
1411
+ base_config = super(SiameseHead, self).get_config()
1412
+ return dict(list(base_config.items()) + list(config.items()))
1413
+
1414
+ def set_previous(self, layer):
1415
+ self.previous = layer
1416
+
1417
+
1418
+ def add_shared_layer(layer, inputs):
1419
+ '''
1420
+ Use this function to add a shared layer across multiple Sequential models
1421
+ without merging the outputs
1422
+ '''
1423
+ input_layers = [l.layers[-1] for l in inputs]
1424
+ s = Siamese(layer, input_layers, merge_mode=None)
1425
+ for i in range(len(inputs)):
1426
+ sh = SiameseHead(i)
1427
+ inputs[i].add(s)
1428
+ inputs[i].add(sh)