keras 0.2.0__py2.7.egg

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