keras 0.2.0__py3.5.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 (106) hide show
  1. EGG-INFO/PKG-INFO +11 -0
  2. EGG-INFO/SOURCES.txt +57 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/requires.txt +6 -0
  5. EGG-INFO/top_level.txt +2 -0
  6. EGG-INFO/zip-safe +1 -0
  7. keras/__init__.py +15 -0
  8. keras/__pycache__/__init__.cpython-35.pyc +0 -0
  9. keras/__pycache__/activations.cpython-35.pyc +0 -0
  10. keras/__pycache__/callbacks.cpython-35.pyc +0 -0
  11. keras/__pycache__/constraints.cpython-35.pyc +0 -0
  12. keras/__pycache__/initializations.cpython-35.pyc +0 -0
  13. keras/__pycache__/models.cpython-35.pyc +0 -0
  14. keras/__pycache__/objectives.cpython-35.pyc +0 -0
  15. keras/__pycache__/optimizers.cpython-35.pyc +0 -0
  16. keras/__pycache__/regularizers.cpython-35.pyc +0 -0
  17. keras/activations.py +44 -0
  18. keras/callbacks.py +293 -0
  19. keras/constraints.py +48 -0
  20. keras/datasets/__init__.py +0 -0
  21. keras/datasets/__pycache__/__init__.cpython-35.pyc +0 -0
  22. keras/datasets/__pycache__/cifar.cpython-35.pyc +0 -0
  23. keras/datasets/__pycache__/cifar10.cpython-35.pyc +0 -0
  24. keras/datasets/__pycache__/cifar100.cpython-35.pyc +0 -0
  25. keras/datasets/__pycache__/data_utils.cpython-35.pyc +0 -0
  26. keras/datasets/__pycache__/imdb.cpython-35.pyc +0 -0
  27. keras/datasets/__pycache__/mnist.cpython-35.pyc +0 -0
  28. keras/datasets/__pycache__/reuters.cpython-35.pyc +0 -0
  29. keras/datasets/cifar.py +22 -0
  30. keras/datasets/cifar10.py +31 -0
  31. keras/datasets/cifar100.py +28 -0
  32. keras/datasets/data_utils.py +50 -0
  33. keras/datasets/imdb.py +66 -0
  34. keras/datasets/mnist.py +23 -0
  35. keras/datasets/reuters.py +148 -0
  36. keras/initializations.py +89 -0
  37. keras/layers/__init__.py +0 -0
  38. keras/layers/__pycache__/__init__.cpython-35.pyc +0 -0
  39. keras/layers/__pycache__/advanced_activations.cpython-35.pyc +0 -0
  40. keras/layers/__pycache__/containers.cpython-35.pyc +0 -0
  41. keras/layers/__pycache__/convolutional.cpython-35.pyc +0 -0
  42. keras/layers/__pycache__/core.cpython-35.pyc +0 -0
  43. keras/layers/__pycache__/embeddings.cpython-35.pyc +0 -0
  44. keras/layers/__pycache__/noise.cpython-35.pyc +0 -0
  45. keras/layers/__pycache__/normalization.cpython-35.pyc +0 -0
  46. keras/layers/__pycache__/recurrent.cpython-35.pyc +0 -0
  47. keras/layers/advanced_activations.py +137 -0
  48. keras/layers/containers.py +318 -0
  49. keras/layers/convolutional.py +504 -0
  50. keras/layers/core.py +963 -0
  51. keras/layers/embeddings.py +153 -0
  52. keras/layers/noise.py +57 -0
  53. keras/layers/normalization.py +117 -0
  54. keras/layers/recurrent.py +837 -0
  55. keras/models.py +733 -0
  56. keras/objectives.py +67 -0
  57. keras/optimizers.py +228 -0
  58. keras/preprocessing/__init__.py +0 -0
  59. keras/preprocessing/__pycache__/__init__.cpython-35.pyc +0 -0
  60. keras/preprocessing/__pycache__/image.cpython-35.pyc +0 -0
  61. keras/preprocessing/__pycache__/sequence.cpython-35.pyc +0 -0
  62. keras/preprocessing/__pycache__/text.cpython-35.pyc +0 -0
  63. keras/preprocessing/image.py +251 -0
  64. keras/preprocessing/sequence.py +124 -0
  65. keras/preprocessing/text.py +176 -0
  66. keras/regularizers.py +84 -0
  67. keras/utils/__init__.py +0 -0
  68. keras/utils/__pycache__/__init__.cpython-35.pyc +0 -0
  69. keras/utils/__pycache__/generic_utils.cpython-35.pyc +0 -0
  70. keras/utils/__pycache__/io_utils.cpython-35.pyc +0 -0
  71. keras/utils/__pycache__/layer_utils.cpython-35.pyc +0 -0
  72. keras/utils/__pycache__/np_utils.cpython-35.pyc +0 -0
  73. keras/utils/__pycache__/test_utils.cpython-35.pyc +0 -0
  74. keras/utils/__pycache__/theano_utils.cpython-35.pyc +0 -0
  75. keras/utils/__pycache__/visualize_util.cpython-35.pyc +0 -0
  76. keras/utils/generic_utils.py +133 -0
  77. keras/utils/io_utils.py +71 -0
  78. keras/utils/layer_utils.py +129 -0
  79. keras/utils/np_utils.py +53 -0
  80. keras/utils/test_utils.py +27 -0
  81. keras/utils/theano_utils.py +44 -0
  82. keras/utils/visualize_util.py +41 -0
  83. keras/wrappers/__init__.py +0 -0
  84. keras/wrappers/__pycache__/__init__.cpython-35.pyc +0 -0
  85. keras/wrappers/__pycache__/scikit_learn.cpython-35.pyc +0 -0
  86. keras/wrappers/scikit_learn.py +266 -0
  87. tests/__init__.py +0 -0
  88. tests/__pycache__/__init__.cpython-35.pyc +0 -0
  89. tests/manual/__init__.py +0 -0
  90. tests/manual/__pycache__/__init__.cpython-35.pyc +0 -0
  91. tests/manual/__pycache__/check_autoencoder.cpython-35.pyc +0 -0
  92. tests/manual/__pycache__/check_callbacks.cpython-35.pyc +0 -0
  93. tests/manual/__pycache__/check_constraints.cpython-35.pyc +0 -0
  94. tests/manual/__pycache__/check_masked_recurrent.cpython-35.pyc +0 -0
  95. tests/manual/__pycache__/check_model_utils.cpython-35.pyc +0 -0
  96. tests/manual/__pycache__/check_save_weights.cpython-35.pyc +0 -0
  97. tests/manual/__pycache__/check_wrappers.cpython-35.pyc +0 -0
  98. tests/manual/__pycache__/check_yaml.cpython-35.pyc +0 -0
  99. tests/manual/check_autoencoder.py +134 -0
  100. tests/manual/check_callbacks.py +236 -0
  101. tests/manual/check_constraints.py +100 -0
  102. tests/manual/check_masked_recurrent.py +130 -0
  103. tests/manual/check_model_utils.py +44 -0
  104. tests/manual/check_save_weights.py +40 -0
  105. tests/manual/check_wrappers.py +126 -0
  106. tests/manual/check_yaml.py +101 -0
keras/layers/core.py ADDED
@@ -0,0 +1,963 @@
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import absolute_import, division
3
+
4
+ import theano
5
+ import theano.tensor as T
6
+ import numpy as np
7
+
8
+ from collections import OrderedDict
9
+ import copy
10
+
11
+ from .. import activations, initializations, regularizers, constraints
12
+ from ..utils.theano_utils import shared_zeros, floatX, ndim_tensor
13
+ from ..utils.generic_utils import make_tuple
14
+ from ..regularizers import ActivityRegularizer, Regularizer
15
+
16
+ from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
17
+ from six.moves import zip
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 = ndim_tensor(len(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 p.eval().shape != w.shape:
136
+ raise Exception("Layer shape %s not compatible with weight shape %s." % (p.eval().shape, w.shape))
137
+ p.set_value(floatX(w))
138
+
139
+ def get_weights(self):
140
+ weights = []
141
+ for p in self.params:
142
+ weights.append(p.get_value())
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 set_name(self, name):
179
+ for i in range(len(self.params)):
180
+ self.params[i].name = '%s_p%d' % (name, i)
181
+
182
+ def count_params(self):
183
+ return sum([np.prod(p.shape.eval()) for p in self.params])
184
+
185
+
186
+ class MaskedLayer(Layer):
187
+ '''
188
+ If your layer trivially supports masking (by simply copying the input mask to the output), then subclass MaskedLayer
189
+ instead of Layer, and make sure that you incorporate the input mask into your calculation of get_output()
190
+ '''
191
+ def supports_masked_input(self):
192
+ return True
193
+
194
+ def get_input_mask(self, train=False):
195
+ if hasattr(self, 'previous'):
196
+ return self.previous.get_output_mask(train)
197
+ else:
198
+ return None
199
+
200
+ def get_output_mask(self, train=False):
201
+ ''' The default output mask is just the input mask unchanged. Override this in your own
202
+ implementations if, 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 = T.tensor3()
221
+
222
+ def get_output_mask(self, train=False):
223
+ X = self.get_input(train)
224
+ return T.any(T.ones_like(X) * (1. - T.eq(X, self.mask_value)), axis=-1)
225
+
226
+ def get_output(self, train=False):
227
+ X = self.get_input(train)
228
+ return X * T.shape_padright(T.any((1. - T.eq(X, self.mask_value)), axis=-1))
229
+
230
+ def get_config(self):
231
+ config = {"name": self.__class__.__name__,
232
+ "mask_value": self.mask_value}
233
+ base_config = super(Masking, self).get_config()
234
+ return dict(list(base_config.items()) + list(config.items()))
235
+
236
+
237
+ class TimeDistributedMerge(Layer):
238
+ '''Sum/multiply/average over the outputs of a TimeDistributed layer.
239
+
240
+ mode: {'sum', 'mul', 'ave'}
241
+ Tensor input dimensions: (nb_sample, time, features)
242
+ Tensor output dimensions: (nb_sample, features)
243
+ '''
244
+ input_ndim = 3
245
+
246
+ def __init__(self, mode='sum', **kwargs):
247
+ super(TimeDistributedMerge, self).__init__(**kwargs)
248
+ self.mode = mode
249
+ self.params = []
250
+ self.regularizers = []
251
+ self.constraints = []
252
+ self.updates = []
253
+
254
+ @property
255
+ def output_shape(self):
256
+ return (None, self.input_shape[2])
257
+
258
+ def get_output(self, train=False):
259
+ X = self.get_input(train)
260
+ if self.mode == 'sum' or self.mode == 'ave':
261
+ s = theano.tensor.sum(X, axis=1)
262
+ if self.mode == 'ave':
263
+ s /= X.shape[1]
264
+ return s
265
+ elif self.mode == 'mul':
266
+ s = theano.tensor.mul(X, axis=1)
267
+ return s
268
+ else:
269
+ raise Exception('Unknown merge mode')
270
+
271
+ def get_config(self):
272
+ config = {"name": self.__class__.__name__,
273
+ "mode": self.mode}
274
+ base_config = super(TimeDistributedMerge, self).get_config()
275
+ return dict(list(base_config.items()) + list(config.items()))
276
+
277
+
278
+ class Merge(Layer):
279
+ def __init__(self, layers, mode='sum', concat_axis=-1, dot_axes=-1):
280
+ ''' Merge the output of a list of layers or containers into a single tensor.
281
+ mode: {'sum', 'mul', 'concat', 'ave', 'join'}
282
+ '''
283
+ if len(layers) < 2:
284
+ raise Exception("Please specify two or more input layers (or containers) to merge")
285
+
286
+ if mode not in {'sum', 'mul', 'concat', 'ave', 'join', 'cos', 'dot'}:
287
+ raise Exception("Invalid merge mode: " + str(mode))
288
+
289
+ if mode in {'sum', 'mul', 'ave', 'cos'}:
290
+ input_shapes = set([l.output_shape for l in layers])
291
+ if len(input_shapes) > 1:
292
+ raise Exception("Only layers of same output shape can be merged using " + mode + " mode. " +
293
+ "Layer shapes: %s" % ([l.output_shape for l in layers]))
294
+ if mode in {'cos', 'dot'}:
295
+ if len(layers) > 2:
296
+ raise Exception(mode + " merge takes exactly 2 layers")
297
+ shape1 = layers[0].output_shape
298
+ shape2 = layers[1].output_shape
299
+ n1 = len(shape1)
300
+ n2 = len(shape2)
301
+ if mode == 'dot':
302
+ if type(dot_axes) == int:
303
+ if dot_axes < 0:
304
+ dot_axes = [range(dot_axes % n1, n1), range(dot_axes % n2, n2)]
305
+ else:
306
+ dot_axes = [range(n1 - dot_axes, n2), range(1, dot_axes + 1)]
307
+ if type(dot_axes) not in [list, tuple]:
308
+ raise Exception("Invalid type for dot_axes - should be a list.")
309
+ if len(dot_axes) != 2:
310
+ raise Exception("Invalid format for dot_axes - should contain two elements.")
311
+ if type(dot_axes[0]) not in [list, tuple, range] or type(dot_axes[1]) not in [list, tuple, range]:
312
+ raise Exception("Invalid format for dot_axes - list elements should have type 'list' or 'tuple'.")
313
+ for i in range(len(dot_axes[0])):
314
+ if shape1[dot_axes[0][i]] != shape2[dot_axes[1][i]]:
315
+ raise Exception("Dimension incompatibility using dot mode: " +
316
+ "%s != %s. " % (shape1[dot_axes[0][i]], shape2[dot_axes[1][i]]) +
317
+ "Layer shapes: %s, %s" % (shape1, shape2))
318
+ elif mode == 'concat':
319
+ input_shapes = set()
320
+ for l in layers:
321
+ oshape = list(l.output_shape)
322
+ oshape.pop(concat_axis)
323
+ oshape = tuple(oshape)
324
+ input_shapes.add(oshape)
325
+ if len(input_shapes) > 1:
326
+ raise Exception("'concat' mode can only merge layers with matching " +
327
+ "output shapes except for the concat axis. " +
328
+ "Layer shapes: %s" % ([l.output_shape for l in layers]))
329
+
330
+ self.mode = mode
331
+ self.concat_axis = concat_axis
332
+ self.dot_axes = dot_axes
333
+ self.layers = layers
334
+ self.params = []
335
+ self.regularizers = []
336
+ self.constraints = []
337
+ self.updates = []
338
+ for l in self.layers:
339
+ params, regs, consts, updates = l.get_params()
340
+ self.regularizers += regs
341
+ self.updates += updates
342
+ # params and constraints have the same size
343
+ for p, c in zip(params, consts):
344
+ if p not in self.params:
345
+ self.params.append(p)
346
+ self.constraints.append(c)
347
+
348
+ @property
349
+ def output_shape(self):
350
+ input_shapes = [layer.output_shape for layer in self.layers]
351
+ if self.mode in ['sum', 'mul', 'ave']:
352
+ return input_shapes[0]
353
+ elif self.mode == 'concat':
354
+ output_shape = list(input_shapes[0])
355
+ for shape in input_shapes[1:]:
356
+ output_shape[self.concat_axis] += shape[self.concat_axis]
357
+ return tuple(output_shape)
358
+ elif self.mode == 'join':
359
+ return None
360
+ elif self.mode == 'dot':
361
+ shape1 = list(input_shapes[0])
362
+ shape2 = list(input_shapes[1])
363
+ dot_axes = []
364
+ for axes in self.dot_axes:
365
+ dot_axes.append([index-1 for index in axes])
366
+ tensordot_output = np.tensordot(np.zeros(tuple(shape1[1:])),
367
+ np.zeros(tuple(shape2[1:])),
368
+ axes=dot_axes)
369
+ if len(tensordot_output.shape) == 0:
370
+ shape = (1,)
371
+ else:
372
+ shape = tensordot_output.shape
373
+ return (shape1[0],) + shape
374
+ elif self.mode == 'cos':
375
+ return tuple(input_shapes[0][0], 1)
376
+
377
+ def get_params(self):
378
+ return self.params, self.regularizers, self.constraints, self.updates
379
+
380
+ def get_output(self, train=False):
381
+ if self.mode == 'sum' or self.mode == 'ave':
382
+ s = self.layers[0].get_output(train)
383
+ for i in range(1, len(self.layers)):
384
+ s += self.layers[i].get_output(train)
385
+ if self.mode == 'ave':
386
+ s /= len(self.layers)
387
+ return s
388
+ elif self.mode == 'concat':
389
+ inputs = [self.layers[i].get_output(train) for i in range(len(self.layers))]
390
+ return T.concatenate(inputs, axis=self.concat_axis)
391
+ elif self.mode == 'join':
392
+ inputs = OrderedDict()
393
+ for i in range(len(self.layers)):
394
+ X = self.layers[i].get_output(train)
395
+ if X.name is None:
396
+ raise ValueError("merge_mode='join' only works with named inputs")
397
+ else:
398
+ inputs[X.name] = X
399
+ return inputs
400
+ elif self.mode == 'mul':
401
+ s = self.layers[0].get_output(train)
402
+ for i in range(1, len(self.layers)):
403
+ s *= self.layers[i].get_output(train)
404
+ return s
405
+ elif self.mode == 'dot':
406
+ l1 = self.layers[0].get_output(train)
407
+ l2 = self.layers[1].get_output(train)
408
+ output = T.batched_tensordot(l1, l2, self.dot_axes)
409
+ output_shape = list(self.output_shape)
410
+ output_shape[0] = l1.shape[0]
411
+ output = output.reshape(tuple(output_shape))
412
+ return output
413
+ elif self.mode == 'cos':
414
+ l1 = self.layers[0].get_output(train)
415
+ l2 = self.layers[1].get_output(train)
416
+ output, _ = theano.scan(lambda v1, v2: T.dot(v1, v2) / T.sqrt(T.dot(v1, v1) * T.dot(v2, v2)),
417
+ sequences=[l1, l2],
418
+ outputs_info=None)
419
+ return output
420
+ else:
421
+ raise Exception('Unknown merge mode')
422
+
423
+ def get_input(self, train=False):
424
+ res = []
425
+ for i in range(len(self.layers)):
426
+ o = self.layers[i].get_input(train)
427
+ if not type(o) == list:
428
+ o = [o]
429
+ for output in o:
430
+ if output not in res:
431
+ res.append(output)
432
+ return res
433
+
434
+ @property
435
+ def input(self):
436
+ return self.get_input()
437
+
438
+ def supports_masked_input(self):
439
+ return False
440
+
441
+ def get_output_mask(self, train=None):
442
+ return None
443
+
444
+ def get_weights(self):
445
+ weights = []
446
+ for l in self.layers:
447
+ weights += l.get_weights()
448
+ return weights
449
+
450
+ def set_weights(self, weights):
451
+ for i in range(len(self.layers)):
452
+ nb_param = len(self.layers[i].params)
453
+ self.layers[i].set_weights(weights[:nb_param])
454
+ weights = weights[nb_param:]
455
+
456
+ def get_config(self):
457
+ config = {"name": self.__class__.__name__,
458
+ "layers": [l.get_config() for l in self.layers],
459
+ "mode": self.mode,
460
+ "concat_axis": self.concat_axis,
461
+ "dot_axes": self.dot_axes}
462
+ base_config = super(Merge, self).get_config()
463
+ return dict(list(base_config.items()) + list(config.items()))
464
+
465
+
466
+ class Dropout(MaskedLayer):
467
+ '''
468
+ Hinton's dropout.
469
+ '''
470
+ def __init__(self, p, **kwargs):
471
+ super(Dropout, self).__init__(**kwargs)
472
+ self.p = p
473
+ self.srng = RandomStreams(seed=np.random.randint(10e6))
474
+
475
+ def get_output(self, train=False):
476
+ X = self.get_input(train)
477
+ if self.p > 0.:
478
+ retain_prob = 1. - self.p
479
+ if train:
480
+ X *= self.srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX) / retain_prob
481
+ return X
482
+
483
+ def get_config(self):
484
+ config = {"name": self.__class__.__name__,
485
+ "p": self.p}
486
+ base_config = super(Dropout, self).get_config()
487
+ return dict(list(base_config.items()) + list(config.items()))
488
+
489
+
490
+ class Activation(MaskedLayer):
491
+ '''
492
+ Apply an activation function to an output.
493
+ '''
494
+ def __init__(self, activation, target=0, beta=0.1, **kwargs):
495
+ super(Activation, self).__init__(**kwargs)
496
+ self.activation = activations.get(activation)
497
+ self.target = target
498
+ self.beta = beta
499
+
500
+ def get_output(self, train=False):
501
+ X = self.get_input(train)
502
+ return self.activation(X)
503
+
504
+ def get_config(self):
505
+ config = {"name": self.__class__.__name__,
506
+ "activation": self.activation.__name__,
507
+ "target": self.target,
508
+ "beta": self.beta}
509
+ base_config = super(Activation, self).get_config()
510
+ return dict(list(base_config.items()) + list(config.items()))
511
+
512
+
513
+ class Reshape(Layer):
514
+ '''
515
+ Reshape an output to a certain shape.
516
+ Can't be used as first layer in a model (no fixed input!)
517
+ First dimension is assumed to be nb_samples.
518
+ '''
519
+ def __init__(self, dims, **kwargs):
520
+ super(Reshape, self).__init__(**kwargs)
521
+ self.dims = tuple(dims)
522
+
523
+ @property
524
+ def output_shape(self):
525
+ return (self.input_shape[0],) + self.dims
526
+
527
+ def get_output(self, train=False):
528
+ X = self.get_input(train)
529
+ new_shape = (X.shape[0],) + self.dims
530
+ return theano.tensor.reshape(X, new_shape)
531
+
532
+ def get_config(self):
533
+ config = {"name": self.__class__.__name__,
534
+ "dims": self.dims}
535
+ base_config = super(Reshape, self).get_config()
536
+ return dict(list(base_config.items()) + list(config.items()))
537
+
538
+
539
+ class Permute(Layer):
540
+ '''
541
+ Permute the dimensions of the input according to the given tuple.
542
+ '''
543
+ def __init__(self, dims, **kwargs):
544
+ super(Permute, self).__init__(**kwargs)
545
+ self.dims = tuple(dims)
546
+
547
+ @property
548
+ def output_shape(self):
549
+ input_shape = list(self.input_shape)
550
+ output_shape = copy.copy(input_shape)
551
+ for i, dim in enumerate(self.dims):
552
+ target_dim = input_shape[dim]
553
+ output_shape[i+1] = target_dim
554
+ return tuple(output_shape)
555
+
556
+ def get_output(self, train=False):
557
+ X = self.get_input(train)
558
+ return X.dimshuffle((0,) + self.dims)
559
+
560
+ def get_config(self):
561
+ config = {"name": self.__class__.__name__,
562
+ "dims": self.dims}
563
+ base_config = super(Permute, self).get_config()
564
+ return dict(list(base_config.items()) + list(config.items()))
565
+
566
+
567
+ class Flatten(Layer):
568
+ '''
569
+ Reshape input to flat shape.
570
+ First dimension is assumed to be nb_samples.
571
+ '''
572
+ def __init__(self, **kwargs):
573
+ super(Flatten, self).__init__(**kwargs)
574
+
575
+ @property
576
+ def output_shape(self):
577
+ input_shape = self.input_shape
578
+ return (input_shape[0], np.prod(input_shape[1:]))
579
+
580
+ def get_output(self, train=False):
581
+ X = self.get_input(train)
582
+ size = theano.tensor.prod(X.shape) // X.shape[0]
583
+ nshape = (X.shape[0], size)
584
+ return theano.tensor.reshape(X, nshape)
585
+
586
+
587
+ class RepeatVector(Layer):
588
+ '''
589
+ Repeat input n times.
590
+
591
+ Dimensions of input are assumed to be (nb_samples, dim).
592
+ Return tensor of shape (nb_samples, n, dim).
593
+ '''
594
+ def __init__(self, n, **kwargs):
595
+ super(RepeatVector, self).__init__(**kwargs)
596
+ self.n = n
597
+
598
+ @property
599
+ def output_shape(self):
600
+ input_shape = self.input_shape
601
+ return (input_shape[0], self.n, input_shape[1])
602
+
603
+ def get_output(self, train=False):
604
+ X = self.get_input(train)
605
+ tensors = [X]*self.n
606
+ stacked = theano.tensor.stack(*tensors)
607
+ return stacked.dimshuffle((1, 0, 2))
608
+
609
+ def get_config(self):
610
+ config = {"name": self.__class__.__name__,
611
+ "n": self.n}
612
+ base_config = super(RepeatVector, self).get_config()
613
+ return dict(list(base_config.items()) + list(config.items()))
614
+
615
+
616
+ class Dense(Layer):
617
+ '''
618
+ Just your regular fully connected NN layer.
619
+ '''
620
+ input_ndim = 2
621
+
622
+ def __init__(self, output_dim, init='glorot_uniform', activation='linear', weights=None,
623
+ W_regularizer=None, b_regularizer=None, activity_regularizer=None,
624
+ W_constraint=None, b_constraint=None, input_dim=None, **kwargs):
625
+ self.init = initializations.get(init)
626
+ self.activation = activations.get(activation)
627
+ self.output_dim = output_dim
628
+
629
+ self.W_regularizer = regularizers.get(W_regularizer)
630
+ self.b_regularizer = regularizers.get(b_regularizer)
631
+ self.activity_regularizer = regularizers.get(activity_regularizer)
632
+
633
+ self.W_constraint = constraints.get(W_constraint)
634
+ self.b_constraint = constraints.get(b_constraint)
635
+ self.constraints = [self.W_constraint, self.b_constraint]
636
+
637
+ self.initial_weights = weights
638
+
639
+ self.input_dim = input_dim
640
+ if self.input_dim:
641
+ kwargs['input_shape'] = (self.input_dim,)
642
+ super(Dense, self).__init__(**kwargs)
643
+
644
+ def build(self):
645
+ input_dim = self.input_shape[1]
646
+
647
+ self.input = T.matrix()
648
+ self.W = self.init((input_dim, self.output_dim))
649
+ self.b = shared_zeros((self.output_dim,))
650
+
651
+ self.params = [self.W, self.b]
652
+
653
+ self.regularizers = []
654
+ if self.W_regularizer:
655
+ self.W_regularizer.set_param(self.W)
656
+ self.regularizers.append(self.W_regularizer)
657
+
658
+ if self.b_regularizer:
659
+ self.b_regularizer.set_param(self.b)
660
+ self.regularizers.append(self.b_regularizer)
661
+
662
+ if self.activity_regularizer:
663
+ self.activity_regularizer.set_layer(self)
664
+ self.regularizers.append(self.activity_regularizer)
665
+
666
+ if self.initial_weights is not None:
667
+ self.set_weights(self.initial_weights)
668
+ del self.initial_weights
669
+
670
+ @property
671
+ def output_shape(self):
672
+ return (self.input_shape[0], self.output_dim)
673
+
674
+ def get_output(self, train=False):
675
+ X = self.get_input(train)
676
+ output = self.activation(T.dot(X, self.W) + self.b)
677
+ return output
678
+
679
+ def get_config(self):
680
+ config = {"name": self.__class__.__name__,
681
+ "output_dim": self.output_dim,
682
+ "init": self.init.__name__,
683
+ "activation": self.activation.__name__,
684
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
685
+ "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None,
686
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
687
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None,
688
+ "b_constraint": self.b_constraint.get_config() if self.b_constraint else None,
689
+ "input_dim": self.input_dim}
690
+ base_config = super(Dense, self).get_config()
691
+ return dict(list(base_config.items()) + list(config.items()))
692
+
693
+
694
+ class ActivityRegularization(Layer):
695
+ '''
696
+ Layer that passes through its input unchanged, but applies an update
697
+ to the cost function based on the activity.
698
+ '''
699
+ def __init__(self, l1=0., l2=0., **kwargs):
700
+ super(ActivityRegularization, self).__init__(**kwargs)
701
+ self.l1 = l1
702
+ self.l2 = l2
703
+
704
+ activity_regularizer = ActivityRegularizer(l1=l1, l2=l2)
705
+ activity_regularizer.set_layer(self)
706
+ self.regularizers = [activity_regularizer]
707
+
708
+ def get_output(self, train=False):
709
+ return self.get_input(train)
710
+
711
+ def get_config(self):
712
+ config = {"name": self.__class__.__name__,
713
+ "l1": self.l1,
714
+ "l2": self.l2}
715
+ base_config = super(ActivityRegularization, self).get_config()
716
+ return dict(list(base_config.items()) + list(config.items()))
717
+
718
+
719
+ class TimeDistributedDense(MaskedLayer):
720
+ '''
721
+ Apply a same Dense layer for each dimension[1] (time_dimension) input.
722
+ Especially useful after a recurrent network with 'return_sequence=True'.
723
+ Tensor input dimensions: (nb_sample, time_dimension, input_dim)
724
+ Tensor output dimensions: (nb_sample, time_dimension, output_dim)
725
+
726
+ '''
727
+ input_ndim = 3
728
+
729
+ def __init__(self, output_dim, init='glorot_uniform', activation='linear', weights=None,
730
+ W_regularizer=None, b_regularizer=None, activity_regularizer=None,
731
+ W_constraint=None, b_constraint=None, input_dim=None, input_length=None, **kwargs):
732
+ self.output_dim = output_dim
733
+ self.init = initializations.get(init)
734
+ self.activation = activations.get(activation)
735
+
736
+ self.W_regularizer = regularizers.get(W_regularizer)
737
+ self.b_regularizer = regularizers.get(b_regularizer)
738
+ self.activity_regularizer = regularizers.get(activity_regularizer)
739
+
740
+ self.W_constraint = constraints.get(W_constraint)
741
+ self.b_constraint = constraints.get(b_constraint)
742
+ self.constraints = [self.W_constraint, self.b_constraint]
743
+
744
+ self.initial_weights = weights
745
+
746
+ self.input_dim = input_dim
747
+ self.input_length = input_length
748
+ if self.input_dim:
749
+ kwargs['input_shape'] = (self.input_length, self.input_dim)
750
+ super(TimeDistributedDense, self).__init__(**kwargs)
751
+
752
+ def build(self):
753
+ input_dim = self.input_shape[2]
754
+
755
+ self.input = T.tensor3()
756
+ self.W = self.init((input_dim, self.output_dim))
757
+ self.b = shared_zeros((self.output_dim))
758
+
759
+ self.params = [self.W, self.b]
760
+ self.regularizers = []
761
+
762
+ if self.W_regularizer:
763
+ self.W_regularizer.set_param(self.W)
764
+ self.regularizers.append(self.W_regularizer)
765
+
766
+ if self.b_regularizer:
767
+ self.b_regularizer.set_param(self.b)
768
+ self.regularizers.append(self.b_regularizer)
769
+
770
+ if self.activity_regularizer:
771
+ self.activity_regularizer.set_layer(self)
772
+ self.regularizers.append(self.activity_regularizer)
773
+
774
+ if self.initial_weights is not None:
775
+ self.set_weights(self.initial_weights)
776
+ del self.initial_weights
777
+
778
+ @property
779
+ def output_shape(self):
780
+ input_shape = self.input_shape
781
+ return (input_shape[0], input_shape[1], self.output_dim)
782
+
783
+ def get_output(self, train=False):
784
+ X = self.get_input(train)
785
+ output = self.activation(T.dot(X.dimshuffle(1, 0, 2), self.W) + self.b)
786
+ return output.dimshuffle(1, 0, 2)
787
+
788
+ def get_config(self):
789
+ config = {"name": self.__class__.__name__,
790
+ "output_dim": self.output_dim,
791
+ "init": self.init.__name__,
792
+ "activation": self.activation.__name__,
793
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
794
+ "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None,
795
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
796
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None,
797
+ "b_constraint": self.b_constraint.get_config() if self.b_constraint else None,
798
+ "input_dim": self.input_dim,
799
+ "input_length": self.input_length}
800
+ base_config = super(TimeDistributedDense, self).get_config()
801
+ return dict(list(base_config.items()) + list(config.items()))
802
+
803
+
804
+ class AutoEncoder(Layer):
805
+ '''A customizable autoencoder model.
806
+
807
+ Tensor input dimensions: same as encoder input
808
+ Tensor output dimensions:
809
+ if output_reconstruction:
810
+ same as encoder output
811
+ else:
812
+ same as decoder output
813
+ '''
814
+ def __init__(self, encoder, decoder, output_reconstruction=True, weights=None, **kwargs):
815
+ super(AutoEncoder, self).__init__(**kwargs)
816
+
817
+ self.output_reconstruction = output_reconstruction
818
+ self.encoder = encoder
819
+ self.decoder = decoder
820
+
821
+ self.decoder.set_previous(self.encoder)
822
+
823
+ self.params = []
824
+ self.regularizers = []
825
+ self.constraints = []
826
+ self.updates = []
827
+ for layer in [self.encoder, self.decoder]:
828
+ params, regularizers, constraints, updates = layer.get_params()
829
+ self.regularizers += regularizers
830
+ self.updates += updates
831
+ for p, c in zip(params, constraints):
832
+ if p not in self.params:
833
+ self.params.append(p)
834
+ self.constraints.append(c)
835
+
836
+ if weights is not None:
837
+ self.set_weights(weights)
838
+
839
+ def set_previous(self, node):
840
+ self.encoder.set_previous(node)
841
+
842
+ def get_weights(self):
843
+ weights = []
844
+ for layer in [self.encoder, self.decoder]:
845
+ weights += layer.get_weights()
846
+ return weights
847
+
848
+ def set_weights(self, weights):
849
+ nb_param = len(self.encoder.params)
850
+ self.encoder.set_weights(weights[:nb_param])
851
+ self.decoder.set_weights(weights[nb_param:])
852
+
853
+ def get_input(self, train=False):
854
+ return self.encoder.get_input(train)
855
+
856
+ @property
857
+ def input(self):
858
+ return self.encoder.input
859
+
860
+ def _get_hidden(self, train=False):
861
+ return self.encoder.get_output(train)
862
+
863
+ @property
864
+ def input_shape(self):
865
+ self.encoder.previous.output_shape
866
+
867
+ @property
868
+ def output_shape(self):
869
+ if self.output_reconstruction:
870
+ return self.encoder.previous.output_shape
871
+ else:
872
+ return self.decoder.previous.output_shape
873
+
874
+ def get_output(self, train=False):
875
+ if not train and not self.output_reconstruction:
876
+ return self.encoder.get_output(train)
877
+
878
+ return self.decoder.get_output(train)
879
+
880
+ def get_config(self):
881
+ return {"name": self.__class__.__name__,
882
+ "encoder_config": self.encoder.get_config(),
883
+ "decoder_config": self.decoder.get_config(),
884
+ "output_reconstruction": self.output_reconstruction}
885
+
886
+
887
+ class MaxoutDense(Layer):
888
+ '''
889
+ Max-out layer, nb_feature is the number of pieces in the piecewise linear approx.
890
+ Refer to http://arxiv.org/pdf/1302.4389.pdf
891
+ '''
892
+ input_ndim = 2
893
+
894
+ def __init__(self, output_dim, nb_feature=4, init='glorot_uniform', weights=None,
895
+ W_regularizer=None, b_regularizer=None, activity_regularizer=None,
896
+ W_constraint=None, b_constraint=None, input_dim=None, **kwargs):
897
+ self.output_dim = output_dim
898
+ self.nb_feature = nb_feature
899
+ self.init = initializations.get(init)
900
+
901
+ self.W_regularizer = regularizers.get(W_regularizer)
902
+ self.b_regularizer = regularizers.get(b_regularizer)
903
+ self.activity_regularizer = regularizers.get(activity_regularizer)
904
+
905
+ self.W_constraint = constraints.get(W_constraint)
906
+ self.b_constraint = constraints.get(b_constraint)
907
+ self.constraints = [self.W_constraint, self.b_constraint]
908
+
909
+ self.initial_weights = weights
910
+ self.input_dim = input_dim
911
+ if self.input_dim:
912
+ kwargs['input_shape'] = (self.input_dim,)
913
+ super(MaxoutDense, self).__init__(**kwargs)
914
+
915
+ def build(self):
916
+ input_dim = self.input_shape[1]
917
+
918
+ self.input = T.matrix()
919
+ self.W = self.init((self.nb_feature, input_dim, self.output_dim))
920
+ self.b = shared_zeros((self.nb_feature, self.output_dim))
921
+
922
+ self.params = [self.W, self.b]
923
+ self.regularizers = []
924
+
925
+ if self.W_regularizer:
926
+ self.W_regularizer.set_param(self.W)
927
+ self.regularizers.append(self.W_regularizer)
928
+
929
+ if self.b_regularizer:
930
+ self.b_regularizer.set_param(self.b)
931
+ self.regularizers.append(self.b_regularizer)
932
+
933
+ if self.activity_regularizer:
934
+ self.activity_regularizer.set_layer(self)
935
+ self.regularizers.append(self.activity_regularizer)
936
+
937
+ if self.initial_weights is not None:
938
+ self.set_weights(self.initial_weights)
939
+ del self.initial_weights
940
+
941
+ @property
942
+ def output_shape(self):
943
+ return (self.input_shape[0], self.output_dim)
944
+
945
+ def get_output(self, train=False):
946
+ X = self.get_input(train)
947
+ # -- don't need activation since it's just linear.
948
+ output = T.max(T.dot(X, self.W) + self.b, axis=1)
949
+ return output
950
+
951
+ def get_config(self):
952
+ config = {"name": self.__class__.__name__,
953
+ "output_dim": self.output_dim,
954
+ "init": self.init.__name__,
955
+ "nb_feature": self.nb_feature,
956
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
957
+ "b_regularizer": self.b_regularizer.get_config() if self.b_regularizer else None,
958
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
959
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None,
960
+ "b_constraint": self.b_constraint.get_config() if self.b_constraint else None,
961
+ "input_dim": self.input_dim}
962
+ base_config = super(MaxoutDense, self).get_config()
963
+ return dict(list(base_config.items()) + list(config.items()))