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.
- EGG-INFO/PKG-INFO +11 -0
- EGG-INFO/SOURCES.txt +51 -0
- EGG-INFO/dependency_links.txt +1 -0
- EGG-INFO/requires.txt +6 -0
- EGG-INFO/top_level.txt +1 -0
- EGG-INFO/zip-safe +1 -0
- keras/__init__.py +15 -0
- keras/__init__.pyc +0 -0
- keras/activations.py +49 -0
- keras/activations.pyc +0 -0
- keras/backend/__init__.py +39 -0
- keras/backend/__init__.pyc +0 -0
- keras/backend/common.py +31 -0
- keras/backend/common.pyc +0 -0
- keras/backend/tensorflow_backend.py +602 -0
- keras/backend/tensorflow_backend.pyc +0 -0
- keras/backend/theano_backend.py +622 -0
- keras/backend/theano_backend.pyc +0 -0
- keras/callbacks.py +295 -0
- keras/callbacks.pyc +0 -0
- keras/constraints.py +45 -0
- keras/constraints.pyc +0 -0
- keras/datasets/__init__.py +0 -0
- keras/datasets/__init__.pyc +0 -0
- keras/datasets/cifar.py +22 -0
- keras/datasets/cifar.pyc +0 -0
- keras/datasets/cifar10.py +31 -0
- keras/datasets/cifar10.pyc +0 -0
- keras/datasets/cifar100.py +28 -0
- keras/datasets/cifar100.pyc +0 -0
- keras/datasets/data_utils.py +50 -0
- keras/datasets/data_utils.pyc +0 -0
- keras/datasets/imdb.py +66 -0
- keras/datasets/imdb.pyc +0 -0
- keras/datasets/mnist.py +23 -0
- keras/datasets/mnist.pyc +0 -0
- keras/datasets/reuters.py +148 -0
- keras/datasets/reuters.pyc +0 -0
- keras/initializations.py +86 -0
- keras/initializations.pyc +0 -0
- keras/layers/__init__.py +0 -0
- keras/layers/__init__.pyc +0 -0
- keras/layers/advanced_activations.py +156 -0
- keras/layers/advanced_activations.pyc +0 -0
- keras/layers/containers.py +405 -0
- keras/layers/containers.pyc +0 -0
- keras/layers/convolutional.py +505 -0
- keras/layers/convolutional.pyc +0 -0
- keras/layers/core.py +1428 -0
- keras/layers/core.pyc +0 -0
- keras/layers/embeddings.py +88 -0
- keras/layers/embeddings.pyc +0 -0
- keras/layers/noise.py +55 -0
- keras/layers/noise.pyc +0 -0
- keras/layers/normalization.py +123 -0
- keras/layers/normalization.pyc +0 -0
- keras/layers/ntm.py +326 -0
- keras/layers/ntm.pyc +0 -0
- keras/layers/recurrent.py +354 -0
- keras/layers/recurrent.pyc +0 -0
- keras/models.py +743 -0
- keras/models.pyc +0 -0
- keras/objectives.py +59 -0
- keras/objectives.pyc +0 -0
- keras/optimizers.py +229 -0
- keras/optimizers.pyc +0 -0
- keras/preprocessing/__init__.py +0 -0
- keras/preprocessing/__init__.pyc +0 -0
- keras/preprocessing/image.py +246 -0
- keras/preprocessing/image.pyc +0 -0
- keras/preprocessing/sequence.py +124 -0
- keras/preprocessing/sequence.pyc +0 -0
- keras/preprocessing/text.py +176 -0
- keras/preprocessing/text.pyc +0 -0
- keras/regularizers.py +86 -0
- keras/regularizers.pyc +0 -0
- keras/utils/__init__.py +0 -0
- keras/utils/__init__.pyc +0 -0
- keras/utils/generic_utils.py +133 -0
- keras/utils/generic_utils.pyc +0 -0
- keras/utils/io_utils.py +71 -0
- keras/utils/io_utils.pyc +0 -0
- keras/utils/layer_utils.py +93 -0
- keras/utils/layer_utils.pyc +0 -0
- keras/utils/np_utils.py +53 -0
- keras/utils/np_utils.pyc +0 -0
- keras/utils/test_utils.py +27 -0
- keras/utils/test_utils.pyc +0 -0
- keras/utils/theano_utils.py +44 -0
- keras/utils/theano_utils.pyc +0 -0
- keras/utils/visualize_util.py +41 -0
- keras/utils/visualize_util.pyc +0 -0
- keras/wrappers/__init__.py +0 -0
- keras/wrappers/__init__.pyc +0 -0
- keras/wrappers/scikit_learn.py +266 -0
- keras/wrappers/scikit_learn.pyc +0 -0
- tests/__init__.py +0 -0
- tests/__init__.pyc +0 -0
- tests/manual/__init__.py +0 -0
- tests/manual/__init__.pyc +0 -0
- tests/manual/check_autoencoder.py +134 -0
- tests/manual/check_autoencoder.pyc +0 -0
- tests/manual/check_callbacks.py +236 -0
- tests/manual/check_callbacks.pyc +0 -0
- tests/manual/check_constraints.py +100 -0
- tests/manual/check_constraints.pyc +0 -0
- tests/manual/check_masked_recurrent.py +130 -0
- tests/manual/check_masked_recurrent.pyc +0 -0
- tests/manual/check_model_utils.py +44 -0
- tests/manual/check_model_utils.pyc +0 -0
- tests/manual/check_save_weights.py +40 -0
- tests/manual/check_save_weights.pyc +0 -0
- tests/manual/check_wrappers.py +126 -0
- tests/manual/check_wrappers.pyc +0 -0
- tests/manual/check_yaml.py +101 -0
- tests/manual/check_yaml.pyc +0 -0
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import theano
|
|
2
|
+
from theano import tensor as T
|
|
3
|
+
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
|
|
4
|
+
from theano.tensor.signal import downsample
|
|
5
|
+
import numpy as np
|
|
6
|
+
from .common import _FLOATX, _EPSILON
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# INTERNAL UTILS
|
|
10
|
+
theano.config.floatX = _FLOATX
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _on_gpu():
|
|
14
|
+
'''Returns whether the session is set to
|
|
15
|
+
run on GPU or not (i.e. on CPU).
|
|
16
|
+
'''
|
|
17
|
+
return theano.config.device[:3] == 'gpu'
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
if _on_gpu():
|
|
21
|
+
'''Import cuDNN only if running on GPU:
|
|
22
|
+
not having Cuda install should not
|
|
23
|
+
prevent from running the present code.
|
|
24
|
+
'''
|
|
25
|
+
from theano.sandbox.cuda import dnn
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# VARIABLE MANIPULATION
|
|
29
|
+
|
|
30
|
+
def variable(value, dtype=_FLOATX, name=None):
|
|
31
|
+
'''Instantiate a tensor variable.
|
|
32
|
+
'''
|
|
33
|
+
value = np.asarray(value, dtype=dtype)
|
|
34
|
+
return theano.shared(value=value, name=name, strict=False)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None):
|
|
38
|
+
'''Instantiate an input data placeholder variable.
|
|
39
|
+
'''
|
|
40
|
+
if shape is None and ndim is None:
|
|
41
|
+
raise Exception('Specify either a shape or ndim value.')
|
|
42
|
+
if shape is not None:
|
|
43
|
+
ndim = len(shape)
|
|
44
|
+
if ndim == 0:
|
|
45
|
+
return T.scalar(name=name, dtype=dtype)
|
|
46
|
+
elif ndim == 1:
|
|
47
|
+
return T.vector(name=name, dtype=dtype)
|
|
48
|
+
elif ndim == 2:
|
|
49
|
+
return T.matrix(name=name, dtype=dtype)
|
|
50
|
+
elif ndim == 3:
|
|
51
|
+
return T.tensor3(name=name, dtype=dtype)
|
|
52
|
+
elif ndim == 4:
|
|
53
|
+
return T.tensor4(name=name, dtype=dtype)
|
|
54
|
+
else:
|
|
55
|
+
raise Exception('ndim too large: ' + str(ndim))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def shape(x):
|
|
59
|
+
'''Return the shape of a tensor.
|
|
60
|
+
|
|
61
|
+
Warning: type returned will be different for
|
|
62
|
+
Theano backend (Theano tensor type) and TF backend (TF TensorShape).
|
|
63
|
+
'''
|
|
64
|
+
return x.shape
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def ndim(x):
|
|
68
|
+
return x.ndim
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def eval(x):
|
|
72
|
+
'''Run a graph.
|
|
73
|
+
'''
|
|
74
|
+
return x.eval()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def zeros(shape, dtype=_FLOATX, name=None):
|
|
78
|
+
'''Instantiate an all-zeros variable.
|
|
79
|
+
'''
|
|
80
|
+
return variable(np.zeros(shape), dtype, name)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def ones(shape, dtype=_FLOATX, name=None):
|
|
84
|
+
'''Instantiate an all-ones variable.
|
|
85
|
+
'''
|
|
86
|
+
return variable(np.ones(shape), dtype, name)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def ones_like(x):
|
|
90
|
+
return T.ones_like(x)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def zeros_like(x):
|
|
94
|
+
return T.zeros_like(x)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def count_params(x):
|
|
98
|
+
'''Return number of scalars in a tensor.
|
|
99
|
+
|
|
100
|
+
Return: numpy integer.
|
|
101
|
+
'''
|
|
102
|
+
return np.prod(x.shape.eval())
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def cast(x, dtype):
|
|
106
|
+
return T.cast(x, dtype)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# LINEAR ALGEBRA
|
|
110
|
+
|
|
111
|
+
'''
|
|
112
|
+
Assumed overridden:
|
|
113
|
+
+, -, /, *, +=, -=, *=, /=
|
|
114
|
+
'''
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def dot(x, y):
|
|
118
|
+
return T.dot(x, y)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def transpose(x):
|
|
122
|
+
return T.transpose(x)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def gather(reference, indices):
|
|
126
|
+
'''reference: a tensor.
|
|
127
|
+
indices: an int tensor of indices.
|
|
128
|
+
|
|
129
|
+
Return: a tensor of same type as reference.
|
|
130
|
+
'''
|
|
131
|
+
return reference[indices]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ELEMENT-WISE OPERATIONS
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def max(x, axis=None, keepdims=False):
|
|
138
|
+
return T.max(x, axis=axis, keepdims=keepdims)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def min(x, axis=None, keepdims=False):
|
|
142
|
+
return T.min(x, axis=axis, keepdims=keepdims)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def sum(x, axis=None, keepdims=False):
|
|
146
|
+
'''Sum of the values in a tensor, alongside the specified axis.
|
|
147
|
+
'''
|
|
148
|
+
return T.sum(x, axis=axis, keepdims=keepdims)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def prod(x, axis=None, keepdims=False):
|
|
152
|
+
'''Multiply the values in a tensor, alongside the specified axis.
|
|
153
|
+
'''
|
|
154
|
+
return T.prod(x, axis=axis, keepdims=keepdims)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def mean(x, axis=None, keepdims=False):
|
|
158
|
+
return T.mean(x, axis=axis, keepdims=keepdims)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def std(x, axis=None, keepdims=False):
|
|
162
|
+
return T.std(x, axis=axis, keepdims=keepdims)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def any(x, axis=None, keepdims=False):
|
|
166
|
+
'''Bitwise reduction (logical OR).
|
|
167
|
+
'''
|
|
168
|
+
return T.any(x, axis=axis, keepdims=keepdims)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def argmax(x, axis=-1):
|
|
172
|
+
return T.argmax(x, axis=axis, keepdims=False)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def argmin(x, axis=-1):
|
|
176
|
+
return T.argmin(x, axis=axis, keepdims=False)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def square(x):
|
|
180
|
+
return T.sqr(x)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def abs(x):
|
|
184
|
+
return T.abs_(x)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def sqrt(x):
|
|
188
|
+
x = T.clip(x, 0., np.inf)
|
|
189
|
+
return T.sqrt(x)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def exp(x):
|
|
193
|
+
return T.exp(x)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def log(x):
|
|
197
|
+
return T.log(x)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def round(x):
|
|
201
|
+
return T.round(x)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def pow(x, a):
|
|
205
|
+
return T.pow(x, a)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def clip(x, min_value, max_value):
|
|
209
|
+
if max_value < min_value:
|
|
210
|
+
max_value = min_value
|
|
211
|
+
return T.clip(x, min_value, max_value)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def equal(x, y):
|
|
215
|
+
return T.eq(x, y)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def maximum(x, y):
|
|
219
|
+
return T.maximum(x, y)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def minimum(x, y):
|
|
223
|
+
return T.minimum(x, y)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# SHAPE OPERATIONS
|
|
227
|
+
|
|
228
|
+
def concatenate(tensors, axis=-1):
|
|
229
|
+
return T.concatenate(tensors, axis=axis)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def reshape(x, shape):
|
|
233
|
+
return T.reshape(x, shape)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def permute_dimensions(x, pattern):
|
|
237
|
+
'''Transpose dimensions.
|
|
238
|
+
|
|
239
|
+
pattern should be a tuple or list of
|
|
240
|
+
dimension indices, e.g. [0, 2, 1].
|
|
241
|
+
'''
|
|
242
|
+
pattern = tuple(pattern)
|
|
243
|
+
return x.dimshuffle(pattern)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def repeat(x, n):
|
|
247
|
+
'''Repeat a 2D tensor:
|
|
248
|
+
|
|
249
|
+
if x has shape (samples, dim) and n=2,
|
|
250
|
+
the output will have shape (samples, 2, dim)
|
|
251
|
+
'''
|
|
252
|
+
tensors = [x] * n
|
|
253
|
+
stacked = T.stack(*tensors)
|
|
254
|
+
return stacked.dimshuffle((1, 0, 2))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def tile(x, n):
|
|
258
|
+
return T.tile(x, n)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def flatten(x):
|
|
262
|
+
'''Turn a n-D tensor into a 2D tensor where
|
|
263
|
+
the first dimension is conserved.
|
|
264
|
+
'''
|
|
265
|
+
x = T.reshape(x, (x.shape[0], T.prod(x.shape) // x.shape[0]))
|
|
266
|
+
return x
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def expand_dims(x, dim=-1):
|
|
270
|
+
'''Add a 1-sized dimension at index "dim".
|
|
271
|
+
'''
|
|
272
|
+
pattern = [i for i in range(x.type.ndim)]
|
|
273
|
+
if dim < 0:
|
|
274
|
+
if x.type.ndim == 0:
|
|
275
|
+
dim = 0
|
|
276
|
+
else:
|
|
277
|
+
dim = dim % x.type.ndim + 1
|
|
278
|
+
pattern.insert(dim, 'x')
|
|
279
|
+
return x.dimshuffle(pattern)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def squeeze(x, axis):
|
|
283
|
+
'''Remove a 1-dimension from the tensor at index "axis".
|
|
284
|
+
'''
|
|
285
|
+
x = T.addbroadcast(x, axis)
|
|
286
|
+
return T.squeeze(x)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def temporal_padding(x, padding=1):
|
|
290
|
+
'''Pad the middle dimension of a 3D tensor
|
|
291
|
+
with "padding" zeros left and right.
|
|
292
|
+
|
|
293
|
+
Appologies for the inane API, but Theano makes this
|
|
294
|
+
really hard.
|
|
295
|
+
'''
|
|
296
|
+
input_shape = x.shape
|
|
297
|
+
output_shape = (input_shape[0],
|
|
298
|
+
input_shape[1] + 2 * padding,
|
|
299
|
+
input_shape[2])
|
|
300
|
+
output = T.zeros(output_shape)
|
|
301
|
+
return T.set_subtensor(output[:, padding:x.shape[1] + padding, :], x)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):
|
|
305
|
+
'''Pad the 2nd and 3rd dimensions of a 4D tensor
|
|
306
|
+
with "padding[0]" and "padding[1]" (resp.) zeros left and right.
|
|
307
|
+
'''
|
|
308
|
+
input_shape = x.shape
|
|
309
|
+
if dim_ordering == 'th':
|
|
310
|
+
output_shape = (input_shape[0],
|
|
311
|
+
input_shape[1],
|
|
312
|
+
input_shape[2] + 2 * padding[0],
|
|
313
|
+
input_shape[3] + 2 * padding[1])
|
|
314
|
+
output = T.zeros(output_shape)
|
|
315
|
+
indices = (slice(None),
|
|
316
|
+
slice(None),
|
|
317
|
+
slice(padding[0], input_shape[2] + padding[0]),
|
|
318
|
+
slice(padding[1], input_shape[3] + padding[1]))
|
|
319
|
+
|
|
320
|
+
elif dim_ordering == 'tf':
|
|
321
|
+
output_shape = (input_shape[0],
|
|
322
|
+
input_shape[1] + 2 * padding[0],
|
|
323
|
+
input_shape[2] + 2 * padding[1],
|
|
324
|
+
input_shape[3])
|
|
325
|
+
output = T.zeros(output_shape)
|
|
326
|
+
indices = (slice(None),
|
|
327
|
+
slice(padding[0], input_shape[1] + padding[0]),
|
|
328
|
+
slice(padding[1], input_shape[2] + padding[1]),
|
|
329
|
+
slice(None))
|
|
330
|
+
else:
|
|
331
|
+
raise Exception('Invalid dim_ordering: ' + dim_ordering)
|
|
332
|
+
return T.set_subtensor(output[indices], x)
|
|
333
|
+
|
|
334
|
+
# VALUE MANIPULATION
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def get_value(x):
|
|
338
|
+
if not hasattr(x, 'get_value'):
|
|
339
|
+
raise Exception("'get_value() can only be called on a variable. " +
|
|
340
|
+
"If you have an expression instead, use eval().")
|
|
341
|
+
return x.get_value()
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def set_value(x, value):
|
|
345
|
+
x.set_value(np.asarray(value, dtype=x.dtype))
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
# GRAPH MANIPULATION
|
|
349
|
+
|
|
350
|
+
class Function(object):
|
|
351
|
+
|
|
352
|
+
def __init__(self, inputs, outputs, updates=[], **kwargs):
|
|
353
|
+
self.function = theano.function(inputs, outputs, updates=updates,
|
|
354
|
+
allow_input_downcast=True, **kwargs)
|
|
355
|
+
|
|
356
|
+
def __call__(self, inputs):
|
|
357
|
+
return self.function(*inputs)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def function(inputs, outputs, updates=[]):
|
|
361
|
+
return Function(inputs, outputs, updates=updates)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def gradients(loss, variables):
|
|
365
|
+
return T.grad(loss, variables)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
# CONTROL FLOW
|
|
369
|
+
|
|
370
|
+
def rnn(step_function, inputs, initial_states,
|
|
371
|
+
go_backwards=False, masking=True):
|
|
372
|
+
'''Iterates over the time dimension of a tensor.
|
|
373
|
+
|
|
374
|
+
Parameters
|
|
375
|
+
----------
|
|
376
|
+
inputs: tensor of temporal data of shape (samples, time, ...)
|
|
377
|
+
(at least 3D).
|
|
378
|
+
step_function:
|
|
379
|
+
Parameters:
|
|
380
|
+
input: tensor with shape (samples, ...) (no time dimension),
|
|
381
|
+
representing input for the batch of samples at a certain
|
|
382
|
+
time step.
|
|
383
|
+
states: list of tensors.
|
|
384
|
+
Returns:
|
|
385
|
+
output: tensor with shape (samples, ...) (no time dimension),
|
|
386
|
+
new_states: list of tensors, same length and shapes
|
|
387
|
+
as 'states'.
|
|
388
|
+
initial_states: tensor with shape (samples, ...) (no time dimension),
|
|
389
|
+
containing the initial values for the states used in
|
|
390
|
+
the step function.
|
|
391
|
+
go_backwards: boolean. If True, do the iteration over
|
|
392
|
+
the time dimension in reverse order.
|
|
393
|
+
masking: boolean. If true, any input timestep inputs[s, i]
|
|
394
|
+
that is all-zeros will be skipped (states will be passed to
|
|
395
|
+
the next step unchanged) and the corresponding output will
|
|
396
|
+
be all zeros.
|
|
397
|
+
|
|
398
|
+
Returns
|
|
399
|
+
-------
|
|
400
|
+
A tuple (last_output, outputs, new_states).
|
|
401
|
+
last_output: the latest output of the rnn, of shape (samples, ...)
|
|
402
|
+
outputs: tensor with shape (samples, time, ...) where each
|
|
403
|
+
entry outputs[s, t] is the output of the step function
|
|
404
|
+
at time t for sample s.
|
|
405
|
+
new_states: list of tensors, latest states returned by
|
|
406
|
+
the step function, of shape (samples, ...).
|
|
407
|
+
'''
|
|
408
|
+
inputs = inputs.dimshuffle((1, 0, 2))
|
|
409
|
+
|
|
410
|
+
def _step(*args):
|
|
411
|
+
global single_result
|
|
412
|
+
input = args[0]
|
|
413
|
+
states = args[1:]
|
|
414
|
+
output, new_states = step_function(input, states)
|
|
415
|
+
if masking:
|
|
416
|
+
# if all-zero input timestep, return
|
|
417
|
+
# all-zero output and unchanged states
|
|
418
|
+
switch = T.any(input)
|
|
419
|
+
output = T.switch(switch, output, 0. * output)
|
|
420
|
+
return_states = []
|
|
421
|
+
for state, new_state in zip(states, new_states):
|
|
422
|
+
return_states.append(T.switch(switch, new_state, state))
|
|
423
|
+
return [output] + return_states
|
|
424
|
+
else:
|
|
425
|
+
return [output] + new_states
|
|
426
|
+
|
|
427
|
+
results, _ = theano.scan(
|
|
428
|
+
_step,
|
|
429
|
+
sequences=inputs,
|
|
430
|
+
outputs_info=[None] + initial_states,
|
|
431
|
+
go_backwards=go_backwards)
|
|
432
|
+
|
|
433
|
+
# deal with Theano API inconsistency
|
|
434
|
+
if type(results) is list:
|
|
435
|
+
outputs = results[0]
|
|
436
|
+
states = results[1:]
|
|
437
|
+
else:
|
|
438
|
+
outputs = results
|
|
439
|
+
states = []
|
|
440
|
+
|
|
441
|
+
outputs = T.squeeze(outputs)
|
|
442
|
+
last_output = outputs[-1]
|
|
443
|
+
|
|
444
|
+
outputs = outputs.dimshuffle((1, 0, 2))
|
|
445
|
+
states = [T.squeeze(state[-1]) for state in states]
|
|
446
|
+
return last_output, outputs, states
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def switch(condition, then_expression, else_expression):
|
|
450
|
+
'''condition: scalar tensor.
|
|
451
|
+
'''
|
|
452
|
+
return T.switch(condition, then_expression, else_expression)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
# NN OPERATIONS
|
|
456
|
+
|
|
457
|
+
def relu(x, alpha=0., max_value=None):
|
|
458
|
+
x = T.nnet.relu(x, alpha)
|
|
459
|
+
if max_value is not None:
|
|
460
|
+
x = T.minimum(x, max_value)
|
|
461
|
+
return x
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def softmax(x):
|
|
465
|
+
return T.nnet.softmax(x)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def softplus(x):
|
|
469
|
+
return T.nnet.softplus(x)
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def categorical_crossentropy(output, target, from_logits=False):
|
|
473
|
+
if from_logits:
|
|
474
|
+
output = T.nnet.softmax(output)
|
|
475
|
+
else:
|
|
476
|
+
# scale preds so that the class probas of each sample sum to 1
|
|
477
|
+
output /= output.sum(axis=-1, keepdims=True)
|
|
478
|
+
# avoid numerical instability with _EPSILON clipping
|
|
479
|
+
output = T.clip(output, _EPSILON, 1.0 - _EPSILON)
|
|
480
|
+
return T.nnet.categorical_crossentropy(output, target)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def binary_crossentropy(output, target, from_logits=False):
|
|
484
|
+
if from_logits:
|
|
485
|
+
output = T.nnet.sigmoid(output)
|
|
486
|
+
# avoid numerical instability with _EPSILON clipping
|
|
487
|
+
output = T.clip(output, _EPSILON, 1.0 - _EPSILON)
|
|
488
|
+
return T.nnet.binary_crossentropy(output, target)
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def sigmoid(x):
|
|
492
|
+
return T.nnet.sigmoid(x)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def hard_sigmoid(x):
|
|
496
|
+
return T.nnet.hard_sigmoid(x)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def tanh(x):
|
|
500
|
+
return T.tanh(x)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def dropout(x, level, seed=None):
|
|
504
|
+
if level < 0. or level >= 1:
|
|
505
|
+
raise Exception('Dropout level must be in interval [0, 1[.')
|
|
506
|
+
if seed is None:
|
|
507
|
+
seed = np.random.randint(10e6)
|
|
508
|
+
rng = RandomStreams(seed=seed)
|
|
509
|
+
retain_prob = 1. - level
|
|
510
|
+
x *= rng.binomial(x.shape, p=retain_prob, dtype=x.dtype)
|
|
511
|
+
x /= retain_prob
|
|
512
|
+
return x
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
# CONVOLUTIONS
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'):
|
|
519
|
+
'''
|
|
520
|
+
Run on cuDNN if available.
|
|
521
|
+
border_mode: string, "same" or "valid".
|
|
522
|
+
'''
|
|
523
|
+
if dim_ordering not in {'th', 'tf'}:
|
|
524
|
+
raise Exception('Unknown dim_ordering ' + str(dim_ordering))
|
|
525
|
+
|
|
526
|
+
if dim_ordering == 'tf':
|
|
527
|
+
# TF uses the last dimension as channel dimension,
|
|
528
|
+
# instead of the 2nd one.
|
|
529
|
+
# TH input shape: (samples, input_depth, rows, cols)
|
|
530
|
+
# TF input shape: (samples, rows, cols, input_depth)
|
|
531
|
+
# TH kernel shape: (depth, input_depth, rows, cols)
|
|
532
|
+
# TF kernel shape: (rows, cols, input_depth, depth)
|
|
533
|
+
x = x.dimshuffle((0, 3, 1, 2))
|
|
534
|
+
kernel = kernel.dimshuffle((3, 2, 0, 1))
|
|
535
|
+
|
|
536
|
+
if _on_gpu() and dnn.dnn_available():
|
|
537
|
+
if border_mode == 'same':
|
|
538
|
+
assert(strides == (1, 1))
|
|
539
|
+
pad_x = (kernel.shape[2] - strides[0]) // 2
|
|
540
|
+
pad_y = (kernel.shape[3] - strides[1]) // 2
|
|
541
|
+
conv_out = dnn.dnn_conv(img=x,
|
|
542
|
+
kerns=kernel,
|
|
543
|
+
border_mode=(pad_x, pad_y))
|
|
544
|
+
else:
|
|
545
|
+
conv_out = dnn.dnn_conv(img=x,
|
|
546
|
+
kerns=kernel,
|
|
547
|
+
border_mode=border_mode,
|
|
548
|
+
subsample=strides)
|
|
549
|
+
else:
|
|
550
|
+
if border_mode == 'same':
|
|
551
|
+
th_border_mode = 'full'
|
|
552
|
+
assert(strides == (1, 1))
|
|
553
|
+
elif border_mode == 'valid':
|
|
554
|
+
th_border_mode = 'valid'
|
|
555
|
+
else:
|
|
556
|
+
raise Exception('Border mode not supported: ' + str(border_mode))
|
|
557
|
+
|
|
558
|
+
conv_out = T.nnet.conv.conv2d(x, kernel,
|
|
559
|
+
border_mode=th_border_mode,
|
|
560
|
+
subsample=strides)
|
|
561
|
+
if border_mode == 'same':
|
|
562
|
+
shift_x = (kernel.shape[2] - 1) // 2
|
|
563
|
+
shift_y = (kernel.shape[3] - 1) // 2
|
|
564
|
+
conv_out = conv_out[:, :,
|
|
565
|
+
shift_x:x.shape[2] + shift_x,
|
|
566
|
+
shift_y:x.shape[3] + shift_y]
|
|
567
|
+
if dim_ordering == 'tf':
|
|
568
|
+
conv_out = conv_out.dimshuffle((0, 2, 3, 1))
|
|
569
|
+
return conv_out
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def maxpool2d(x, pool_size, strides=(1, 1), border_mode='valid',
|
|
573
|
+
dim_ordering='th'):
|
|
574
|
+
if border_mode == 'same':
|
|
575
|
+
# TODO: add implementation for border_mode="same"
|
|
576
|
+
raise Exception('border_mode="same" not supported with Theano.')
|
|
577
|
+
elif border_mode == 'valid':
|
|
578
|
+
ignore_border = True
|
|
579
|
+
padding = (0, 0)
|
|
580
|
+
else:
|
|
581
|
+
raise Exception('Invalid border mode: ' + str(border_mode))
|
|
582
|
+
|
|
583
|
+
if dim_ordering not in {'th', 'tf'}:
|
|
584
|
+
raise Exception('Unknown dim_ordering ' + str(dim_ordering))
|
|
585
|
+
|
|
586
|
+
if dim_ordering == 'tf':
|
|
587
|
+
x = x.dimshuffle((0, 3, 1, 2))
|
|
588
|
+
|
|
589
|
+
pool_out = downsample.max_pool_2d(x,
|
|
590
|
+
ds=pool_size,
|
|
591
|
+
st=strides,
|
|
592
|
+
ignore_border=ignore_border,
|
|
593
|
+
padding=padding,
|
|
594
|
+
mode='average_exc_pad')
|
|
595
|
+
if dim_ordering == 'tf':
|
|
596
|
+
pool_out = pool_out.dimshuffle((0, 2, 3, 1))
|
|
597
|
+
return pool_out
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
# RANDOMNESS
|
|
601
|
+
|
|
602
|
+
def random_normal(shape, mean=0.0, std=1.0, dtype=_FLOATX, seed=None):
|
|
603
|
+
if seed is None:
|
|
604
|
+
seed = np.random.randint(10e6)
|
|
605
|
+
rng = RandomStreams(seed=seed)
|
|
606
|
+
return rng.normal(size=shape, avg=mean, std=std, dtype=dtype)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None):
|
|
610
|
+
if seed is None:
|
|
611
|
+
seed = np.random.randint(10e6)
|
|
612
|
+
rng = RandomStreams(seed=seed)
|
|
613
|
+
return rng.uniform(shape, low=low, high=high, dtype=dtype)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
'''
|
|
618
|
+
more TODO:
|
|
619
|
+
|
|
620
|
+
tensordot -> soon to be introduced in TF
|
|
621
|
+
batched_tensordot -> reimplement
|
|
622
|
+
'''
|
|
Binary file
|