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/models.py ADDED
@@ -0,0 +1,733 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+ import theano
4
+ import theano.tensor as T
5
+ import numpy as np
6
+ import warnings, time, copy, pprint
7
+ from six.moves import range
8
+ import six
9
+
10
+ from . import optimizers
11
+ from . import objectives
12
+ from . import regularizers
13
+ from . import constraints
14
+ from . import callbacks as cbks
15
+ from .utils.layer_utils import container_from_config
16
+ from .utils.generic_utils import Progbar, printv
17
+ from .layers import containers
18
+
19
+
20
+ def standardize_y(y):
21
+ if not hasattr(y, 'shape'):
22
+ y = np.asarray(y)
23
+ if len(y.shape) == 1:
24
+ y = np.expand_dims(y, 1)
25
+ return y
26
+
27
+
28
+ def batch_shuffle(index_array, batch_size):
29
+ batch_count = int(len(index_array)/batch_size)
30
+ # to reshape we need to be cleanly divisible by batch size
31
+ # we stash extra items and reappend them after shuffling
32
+ last_batch = index_array[batch_count*batch_size:]
33
+ index_array = index_array[:batch_count*batch_size]
34
+ index_array = index_array.reshape((batch_count, batch_size))
35
+ np.random.shuffle(index_array)
36
+ index_array = index_array.flatten()
37
+ return np.append(index_array, last_batch)
38
+
39
+
40
+ def make_batches(size, batch_size):
41
+ nb_batch = int(np.ceil(size/float(batch_size)))
42
+ return [(i*batch_size, min(size, (i+1)*batch_size)) for i in range(0, nb_batch)]
43
+
44
+
45
+ def standardize_X(X):
46
+ if type(X) == list:
47
+ return X
48
+ else:
49
+ return [X]
50
+
51
+
52
+ def slice_X(X, start=None, stop=None):
53
+ if type(X) == list:
54
+ if hasattr(start, '__len__'):
55
+ # hdf5 dataset only support list object as indices
56
+ if hasattr(start, 'shape'):
57
+ start = start.tolist()
58
+ return [x[start] for x in X]
59
+ else:
60
+ return [x[start:stop] for x in X]
61
+ else:
62
+ if hasattr(start, '__len__'):
63
+ if hasattr(start, 'shape'):
64
+ start = start.tolist()
65
+ return X[start]
66
+ else:
67
+ return X[start:stop]
68
+
69
+
70
+ def weighted_objective(fn):
71
+ def weighted(y_true, y_pred, weights, mask=None):
72
+ # it's important that 0 * Inf == 0, not NaN, so we need to filter
73
+ # those out first
74
+ filtered_y_true = y_true[weights.nonzero()[:-1]]
75
+ filtered_y_pred = y_pred[weights.nonzero()[:-1]]
76
+ filtered_weights = weights[weights.nonzero()]
77
+ obj_output = fn(filtered_y_true, filtered_y_pred)
78
+ weighted = filtered_weights * obj_output
79
+ if mask is None:
80
+ # Instead of calling mean() here, we divide by the sum of filtered_weights.
81
+ return weighted.sum() / filtered_weights.sum()
82
+ else:
83
+ filtered_mask = mask[weights.nonzero()[:-1]]
84
+ return weighted.sum() / (filtered_mask * filtered_weights).sum()
85
+ return weighted
86
+
87
+
88
+ def standardize_weights(y, sample_weight=None, class_weight=None):
89
+ if sample_weight is not None:
90
+ return standardize_y(sample_weight)
91
+ elif isinstance(class_weight, dict):
92
+ if len(y.shape) > 3:
93
+ raise Exception('class_weight not supported for 4+ dimensional targets.')
94
+ yshape = y.shape
95
+ y = np.reshape(y, (-1, yshape[-1])) # for time-distributed data, collapse time and sample
96
+ if y.shape[1] > 1:
97
+ y_classes = y.argmax(axis=1)
98
+ elif y.shape[1] == 1:
99
+ y_classes = np.reshape(y, y.shape[0])
100
+ else:
101
+ y_classes = y
102
+ class_weights = np.asarray([class_weight[cls] for cls in y_classes])
103
+ return np.reshape(class_weights, yshape[:-1] + (1,)) # uncollapse initial dimensions
104
+ else:
105
+ return np.ones(y.shape[:-1] + (1,))
106
+
107
+
108
+ def model_from_yaml(yaml_string, custom_objects={}):
109
+ '''
110
+ Returns a model generated from a local yaml file,
111
+ which is either created by hand or from to_yaml method of Sequential or Graph
112
+ '''
113
+ import yaml
114
+ config = yaml.load(yaml_string)
115
+ return model_from_config(config, custom_objects=custom_objects)
116
+
117
+
118
+ def model_from_json(json_string, custom_objects={}):
119
+ import json
120
+ config = json.loads(json_string)
121
+ return model_from_config(config, custom_objects=custom_objects)
122
+
123
+
124
+ def model_from_config(config, custom_objects={}):
125
+ model_name = config.get('name')
126
+ if model_name not in {'Graph', 'Sequential'}:
127
+ raise Exception('Unrecognized model:', model_name)
128
+
129
+ # Create a container then set class to appropriate model
130
+ model = container_from_config(config, custom_objects=custom_objects)
131
+ if model_name == 'Graph':
132
+ model.__class__ = Graph
133
+ elif model_name == 'Sequential':
134
+ model.__class__ = Sequential
135
+
136
+ if 'optimizer' in config:
137
+ # if it has an optimizer, the model is assumed to be compiled
138
+ loss = config.get('loss')
139
+ class_mode = config.get('class_mode')
140
+ theano_mode = config.get('theano_mode')
141
+
142
+ optimizer_params = dict([(k, v) for k, v in config.get('optimizer').items()])
143
+ optimizer_name = optimizer_params.pop('name')
144
+ optimizer = optimizers.get(optimizer_name, optimizer_params)
145
+
146
+ if model_name == 'Sequential':
147
+ model.compile(loss=loss, optimizer=optimizer, class_mode=class_mode, theano_mode=theano_mode)
148
+ elif model_name == 'Graph':
149
+ model.compile(loss=loss, optimizer=optimizer, theano_mode=theano_mode)
150
+
151
+ return model
152
+
153
+
154
+ def get_function_name(o):
155
+ if isinstance(o, six.string_types):
156
+ return o
157
+ else:
158
+ return o.__name__
159
+
160
+
161
+ class Model(object):
162
+ def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
163
+ val_f=None, val_ins=None, shuffle=True, metrics=[]):
164
+ '''
165
+ Abstract fit function for f(*ins). Assume that f returns a list, labelled by out_labels.
166
+ '''
167
+ do_validation = False
168
+ if val_f and val_ins:
169
+ do_validation = True
170
+ if verbose:
171
+ print("Train on %d samples, validate on %d samples" % (len(ins[0]), len(val_ins[0])))
172
+
173
+ nb_train_sample = len(ins[0])
174
+ index_array = np.arange(nb_train_sample)
175
+
176
+ history = cbks.History()
177
+ if verbose:
178
+ callbacks = [history, cbks.BaseLogger()] + callbacks
179
+ else:
180
+ callbacks = [history] + callbacks
181
+ callbacks = cbks.CallbackList(callbacks)
182
+
183
+ callbacks._set_model(self)
184
+ callbacks._set_params({
185
+ 'batch_size': batch_size,
186
+ 'nb_epoch': nb_epoch,
187
+ 'nb_sample': nb_train_sample,
188
+ 'verbose': verbose,
189
+ 'do_validation': do_validation,
190
+ 'metrics': metrics,
191
+ })
192
+ callbacks.on_train_begin()
193
+
194
+ self.stop_training = False
195
+ for epoch in range(nb_epoch):
196
+ callbacks.on_epoch_begin(epoch)
197
+ if shuffle == 'batch':
198
+ index_array = batch_shuffle(index_array, batch_size)
199
+ elif shuffle:
200
+ np.random.shuffle(index_array)
201
+
202
+ batches = make_batches(nb_train_sample, batch_size)
203
+ for batch_index, (batch_start, batch_end) in enumerate(batches):
204
+ batch_ids = index_array[batch_start:batch_end]
205
+ try:
206
+ ins_batch = slice_X(ins, batch_ids)
207
+ except TypeError as err:
208
+ raise Exception('TypeError while preparing batch. \
209
+ If using HDF5 input data, pass shuffle="batch".\n')
210
+
211
+ batch_logs = {}
212
+ batch_logs['batch'] = batch_index
213
+ batch_logs['size'] = len(batch_ids)
214
+ callbacks.on_batch_begin(batch_index, batch_logs)
215
+ outs = f(*ins_batch)
216
+ if type(outs) != list:
217
+ outs = [outs]
218
+ for l, o in zip(out_labels, outs):
219
+ batch_logs[l] = o
220
+
221
+ callbacks.on_batch_end(batch_index, batch_logs)
222
+
223
+ epoch_logs = {}
224
+ if batch_index == len(batches) - 1: # last batch
225
+ # validation
226
+ if do_validation:
227
+ # replace with self._evaluate
228
+ val_outs = self._test_loop(val_f, val_ins, batch_size=batch_size, verbose=0)
229
+ if type(val_outs) != list:
230
+ val_outs = [val_outs]
231
+ # same labels assumed
232
+ for l, o in zip(out_labels, val_outs):
233
+ epoch_logs['val_' + l] = o
234
+
235
+ callbacks.on_epoch_end(epoch, epoch_logs)
236
+ if self.stop_training:
237
+ break
238
+
239
+ callbacks.on_train_end()
240
+ return history
241
+
242
+ def _predict_loop(self, f, ins, batch_size=128, verbose=0):
243
+ '''
244
+ Abstract method to loop over some data in batches.
245
+ '''
246
+ nb_sample = len(ins[0])
247
+ outs = []
248
+ if verbose == 1:
249
+ progbar = Progbar(target=nb_sample)
250
+ batches = make_batches(nb_sample, batch_size)
251
+ index_array = np.arange(nb_sample)
252
+ for batch_index, (batch_start, batch_end) in enumerate(batches):
253
+ batch_ids = index_array[batch_start:batch_end]
254
+ ins_batch = slice_X(ins, batch_ids)
255
+
256
+ batch_outs = f(*ins_batch)
257
+ if type(batch_outs) != list:
258
+ batch_outs = [batch_outs]
259
+ if batch_index == 0:
260
+ for batch_out in batch_outs:
261
+ shape = (nb_sample,) + batch_out.shape[1:]
262
+ outs.append(np.zeros(shape))
263
+
264
+ for i, batch_out in enumerate(batch_outs):
265
+ outs[i][batch_start:batch_end] = batch_out
266
+ if verbose == 1:
267
+ progbar.update(batch_end)
268
+ return outs
269
+
270
+ def _test_loop(self, f, ins, batch_size=128, verbose=0):
271
+ '''
272
+ Abstract method to loop over some data in batches.
273
+ '''
274
+ nb_sample = len(ins[0])
275
+ outs = []
276
+ if verbose == 1:
277
+ progbar = Progbar(target=nb_sample)
278
+ batches = make_batches(nb_sample, batch_size)
279
+ index_array = np.arange(nb_sample)
280
+ for batch_index, (batch_start, batch_end) in enumerate(batches):
281
+ batch_ids = index_array[batch_start:batch_end]
282
+ ins_batch = slice_X(ins, batch_ids)
283
+
284
+ batch_outs = f(*ins_batch)
285
+ if type(batch_outs) == list:
286
+ if batch_index == 0:
287
+ for batch_out in enumerate(batch_outs):
288
+ outs.append(0.)
289
+ for i, batch_out in enumerate(batch_outs):
290
+ outs[i] += batch_out * len(batch_ids)
291
+ else:
292
+ if batch_index == 0:
293
+ outs.append(0.)
294
+ outs[0] += batch_outs * len(batch_ids)
295
+
296
+ if verbose == 1:
297
+ progbar.update(batch_end)
298
+ for i, out in enumerate(outs):
299
+ outs[i] /= nb_sample
300
+ return outs
301
+
302
+ def get_config(self, verbose=0):
303
+ config = super(Model, self).get_config()
304
+ for p in ['class_mode', 'theano_mode']:
305
+ if hasattr(self, p):
306
+ config[p] = getattr(self, p)
307
+ if hasattr(self, 'optimizer'):
308
+ config['optimizer'] = self.optimizer.get_config()
309
+ if hasattr(self, 'loss'):
310
+ if type(self.loss) == dict:
311
+ config['loss'] = dict([(k, get_function_name(v)) for k, v in self.loss.items()])
312
+ else:
313
+ config['loss'] = get_function_name(self.loss)
314
+
315
+ if verbose:
316
+ pp = pprint.PrettyPrinter(indent=4)
317
+ pp.pprint(config)
318
+ return config
319
+
320
+ def to_yaml(self, **kwargs):
321
+ # dump model configuration to yaml string
322
+ import yaml
323
+ config = self.get_config()
324
+ return yaml.dump(config, **kwargs)
325
+
326
+ def to_json(self, **kwargs):
327
+ # dump model configuration to json string
328
+ import json
329
+ config = self.get_config()
330
+ return json.dumps(config, **kwargs)
331
+
332
+
333
+ class Sequential(Model, containers.Sequential):
334
+ '''
335
+ Inherits from Model the following methods:
336
+ - _fit
337
+ - _predict
338
+ - _evaluate
339
+ Inherits from containers.Sequential the following methods:
340
+ - __init__
341
+ - add
342
+ - get_output
343
+ - get_input
344
+ - get_weights
345
+ - set_weights
346
+ '''
347
+
348
+ def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None):
349
+ self.optimizer = optimizers.get(optimizer)
350
+
351
+ self.loss = objectives.get(loss)
352
+ weighted_loss = weighted_objective(objectives.get(loss))
353
+
354
+ # input of model
355
+ self.X_train = self.get_input(train=True)
356
+ self.X_test = self.get_input(train=False)
357
+
358
+ self.y_train = self.get_output(train=True)
359
+ self.y_test = self.get_output(train=False)
360
+
361
+ # target of model
362
+ self.y = T.zeros_like(self.y_train)
363
+
364
+ self.weights = T.ones_like(self.y_train)
365
+
366
+ if hasattr(self.layers[-1], "get_output_mask"):
367
+ mask = self.layers[-1].get_output_mask()
368
+ else:
369
+ mask = None
370
+ train_loss = weighted_loss(self.y, self.y_train, self.weights, mask)
371
+ test_loss = weighted_loss(self.y, self.y_test, self.weights, mask)
372
+
373
+ train_loss.name = 'train_loss'
374
+ test_loss.name = 'test_loss'
375
+ self.y.name = 'y'
376
+
377
+ if class_mode == "categorical":
378
+ train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))
379
+ test_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_test, axis=-1)))
380
+
381
+ elif class_mode == "binary":
382
+ train_accuracy = T.mean(T.eq(self.y, T.round(self.y_train)))
383
+ test_accuracy = T.mean(T.eq(self.y, T.round(self.y_test)))
384
+ else:
385
+ raise Exception("Invalid class mode:" + str(class_mode))
386
+ self.class_mode = class_mode
387
+ self.theano_mode = theano_mode
388
+
389
+ for r in self.regularizers:
390
+ train_loss = r(train_loss)
391
+ updates = self.optimizer.get_updates(self.params, self.constraints, train_loss)
392
+ updates += self.updates
393
+
394
+ if type(self.X_train) == list:
395
+ train_ins = self.X_train + [self.y, self.weights]
396
+ test_ins = self.X_test + [self.y, self.weights]
397
+ predict_ins = self.X_test
398
+ else:
399
+ train_ins = [self.X_train, self.y, self.weights]
400
+ test_ins = [self.X_test, self.y, self.weights]
401
+ predict_ins = [self.X_test]
402
+
403
+ self._train = theano.function(train_ins, train_loss, updates=updates,
404
+ allow_input_downcast=True, mode=theano_mode)
405
+ self._train_with_acc = theano.function(train_ins, [train_loss, train_accuracy], updates=updates,
406
+ allow_input_downcast=True, mode=theano_mode)
407
+ self._predict = theano.function(predict_ins, self.y_test,
408
+ allow_input_downcast=True, mode=theano_mode)
409
+ self._test = theano.function(test_ins, test_loss,
410
+ allow_input_downcast=True, mode=theano_mode)
411
+ self._test_with_acc = theano.function(test_ins, [test_loss, test_accuracy],
412
+ allow_input_downcast=True, mode=theano_mode)
413
+
414
+ def train_on_batch(self, X, y, accuracy=False, class_weight=None, sample_weight=None):
415
+ X = standardize_X(X)
416
+ y = standardize_y(y)
417
+ sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight)
418
+
419
+ ins = X + [y, sample_weight]
420
+ if accuracy:
421
+ return self._train_with_acc(*ins)
422
+ else:
423
+ return self._train(*ins)
424
+
425
+ def test_on_batch(self, X, y, accuracy=False, sample_weight=None):
426
+ X = standardize_X(X)
427
+ y = standardize_y(y)
428
+ sample_weight = standardize_weights(y, sample_weight=sample_weight)
429
+
430
+ ins = X + [y, sample_weight]
431
+ if accuracy:
432
+ return self._test_with_acc(*ins)
433
+ else:
434
+ return self._test(*ins)
435
+
436
+ def predict_on_batch(self, X):
437
+ ins = standardize_X(X)
438
+ return self._predict(*ins)
439
+
440
+ def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
441
+ validation_split=0., validation_data=None, shuffle=True, show_accuracy=False,
442
+ class_weight=None, sample_weight=None):
443
+
444
+ X = standardize_X(X)
445
+ y = standardize_y(y)
446
+
447
+ val_f = None
448
+ val_ins = None
449
+ if validation_data or validation_split:
450
+ if show_accuracy:
451
+ val_f = self._test_with_acc
452
+ else:
453
+ val_f = self._test
454
+ if validation_data:
455
+ if len(validation_data) == 2:
456
+ X_val, y_val = validation_data
457
+ X_val = standardize_X(X_val)
458
+ y_val = standardize_y(y_val)
459
+ sample_weight_val = np.ones(y_val.shape[:-1] + (1,))
460
+ elif len(validation_data) == 3:
461
+ X_val, y_val, sample_weight_val = validation_data
462
+ X_val = standardize_X(X_val)
463
+ y_val = standardize_y(y_val)
464
+ sample_weight_val = standardize_weights(y_val, sample_weight=sample_weight_val)
465
+ else:
466
+ raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val) or (X_val, y_val, sample_weight). \
467
+ X_val may be a numpy array or a list of numpy arrays depending on your model input.")
468
+ val_ins = X_val + [y_val, sample_weight_val]
469
+
470
+ elif 0 < validation_split < 1:
471
+ split_at = int(len(X[0]) * (1 - validation_split))
472
+ X, X_val = (slice_X(X, 0, split_at), slice_X(X, split_at))
473
+ y, y_val = (slice_X(y, 0, split_at), slice_X(y, split_at))
474
+ if sample_weight is not None:
475
+ sample_weight, sample_weight_val = (slice_X(sample_weight, 0, split_at), slice_X(sample_weight, split_at))
476
+ sample_weight_val = standardize_weights(y_val, sample_weight=sample_weight_val)
477
+ else:
478
+ sample_weight_val = np.ones(y_val.shape[:-1] + (1,))
479
+ val_ins = X_val + [y_val, sample_weight_val]
480
+
481
+ if show_accuracy:
482
+ f = self._train_with_acc
483
+ out_labels = ['loss', 'acc']
484
+ else:
485
+ f = self._train
486
+ out_labels = ['loss']
487
+
488
+ sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight)
489
+ ins = X + [y, sample_weight]
490
+ metrics = ['loss', 'acc', 'val_loss', 'val_acc']
491
+ return self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch,
492
+ verbose=verbose, callbacks=callbacks,
493
+ val_f=val_f, val_ins=val_ins,
494
+ shuffle=shuffle, metrics=metrics)
495
+
496
+ def predict(self, X, batch_size=128, verbose=0):
497
+ X = standardize_X(X)
498
+ return self._predict_loop(self._predict, X, batch_size, verbose)[0]
499
+
500
+ def predict_proba(self, X, batch_size=128, verbose=1):
501
+ preds = self.predict(X, batch_size, verbose)
502
+ if preds.min() < 0 or preds.max() > 1:
503
+ warnings.warn("Network returning invalid probability values.")
504
+ return preds
505
+
506
+ def predict_classes(self, X, batch_size=128, verbose=1):
507
+ proba = self.predict(X, batch_size=batch_size, verbose=verbose)
508
+ if self.class_mode == "categorical":
509
+ return proba.argmax(axis=-1)
510
+ else:
511
+ return (proba > 0.5).astype('int32')
512
+
513
+ def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1, sample_weight=None):
514
+ X = standardize_X(X)
515
+ y = standardize_y(y)
516
+ sample_weight = standardize_weights(y, sample_weight=sample_weight)
517
+
518
+ ins = X + [y, sample_weight]
519
+ if show_accuracy:
520
+ f = self._test_with_acc
521
+ else:
522
+ f = self._test
523
+ outs = self._test_loop(f, ins, batch_size, verbose)
524
+ if show_accuracy:
525
+ return outs
526
+ else:
527
+ return outs[0]
528
+
529
+ def save_weights(self, filepath, overwrite=False):
530
+ # Save weights from all layers to HDF5
531
+ import h5py
532
+ import os.path
533
+ # if file exists and should not be overwritten
534
+ if not overwrite and os.path.isfile(filepath):
535
+ import sys
536
+ get_input = input
537
+ if sys.version_info[:2] <= (2, 7):
538
+ get_input = raw_input
539
+ overwrite = get_input('[WARNING] %s already exists - overwrite? [y/n]' % (filepath))
540
+ while overwrite not in ['y', 'n']:
541
+ overwrite = get_input('Enter "y" (overwrite) or "n" (cancel).')
542
+ if overwrite == 'n':
543
+ return
544
+ print('[TIP] Next time specify overwrite=True in save_weights!')
545
+
546
+ f = h5py.File(filepath, 'w')
547
+ f.attrs['nb_layers'] = len(self.layers)
548
+ for k, l in enumerate(self.layers):
549
+ g = f.create_group('layer_{}'.format(k))
550
+ weights = l.get_weights()
551
+ g.attrs['nb_params'] = len(weights)
552
+ for n, param in enumerate(weights):
553
+ param_name = 'param_{}'.format(n)
554
+ param_dset = g.create_dataset(param_name, param.shape, dtype=param.dtype)
555
+ param_dset[:] = param
556
+ f.flush()
557
+ f.close()
558
+
559
+ def load_weights(self, filepath):
560
+ '''
561
+ This method does not make use of Sequential.set_weights()
562
+ for backwards compatibility.
563
+ '''
564
+ # Loads weights from HDF5 file
565
+ import h5py
566
+ f = h5py.File(filepath)
567
+ for k in range(f.attrs['nb_layers']):
568
+ g = f['layer_{}'.format(k)]
569
+ weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
570
+ self.layers[k].set_weights(weights)
571
+ f.close()
572
+
573
+
574
+ class Graph(Model, containers.Graph):
575
+ def compile(self, optimizer, loss, theano_mode=None):
576
+ # loss is a dictionary mapping output name to loss functions
577
+ ys = []
578
+ ys_train = []
579
+ ys_test = []
580
+ weights = []
581
+ train_loss = 0.
582
+ test_loss = 0.
583
+ for output_name in self.output_order:
584
+ loss_fn = loss[output_name]
585
+ output = self.outputs[output_name]
586
+ y_train = output.get_output(True)
587
+ y_test = output.get_output(False)
588
+ y = T.zeros_like(y_test)
589
+ ys.append(y)
590
+ ys_train.append(y_train)
591
+ ys_test.append(y_test)
592
+
593
+ if hasattr(output, "get_output_mask"):
594
+ mask = output.get_output_mask()
595
+ else:
596
+ mask = None
597
+
598
+ weight = T.ones_like(y_test)
599
+ weights.append(weight)
600
+ weighted_loss = weighted_objective(objectives.get(loss_fn))
601
+ train_loss += weighted_loss(y, y_train, weight, mask)
602
+ test_loss += weighted_loss(y, y_test, weight, mask)
603
+
604
+ train_loss.name = 'train_loss'
605
+ test_loss.name = 'test_loss'
606
+
607
+ ins = [self.inputs[name].input for name in self.input_order]
608
+ train_ins = ins + ys + weights
609
+ test_ins = ins + ys + weights
610
+
611
+ for r in self.regularizers:
612
+ train_loss = r(train_loss)
613
+ self.optimizer = optimizers.get(optimizer)
614
+ updates = self.optimizer.get_updates(self.params, self.constraints, train_loss)
615
+ updates += self.updates
616
+ self.theano_mode = theano_mode
617
+ self.loss = loss
618
+
619
+ self._train = theano.function(train_ins, train_loss, updates=updates,
620
+ allow_input_downcast=True, mode=theano_mode)
621
+ self._test = theano.function(test_ins, test_loss,
622
+ allow_input_downcast=True, mode=theano_mode)
623
+ self._predict = theano.function(inputs=ins, outputs=ys_test,
624
+ allow_input_downcast=True, mode=theano_mode)
625
+
626
+ def train_on_batch(self, data, class_weight={}, sample_weight={}):
627
+ # data is a dictionary mapping output and input names to arrays
628
+ sample_weight = [standardize_weights(data[name],
629
+ sample_weight=sample_weight.get(name),
630
+ class_weight=class_weight.get(name)) for name in self.output_order]
631
+ ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight
632
+ return self._train(*ins)
633
+
634
+ def test_on_batch(self, data, sample_weight={}):
635
+ # data is a dictionary mapping input names to arrays
636
+ sample_weight = [standardize_weights(data[name],
637
+ sample_weight=sample_weight.get(name)) for name in self.output_order]
638
+ ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight
639
+ return self._test(*ins)
640
+
641
+ def predict_on_batch(self, data):
642
+ # data is a dictionary mapping input names to arrays
643
+ ins = [data[name] for name in self.input_order]
644
+ return self._predict(*ins)
645
+
646
+ def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
647
+ validation_split=0., validation_data=None, shuffle=True, class_weight={}, sample_weight={}):
648
+ X = [data[name] for name in self.input_order]
649
+ y = [standardize_y(data[name]) for name in self.output_order]
650
+
651
+ sample_weight_list = [standardize_weights(y[i],
652
+ sample_weight=sample_weight.get(self.output_order[i])) for i in range(len(self.output_order))]
653
+ class_weight_list = [class_weight.get(name) for name in self.output_order]
654
+
655
+ val_f = None
656
+ val_ins = None
657
+ if validation_data or validation_split:
658
+ val_f = self._test
659
+ if validation_data:
660
+ # can't use sample weights with validation data at this point
661
+ sample_weight = [standardize_weights(validation_data[name]) for name in self.output_order]
662
+ val_ins = [validation_data[name] for name in self.input_order] + [standardize_y(validation_data[name]) for name in self.output_order] + sample_weight
663
+
664
+ elif 0 < validation_split < 1:
665
+ split_at = int(len(X[0]) * (1 - validation_split))
666
+ X, X_val = (slice_X(X, 0, split_at), slice_X(X, split_at))
667
+ y, y_val = (slice_X(y, 0, split_at), slice_X(y, split_at))
668
+ sample_weight_list, sample_weight_list_val = (slice_X(sample_weight_list, 0, split_at), slice_X(sample_weight_list, split_at))
669
+ val_ins = X_val + y_val + sample_weight_list_val
670
+
671
+ f = self._train
672
+ out_labels = ['loss']
673
+ metrics = ['loss', 'val_loss']
674
+
675
+ sample_weight_list = [standardize_weights(y[i],
676
+ sample_weight=sample_weight_list[i],
677
+ class_weight=class_weight_list[i]) for i in range(len(self.output_order))]
678
+ ins = X + y + sample_weight_list
679
+ history = self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch,
680
+ verbose=verbose, callbacks=callbacks,
681
+ val_f=val_f, val_ins=val_ins,
682
+ shuffle=shuffle, metrics=metrics)
683
+ return history
684
+
685
+ def evaluate(self, data, batch_size=128, verbose=0, sample_weight={}):
686
+ sample_weight = [standardize_weights(data[name],
687
+ sample_weight=sample_weight.get(name)) for name in self.output_order]
688
+
689
+ ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight
690
+ outs = self._test_loop(self._test, ins, batch_size, verbose)
691
+ return outs[0]
692
+
693
+ def predict(self, data, batch_size=128, verbose=0):
694
+ ins = [data[name] for name in self.input_order]
695
+ outs = self._predict_loop(self._predict, ins, batch_size, verbose)
696
+ return dict(zip(self.output_order, outs))
697
+
698
+ def save_weights(self, filepath, overwrite=False):
699
+ # Save weights from all layers to HDF5
700
+ import h5py
701
+ import os.path
702
+ # if file exists and should not be overwritten
703
+ if not overwrite and os.path.isfile(filepath):
704
+ import sys
705
+ get_input = input
706
+ if sys.version_info[:2] <= (2, 7):
707
+ get_input = raw_input
708
+ overwrite = get_input('[WARNING] %s already exists - overwrite? [y/n]' % (filepath))
709
+ while overwrite not in ['y', 'n']:
710
+ overwrite = get_input('Enter "y" (overwrite) or "n" (cancel).')
711
+ if overwrite == 'n':
712
+ return
713
+ print('[TIP] Next time specify overwrite=True in save_weights!')
714
+
715
+ f = h5py.File(filepath, 'w')
716
+ g = f.create_group('graph')
717
+ weights = self.get_weights()
718
+ g.attrs['nb_params'] = len(weights)
719
+ for n, param in enumerate(weights):
720
+ param_name = 'param_{}'.format(n)
721
+ param_dset = g.create_dataset(param_name, param.shape, dtype=param.dtype)
722
+ param_dset[:] = param
723
+ f.flush()
724
+ f.close()
725
+
726
+ def load_weights(self, filepath):
727
+ # Loads weights from HDF5 file
728
+ import h5py
729
+ f = h5py.File(filepath)
730
+ g = f['graph']
731
+ weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
732
+ self.set_weights(weights)
733
+ f.close()