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,602 @@
|
|
|
1
|
+
import tensorflow as tf
|
|
2
|
+
import numpy as np
|
|
3
|
+
from .common import _FLOATX, _EPSILON
|
|
4
|
+
|
|
5
|
+
# INTERNAL UTILS
|
|
6
|
+
|
|
7
|
+
_SESSION = None
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _get_session():
|
|
11
|
+
global _SESSION
|
|
12
|
+
if _SESSION is None:
|
|
13
|
+
_SESSION = tf.Session('')
|
|
14
|
+
return _SESSION
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _set_session(session):
|
|
18
|
+
global _SESSION
|
|
19
|
+
_SESSION = session
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# VARIABLE MANIPULATION
|
|
23
|
+
|
|
24
|
+
def variable(value, dtype=_FLOATX, name=None):
|
|
25
|
+
v = tf.Variable(np.asarray(value, dtype=dtype), name=name)
|
|
26
|
+
_get_session().run(v.initializer)
|
|
27
|
+
return v
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None):
|
|
31
|
+
if not shape:
|
|
32
|
+
if ndim:
|
|
33
|
+
shape = [None for _ in range(ndim)]
|
|
34
|
+
return tf.placeholder(dtype, shape=shape, name=name)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def shape(x):
|
|
38
|
+
return x.get_shape()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def ndim(x):
|
|
42
|
+
return len(x.get_shape())
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def eval(x):
|
|
46
|
+
'''Run a graph.
|
|
47
|
+
'''
|
|
48
|
+
return x.eval(session=_get_session())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def zeros(shape, dtype=_FLOATX, name=None):
|
|
52
|
+
return variable(np.zeros(shape), dtype, name)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ones(shape, dtype=_FLOATX, name=None):
|
|
56
|
+
return variable(np.ones(shape), dtype, name)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def ones_like(x, name=None):
|
|
60
|
+
return tf.ones_like(x)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def zeros_like(x, name=None):
|
|
64
|
+
return tf.zeros_like(x)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def count_params(x):
|
|
68
|
+
'''Return number of scalars in a tensor.
|
|
69
|
+
'''
|
|
70
|
+
shape = x.get_shape()
|
|
71
|
+
return np.prod([shape[i]._value for i in range(len(shape))])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def cast(x, dtype):
|
|
75
|
+
return tf.cast(x, dtype)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# LINEAR ALGEBRA
|
|
79
|
+
|
|
80
|
+
def dot(x, y):
|
|
81
|
+
return tf.matmul(x, y)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def transpose(x):
|
|
85
|
+
return tf.transpose(x)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def gather(reference, indices):
|
|
89
|
+
'''reference: a tensor.
|
|
90
|
+
indices: an int tensor of indices.
|
|
91
|
+
|
|
92
|
+
Return: a tensor of same type as reference.
|
|
93
|
+
'''
|
|
94
|
+
return tf.gather(reference, indices)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ELEMENT-WISE OPERATIONS
|
|
98
|
+
|
|
99
|
+
def max(x, axis=None, keepdims=False):
|
|
100
|
+
if axis is not None and axis < 0:
|
|
101
|
+
axis = axis % len(x.get_shape())
|
|
102
|
+
return tf.reduce_max(x, reduction_indices=axis, keep_dims=keepdims)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def min(x, axis=None, keepdims=False):
|
|
106
|
+
if axis is not None and axis < 0:
|
|
107
|
+
axis = axis % len(x.get_shape())
|
|
108
|
+
return tf.reduce_min(x, reduction_indices=axis, keep_dims=keepdims)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def sum(x, axis=None, keepdims=False):
|
|
112
|
+
'''Sum of the values in a tensor, alongside the specified axis.
|
|
113
|
+
'''
|
|
114
|
+
if axis is not None and axis < 0:
|
|
115
|
+
axis = axis % len(x.get_shape())
|
|
116
|
+
return tf.reduce_sum(x, reduction_indices=axis, keep_dims=keepdims)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def prod(x, axis=None, keepdims=False):
|
|
120
|
+
'''Multiply the values in a tensor, alongside the specified axis.
|
|
121
|
+
'''
|
|
122
|
+
return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def std(x, axis=None, keepdims=False):
|
|
126
|
+
if axis is not None and axis < 0:
|
|
127
|
+
axis = axis % len(x.get_shape())
|
|
128
|
+
if x.dtype.base_dtype == tf.bool:
|
|
129
|
+
x = tf.cast(x, _FLOATX)
|
|
130
|
+
m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)
|
|
131
|
+
devs_squared = tf.square(x - m)
|
|
132
|
+
return tf.sqrt(tf.reduce_mean(devs_squared,
|
|
133
|
+
reduction_indices=axis,
|
|
134
|
+
keep_dims=keepdims))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def mean(x, axis=None, keepdims=False):
|
|
138
|
+
if axis is not None and axis < 0:
|
|
139
|
+
axis = axis % len(x.get_shape())
|
|
140
|
+
if x.dtype.base_dtype == tf.bool:
|
|
141
|
+
x = tf.cast(x, _FLOATX)
|
|
142
|
+
return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def any(x, axis=None, keepdims=False):
|
|
146
|
+
'''Bitwise reduction (logical OR).
|
|
147
|
+
|
|
148
|
+
Return array of int8 (0s and 1s).
|
|
149
|
+
'''
|
|
150
|
+
if axis is not None and axis < 0:
|
|
151
|
+
axis = axis % len(x.get_shape())
|
|
152
|
+
x = tf.cast(x, tf.bool)
|
|
153
|
+
x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims)
|
|
154
|
+
return tf.cast(x, tf.int8)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def argmax(x, axis=-1):
|
|
158
|
+
if axis < 0:
|
|
159
|
+
axis = axis % len(x.get_shape())
|
|
160
|
+
return tf.argmax(x, axis)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def argmin(x, axis=-1):
|
|
164
|
+
if axis < 0:
|
|
165
|
+
axis = axis % len(x.get_shape())
|
|
166
|
+
return tf.argmin(x, axis)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def square(x):
|
|
170
|
+
return tf.square(x)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def abs(x):
|
|
174
|
+
return tf.abs(x)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def sqrt(x):
|
|
178
|
+
x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),
|
|
179
|
+
tf.cast(np.inf, dtype=_FLOATX))
|
|
180
|
+
return tf.sqrt(x)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def exp(x):
|
|
184
|
+
return tf.exp(x)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def log(x):
|
|
188
|
+
return tf.log(x)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def round(x):
|
|
192
|
+
return tf.round(x)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def pow(x, a):
|
|
196
|
+
return tf.pow(x, a)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def clip(x, min_value, max_value):
|
|
200
|
+
if max_value < min_value:
|
|
201
|
+
max_value = min_value
|
|
202
|
+
return tf.clip_by_value(x, tf.cast(min_value, dtype=_FLOATX),
|
|
203
|
+
tf.cast(max_value, dtype=_FLOATX))
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def equal(x, y):
|
|
207
|
+
return tf.equal(x, y)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def maximum(x, y):
|
|
211
|
+
return tf.maximum(x, y)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def minimum(x, y):
|
|
215
|
+
return tf.minimum(x, y)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# SHAPE OPERATIONS
|
|
219
|
+
|
|
220
|
+
def concatenate(tensors, axis=-1):
|
|
221
|
+
if axis < 0:
|
|
222
|
+
axis = axis % len(tensors[0].get_shape())
|
|
223
|
+
return tf.concat(axis, tensors)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def reshape(x, shape):
|
|
227
|
+
return tf.reshape(x, shape)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def permute_dimensions(x, pattern):
|
|
231
|
+
'''Transpose dimensions.
|
|
232
|
+
|
|
233
|
+
pattern should be a tuple or list of
|
|
234
|
+
dimension indices, e.g. [0, 2, 1].
|
|
235
|
+
'''
|
|
236
|
+
return tf.transpose(x, perm=pattern)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def repeat(x, n):
|
|
240
|
+
'''Repeat a 2D tensor:
|
|
241
|
+
|
|
242
|
+
if x has shape (samples, dim) and n=2,
|
|
243
|
+
the output will have shape (samples, 2, dim)
|
|
244
|
+
'''
|
|
245
|
+
tensors = [x] * n
|
|
246
|
+
stacked = tf.pack(tensors)
|
|
247
|
+
return tf.transpose(stacked, (1, 0, 2))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def tile(x, n):
|
|
251
|
+
return tf.tile(x, n)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def flatten(x):
|
|
255
|
+
'''Turn a n-D tensor into a 2D tensor where
|
|
256
|
+
the first dimension is conserved.
|
|
257
|
+
'''
|
|
258
|
+
x = tf.reshape(x, [-1, np.prod(x.get_shape()[1:].as_list())])
|
|
259
|
+
return x
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def expand_dims(x, dim=-1):
|
|
263
|
+
'''Add a 1-sized dimension at index "dim".
|
|
264
|
+
'''
|
|
265
|
+
return tf.expand_dims(x, dim)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def squeeze(x, axis):
|
|
269
|
+
'''Remove a 1-dimension from the tensor at index "axis".
|
|
270
|
+
'''
|
|
271
|
+
return tf.squeeze(x, [axis])
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def temporal_padding(x, padding=1):
|
|
275
|
+
'''Pad the middle dimension of a 3D tensor
|
|
276
|
+
with "padding" zeros left and right.
|
|
277
|
+
|
|
278
|
+
Appologies for the inane API, but Theano makes this
|
|
279
|
+
really hard.
|
|
280
|
+
'''
|
|
281
|
+
pattern = [[0, 0], [padding, padding], [0, 0]]
|
|
282
|
+
return tf.pad(x, pattern)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def spatial_2d_padding(x, padding=(1, 1), dim_ordering='th'):
|
|
286
|
+
'''Pad the 2nd and 3rd dimensions of a 4D tensor
|
|
287
|
+
with "padding[0]" and "padding[1]" (resp.) zeros left and right.
|
|
288
|
+
'''
|
|
289
|
+
if dim_ordering == 'th':
|
|
290
|
+
pattern = [[0, 0], [0, 0],
|
|
291
|
+
[padding[0], padding[0]], [padding[1], padding[1]]]
|
|
292
|
+
else:
|
|
293
|
+
pattern = [[0, 0],
|
|
294
|
+
[padding[0], padding[0]], [padding[1], padding[1]],
|
|
295
|
+
[0, 0]]
|
|
296
|
+
return tf.pad(x, pattern)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# VALUE MANIPULATION
|
|
300
|
+
|
|
301
|
+
def get_value(x):
|
|
302
|
+
'''Technically the same as eval() for TF.
|
|
303
|
+
'''
|
|
304
|
+
return x.eval(session=_get_session())
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def set_value(x, value):
|
|
308
|
+
tf.assign(x, np.asarray(value)).op.run(session=_get_session())
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# GRAPH MANIPULATION
|
|
312
|
+
|
|
313
|
+
class Function(object):
|
|
314
|
+
|
|
315
|
+
def __init__(self, inputs, outputs, updates=[]):
|
|
316
|
+
self.inputs = list(inputs)
|
|
317
|
+
self.outputs = list(outputs)
|
|
318
|
+
with tf.control_dependencies(self.outputs):
|
|
319
|
+
self.updates = [tf.assign(p, new_p) for (p, new_p) in updates]
|
|
320
|
+
|
|
321
|
+
def __call__(self, inputs):
|
|
322
|
+
names = [v.name for v in self.inputs]
|
|
323
|
+
feed_dict = dict(zip(names, inputs))
|
|
324
|
+
session = _get_session()
|
|
325
|
+
updated = session.run(self.outputs + self.updates, feed_dict=feed_dict)
|
|
326
|
+
return updated[:len(self.outputs)]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def function(inputs, outputs, updates=[]):
|
|
330
|
+
return Function(inputs, outputs, updates=updates)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def gradients(loss, variables):
|
|
334
|
+
return tf.gradients(loss, variables)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# CONTROL FLOW
|
|
338
|
+
|
|
339
|
+
def rnn(step_function, inputs, initial_states,
|
|
340
|
+
go_backwards=False, masking=True):
|
|
341
|
+
'''Iterates over the time dimension of a tensor.
|
|
342
|
+
|
|
343
|
+
Parameters
|
|
344
|
+
----------
|
|
345
|
+
inputs: tensor of temporal data of shape (samples, time, ...)
|
|
346
|
+
(at least 3D).
|
|
347
|
+
step_function:
|
|
348
|
+
Parameters:
|
|
349
|
+
input: tensor with shape (samples, ...) (no time dimension),
|
|
350
|
+
representing input for the batch of samples at a certain
|
|
351
|
+
time step.
|
|
352
|
+
states: list of tensors.
|
|
353
|
+
Returns:
|
|
354
|
+
output: tensor with shape (samples, ...) (no time dimension),
|
|
355
|
+
new_states: list of tensors, same length and shapes
|
|
356
|
+
as 'states'.
|
|
357
|
+
initial_states: tensor with shape (samples, ...) (no time dimension),
|
|
358
|
+
containing the initial values for the states used in
|
|
359
|
+
the step function.
|
|
360
|
+
go_backwards: boolean. If True, do the iteration over
|
|
361
|
+
the time dimension in reverse order.
|
|
362
|
+
masking: boolean. If true, any input timestep inputs[s, i]
|
|
363
|
+
that is all-zeros will be skipped (states will be passed to
|
|
364
|
+
the next step unchanged) and the corresponding output will
|
|
365
|
+
be all zeros.
|
|
366
|
+
|
|
367
|
+
Returns
|
|
368
|
+
-------
|
|
369
|
+
A tuple (last_output, outputs, new_states).
|
|
370
|
+
last_output: the latest output of the rnn, of shape (samples, ...)
|
|
371
|
+
outputs: tensor with shape (samples, time, ...) where each
|
|
372
|
+
entry outputs[s, t] is the output of the step function
|
|
373
|
+
at time t for sample s.
|
|
374
|
+
new_states: list of tensors, latest states returned by
|
|
375
|
+
the step function, of shape (samples, ...).
|
|
376
|
+
'''
|
|
377
|
+
inputs = tf.transpose(inputs, (1, 0, 2))
|
|
378
|
+
input_list = tf.unpack(inputs)
|
|
379
|
+
|
|
380
|
+
states = initial_states
|
|
381
|
+
successive_states = []
|
|
382
|
+
successive_outputs = []
|
|
383
|
+
if go_backwards:
|
|
384
|
+
input_list.reverse()
|
|
385
|
+
for input in input_list:
|
|
386
|
+
output, new_states = step_function(input, states)
|
|
387
|
+
if masking:
|
|
388
|
+
# for now we raise an exception because tf.reduce_any will not work
|
|
389
|
+
raise Exception("Masking is Theano-only for the time being.")
|
|
390
|
+
|
|
391
|
+
# if all-zero input timestep, return
|
|
392
|
+
# all-zero output and unchanged states
|
|
393
|
+
switch = tf.reduce_any(input)
|
|
394
|
+
output = tf.control_flow_ops.cond(switch,
|
|
395
|
+
lambda: output,
|
|
396
|
+
lambda: 0. * output)
|
|
397
|
+
return_states = []
|
|
398
|
+
for state, new_state in zip(states, new_states):
|
|
399
|
+
return_states.append(tf.control_flow_ops.cond(switch,
|
|
400
|
+
lambda: new_state,
|
|
401
|
+
lambda: state))
|
|
402
|
+
states = return_states
|
|
403
|
+
else:
|
|
404
|
+
states = new_states
|
|
405
|
+
successive_outputs.append(output)
|
|
406
|
+
successive_states.append(states)
|
|
407
|
+
|
|
408
|
+
last_output = successive_outputs[-1]
|
|
409
|
+
outputs = tf.pack(successive_outputs)
|
|
410
|
+
new_states = successive_states[-1]
|
|
411
|
+
|
|
412
|
+
outputs = tf.transpose(outputs, (1, 0, 2))
|
|
413
|
+
return last_output, outputs, states
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def switch(condition, then_expression, else_expression):
|
|
417
|
+
'''condition: scalar tensor.
|
|
418
|
+
'''
|
|
419
|
+
return tf.control_flow_ops.cond(condition,
|
|
420
|
+
lambda: then_expression,
|
|
421
|
+
lambda: else_expression)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
# NN OPERATIONS
|
|
425
|
+
|
|
426
|
+
def relu(x, alpha=0., max_value=None):
|
|
427
|
+
'''ReLU.
|
|
428
|
+
|
|
429
|
+
alpha: slope of negative section.
|
|
430
|
+
'''
|
|
431
|
+
negative_part = tf.nn.relu(-x)
|
|
432
|
+
x = tf.nn.relu(x)
|
|
433
|
+
if max_value is not None:
|
|
434
|
+
x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),
|
|
435
|
+
tf.cast(max_value, dtype=_FLOATX))
|
|
436
|
+
x -= tf.constant(alpha, dtype=_FLOATX) * negative_part
|
|
437
|
+
return x
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def softmax(x):
|
|
441
|
+
return tf.nn.softmax(x)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def softplus(x):
|
|
445
|
+
return tf.nn.softplus(x)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def categorical_crossentropy(output, target, from_logits=False):
|
|
449
|
+
'''Note: tf.nn.softmax_cross_entropy_with_logits
|
|
450
|
+
expects logits, Keras expects probabilities.
|
|
451
|
+
'''
|
|
452
|
+
if not from_logits:
|
|
453
|
+
# scale preds so that the class probas of each sample sum to 1
|
|
454
|
+
output /= tf.reduce_sum(output,
|
|
455
|
+
reduction_indices=len(output.get_shape())-1,
|
|
456
|
+
keep_dims=True)
|
|
457
|
+
# manual computation of crossentropy
|
|
458
|
+
output = tf.clip_by_value(output, tf.cast(_EPSILON, dtype=_FLOATX),
|
|
459
|
+
tf.cast(1.-_EPSILON, dtype=_FLOATX))
|
|
460
|
+
return - tf.reduce_sum(target * tf.log(output),
|
|
461
|
+
reduction_indices=len(output.get_shape())-1)
|
|
462
|
+
else:
|
|
463
|
+
return tf.nn.softmax_cross_entropy_with_logits(output, target)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def binary_crossentropy(output, target, from_logits=False):
|
|
467
|
+
'''Note: tf.nn.sigmoid_cross_entropy_with_logits
|
|
468
|
+
expects logits, Keras expects probabilities.
|
|
469
|
+
'''
|
|
470
|
+
if not from_logits:
|
|
471
|
+
# transform back to logits
|
|
472
|
+
output = tf.clip_by_value(output, tf.cast(_EPSILON, dtype=_FLOATX),
|
|
473
|
+
tf.cast(1.-_EPSILON, dtype=_FLOATX))
|
|
474
|
+
output = tf.log(output / (1 - output))
|
|
475
|
+
return tf.nn.sigmoid_cross_entropy_with_logits(output, target)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def sigmoid(x):
|
|
479
|
+
return tf.nn.sigmoid(x)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def hard_sigmoid(x):
|
|
483
|
+
x = (0.2 * x) + 0.5
|
|
484
|
+
x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),
|
|
485
|
+
tf.cast(1., dtype=_FLOATX))
|
|
486
|
+
return x
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def tanh(x):
|
|
490
|
+
return tf.nn.tanh(x)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def dropout(x, level, seed=None):
|
|
494
|
+
retain_prob = 1. - level
|
|
495
|
+
if seed is None:
|
|
496
|
+
seed = np.random.randint(10e6)
|
|
497
|
+
# the dummy 1. works around a TF bug
|
|
498
|
+
# (float32_ref vs. float32 incomptability)
|
|
499
|
+
return tf.nn.dropout(x * 1., retain_prob, seed=seed)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
# CONVOLUTIONS
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'):
|
|
506
|
+
'''
|
|
507
|
+
Run on cuDNN if available.
|
|
508
|
+
border_mode: string, "same" or "valid".
|
|
509
|
+
dim_ordering: whether to use Theano or TensorFlow dimension ordering
|
|
510
|
+
in inputs/kernels/ouputs.
|
|
511
|
+
'''
|
|
512
|
+
if border_mode == 'same':
|
|
513
|
+
padding = 'SAME'
|
|
514
|
+
elif border_mode == 'valid':
|
|
515
|
+
padding = 'VALID'
|
|
516
|
+
else:
|
|
517
|
+
raise Exception('Invalid border mode: ' + str(border_mode))
|
|
518
|
+
|
|
519
|
+
strides = (1,) + strides + (1,)
|
|
520
|
+
|
|
521
|
+
if _FLOATX == 'float64':
|
|
522
|
+
# tf conv2d only supports float32
|
|
523
|
+
x = tf.cast(x, 'float32')
|
|
524
|
+
kernel = tf.cast(kernel, 'float32')
|
|
525
|
+
|
|
526
|
+
if dim_ordering == 'th':
|
|
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 = tf.transpose(x, (0, 2, 3, 1))
|
|
534
|
+
kernel = tf.transpose(kernel, (2, 3, 1, 0))
|
|
535
|
+
x = tf.nn.conv2d(x, kernel, strides, padding=padding)
|
|
536
|
+
x = tf.transpose(x, (0, 3, 1, 2))
|
|
537
|
+
elif dim_ordering == 'tf':
|
|
538
|
+
x = tf.nn.conv2d(x, kernel, strides, padding=padding)
|
|
539
|
+
else:
|
|
540
|
+
raise Exception('Unknown dim_ordering: ' + str(dim_ordering))
|
|
541
|
+
|
|
542
|
+
if _FLOATX == 'float64':
|
|
543
|
+
x = tf.cast(x, 'float64')
|
|
544
|
+
return x
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def maxpool2d(x, pool_size, strides=(1, 1),
|
|
548
|
+
border_mode='valid', dim_ordering='th'):
|
|
549
|
+
'''
|
|
550
|
+
pool_size: tuple of 2 integers.
|
|
551
|
+
strides: tuple of 2 integers.
|
|
552
|
+
border_mode: one of "valid", "same".
|
|
553
|
+
dim_ordering: one of "th", "tf".
|
|
554
|
+
'''
|
|
555
|
+
if border_mode == 'same':
|
|
556
|
+
padding = 'SAME'
|
|
557
|
+
elif border_mode == 'valid':
|
|
558
|
+
padding = 'VALID'
|
|
559
|
+
else:
|
|
560
|
+
raise Exception('Invalid border mode: ' + str(border_mode))
|
|
561
|
+
|
|
562
|
+
strides = (1,) + strides + (1,)
|
|
563
|
+
pool_size = (1,) + pool_size + (1,)
|
|
564
|
+
|
|
565
|
+
if _FLOATX == 'float64':
|
|
566
|
+
# tf max_pool only supports float32
|
|
567
|
+
x = tf.cast(x, 'float32')
|
|
568
|
+
|
|
569
|
+
if dim_ordering == 'th':
|
|
570
|
+
# TF uses the last dimension as channel dimension,
|
|
571
|
+
# instead of the 2nd one.
|
|
572
|
+
# TH input shape: (samples, input_depth, rows, cols)
|
|
573
|
+
# TF input shape: (samples, rows, cols, input_depth)
|
|
574
|
+
# TH kernel shape: (depth, input_depth, rows, cols)
|
|
575
|
+
# TF kernel shape: (rows, cols, input_depth, depth)
|
|
576
|
+
x = tf.transpose(x, (0, 2, 3, 1))
|
|
577
|
+
x = tf.nn.max_pool(x, pool_size, strides, padding=padding)
|
|
578
|
+
x = tf.transpose(x, (0, 3, 1, 2))
|
|
579
|
+
elif dim_ordering == 'tf':
|
|
580
|
+
x = tf.nn.max_pool(x, pool_size, strides, padding=padding)
|
|
581
|
+
else:
|
|
582
|
+
raise Exception('Unknown dim_ordering: ' + str(dim_ordering))
|
|
583
|
+
|
|
584
|
+
if _FLOATX == 'float64':
|
|
585
|
+
x = tf.cast(x, 'float64')
|
|
586
|
+
return x
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
# RANDOMNESS
|
|
590
|
+
|
|
591
|
+
def random_normal(shape, mean=0.0, std=1.0, dtype=_FLOATX, seed=None):
|
|
592
|
+
if seed is None:
|
|
593
|
+
seed = np.random.randint(10e6)
|
|
594
|
+
return tf.random_normal(shape, mean=mean, stddev=std,
|
|
595
|
+
dtype=dtype, seed=seed)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None):
|
|
599
|
+
if seed is None:
|
|
600
|
+
seed = np.random.randint(10e6)
|
|
601
|
+
return tf.random_uniform(shape, minval=low, maxval=high,
|
|
602
|
+
dtype=dtype, seed=seed)
|
|
Binary file
|