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/callbacks.py ADDED
@@ -0,0 +1,295 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+
4
+ import numpy as np
5
+ import time
6
+ import json
7
+ import warnings
8
+
9
+ from collections import deque
10
+ from .utils.generic_utils import Progbar
11
+
12
+
13
+ class CallbackList(object):
14
+ def __init__(self, callbacks=[], queue_length=10):
15
+ self.callbacks = [c for c in callbacks]
16
+ self.queue_length = queue_length
17
+
18
+ def append(self, callback):
19
+ self.callbacks.append(callback)
20
+
21
+ def _set_params(self, params):
22
+ for callback in self.callbacks:
23
+ callback._set_params(params)
24
+
25
+ def _set_model(self, model):
26
+ for callback in self.callbacks:
27
+ callback._set_model(model)
28
+
29
+ def on_epoch_begin(self, epoch, logs={}):
30
+ for callback in self.callbacks:
31
+ callback.on_epoch_begin(epoch, logs)
32
+ self._delta_t_batch = 0.
33
+ self._delta_ts_batch_begin = deque([], maxlen=self.queue_length)
34
+ self._delta_ts_batch_end = deque([], maxlen=self.queue_length)
35
+
36
+ def on_epoch_end(self, epoch, logs={}):
37
+ for callback in self.callbacks:
38
+ callback.on_epoch_end(epoch, logs)
39
+
40
+ def on_batch_begin(self, batch, logs={}):
41
+ t_before_callbacks = time.time()
42
+ for callback in self.callbacks:
43
+ callback.on_batch_begin(batch, logs)
44
+ self._delta_ts_batch_begin.append(time.time() - t_before_callbacks)
45
+ delta_t_median = np.median(self._delta_ts_batch_begin)
46
+ if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1:
47
+ warnings.warn('Method on_batch_begin() is slow compared '
48
+ 'to the batch update (%f). Check your callbacks.' % delta_t_median)
49
+ self._t_enter_batch = time.time()
50
+
51
+ def on_batch_end(self, batch, logs={}):
52
+ self._delta_t_batch = time.time() - self._t_enter_batch
53
+ t_before_callbacks = time.time()
54
+ for callback in self.callbacks:
55
+ callback.on_batch_end(batch, logs)
56
+ self._delta_ts_batch_end.append(time.time() - t_before_callbacks)
57
+ delta_t_median = np.median(self._delta_ts_batch_end)
58
+ if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1:
59
+ warnings.warn('Method on_batch_end() is slow compared '
60
+ 'to the batch update (%f). Check your callbacks.' % delta_t_median)
61
+
62
+ def on_train_begin(self, logs={}):
63
+ for callback in self.callbacks:
64
+ callback.on_train_begin(logs)
65
+
66
+ def on_train_end(self, logs={}):
67
+ for callback in self.callbacks:
68
+ callback.on_train_end(logs)
69
+
70
+
71
+ class Callback(object):
72
+
73
+ def __init__(self):
74
+ pass
75
+
76
+ def _set_params(self, params):
77
+ self.params = params
78
+
79
+ def _set_model(self, model):
80
+ self.model = model
81
+
82
+ def on_epoch_begin(self, epoch, logs={}):
83
+ pass
84
+
85
+ def on_epoch_end(self, epoch, logs={}):
86
+ pass
87
+
88
+ def on_batch_begin(self, batch, logs={}):
89
+ pass
90
+
91
+ def on_batch_end(self, batch, logs={}):
92
+ pass
93
+
94
+ def on_train_begin(self, logs={}):
95
+ pass
96
+
97
+ def on_train_end(self, logs={}):
98
+ pass
99
+
100
+
101
+ class BaseLogger(Callback):
102
+ def on_train_begin(self, logs={}):
103
+ self.verbose = self.params['verbose']
104
+ self.nb_epoch = self.params['nb_epoch']
105
+
106
+ def on_epoch_begin(self, epoch, logs={}):
107
+ if self.verbose:
108
+ print('Epoch %d/%d' % (epoch + 1, self.nb_epoch))
109
+ self.progbar = Progbar(target=self.params['nb_sample'],
110
+ verbose=self.verbose)
111
+ self.seen = 0
112
+ self.totals = {}
113
+
114
+ def on_batch_begin(self, batch, logs={}):
115
+ if self.seen < self.params['nb_sample']:
116
+ self.log_values = []
117
+
118
+ def on_batch_end(self, batch, logs={}):
119
+ batch_size = logs.get('size', 0)
120
+ self.seen += batch_size
121
+
122
+ for k, v in logs.items():
123
+ if k in self.totals:
124
+ self.totals[k] += v * batch_size
125
+ else:
126
+ self.totals[k] = v * batch_size
127
+ for k in self.params['metrics']:
128
+ if k in logs:
129
+ self.log_values.append((k, logs[k]))
130
+
131
+ # skip progbar update for the last batch; will be handled by on_epoch_end
132
+ if self.verbose and self.seen < self.params['nb_sample']:
133
+ self.progbar.update(self.seen, self.log_values)
134
+
135
+ def on_epoch_end(self, epoch, logs={}):
136
+ for k in self.params['metrics']:
137
+ if k in self.totals:
138
+ self.log_values.append((k, self.totals[k] / self.seen))
139
+ if k in logs:
140
+ self.log_values.append((k, logs[k]))
141
+ if self.verbose:
142
+ self.progbar.update(self.seen, self.log_values)
143
+
144
+
145
+ class History(Callback):
146
+
147
+ def on_train_begin(self, logs={}):
148
+ self.epoch = []
149
+ self.history = {}
150
+
151
+ def on_epoch_begin(self, epoch, logs={}):
152
+ self.seen = 0
153
+ self.totals = {}
154
+
155
+ def on_batch_end(self, batch, logs={}):
156
+ batch_size = logs.get('size', 0)
157
+ self.seen += batch_size
158
+ for k, v in logs.items():
159
+ if k in self.totals:
160
+ self.totals[k] += v * batch_size
161
+ else:
162
+ self.totals[k] = v * batch_size
163
+
164
+ def on_epoch_end(self, epoch, logs={}):
165
+ self.epoch.append(epoch)
166
+ for k, v in self.totals.items():
167
+ if k not in self.history:
168
+ self.history[k] = []
169
+ self.history[k].append(v / self.seen)
170
+
171
+ for k, v in logs.items():
172
+ if k not in self.history:
173
+ self.history[k] = []
174
+ self.history[k].append(v)
175
+
176
+
177
+ class ModelCheckpoint(Callback):
178
+ def __init__(self, filepath, monitor='val_loss', verbose=0, save_best_only=False, mode='auto'):
179
+
180
+ super(Callback, self).__init__()
181
+ self.monitor = monitor
182
+ self.verbose = verbose
183
+ self.filepath = filepath
184
+ self.save_best_only = save_best_only
185
+
186
+ if mode not in ['auto', 'min', 'max']:
187
+ warnings.warn("ModelCheckpoint mode %s is unknown, fallback to auto mode" % (self.mode), RuntimeWarning)
188
+ mode = 'auto'
189
+
190
+ if mode == "min":
191
+ self.monitor_op = np.less
192
+ self.best = np.Inf
193
+ elif mode == "max":
194
+ self.monitor_op = np.greater
195
+ self.best = -np.Inf
196
+ else:
197
+ if "acc" in self.monitor:
198
+ self.monitor_op = np.greater
199
+ self.best = -np.Inf
200
+ else:
201
+ self.monitor_op = np.less
202
+ self.best = np.Inf
203
+
204
+ def on_epoch_end(self, epoch, logs={}):
205
+ filepath = self.filepath.format(epoch=epoch, **logs)
206
+ if self.save_best_only:
207
+ current = logs.get(self.monitor)
208
+ if current is None:
209
+ warnings.warn("Can save best model only with %s available, skipping." % (self.monitor), RuntimeWarning)
210
+ else:
211
+ if self.monitor_op(current, self.best):
212
+ if self.verbose > 0:
213
+ print("Epoch %05d: %s improved from %0.5f to %0.5f, saving model to %s"
214
+ % (epoch, self.monitor, self.best, current, filepath))
215
+ self.best = current
216
+ self.model.save_weights(filepath, overwrite=True)
217
+ else:
218
+ if self.verbose > 0:
219
+ print("Epoch %05d: %s did not improve" % (epoch, self.monitor))
220
+ else:
221
+ if self.verbose > 0:
222
+ print("Epoch %05d: saving model to %s" % (epoch, filepath))
223
+ self.model.save_weights(filepath, overwrite=True)
224
+
225
+
226
+ class EarlyStopping(Callback):
227
+ def __init__(self, monitor='val_loss', patience=0, verbose=0):
228
+ super(Callback, self).__init__()
229
+
230
+ self.monitor = monitor
231
+ self.patience = patience
232
+ self.verbose = verbose
233
+ self.best = np.Inf
234
+ self.wait = 0
235
+
236
+ def on_epoch_end(self, epoch, logs={}):
237
+ current = logs.get(self.monitor)
238
+ if current is None:
239
+ warnings.warn("Early stopping requires %s available!" % (self.monitor), RuntimeWarning)
240
+
241
+ if current < self.best:
242
+ self.best = current
243
+ self.wait = 0
244
+ else:
245
+ if self.wait >= self.patience:
246
+ if self.verbose > 0:
247
+ print("Epoch %05d: early stopping" % (epoch))
248
+ self.model.stop_training = True
249
+ self.wait += 1
250
+
251
+
252
+ class RemoteMonitor(Callback):
253
+ def __init__(self, root='http://localhost:9000'):
254
+ self.root = root
255
+
256
+ def on_epoch_begin(self, epoch, logs={}):
257
+ self.seen = 0
258
+ self.totals = {}
259
+
260
+ def on_batch_end(self, batch, logs={}):
261
+ batch_size = logs.get('size', 0)
262
+ self.seen += batch_size
263
+ for k, v in logs.items():
264
+ if k in self.totals:
265
+ self.totals[k] += v * batch_size
266
+ else:
267
+ self.totals[k] = v * batch_size
268
+
269
+ def on_epoch_end(self, epoch, logs={}):
270
+ import requests
271
+ send = {}
272
+ send['epoch'] = epoch
273
+
274
+ for k, v in self.totals.items():
275
+ send[k] = v / self.seen
276
+ for k, v in logs.items():
277
+ send[k] = v
278
+
279
+ try:
280
+ r = requests.post(self.root + '/publish/epoch/end/', {'data': json.dumps(send)})
281
+ except:
282
+ print('Warning: could not reach RemoteMonitor root server at ' + str(self.root))
283
+
284
+
285
+ class LearningRateScheduler(Callback):
286
+ '''LearningRateScheduler
287
+ schedule is a function that gets an epoch number as input and returns a new
288
+ learning rate as output.
289
+ '''
290
+ def __init__(self, schedule):
291
+ super(LearningRateScheduler, self).__init__()
292
+ self.schedule = schedule
293
+
294
+ def on_epoch_begin(self, epoch, logs={}):
295
+ self.model.optimizer.lr.set_value(self.schedule(epoch))
keras/callbacks.pyc ADDED
Binary file
keras/constraints.py ADDED
@@ -0,0 +1,45 @@
1
+ from __future__ import absolute_import
2
+ from . import backend as K
3
+
4
+
5
+ class Constraint(object):
6
+ def __call__(self, p):
7
+ return p
8
+
9
+ def get_config(self):
10
+ return {"name": self.__class__.__name__}
11
+
12
+
13
+ class MaxNorm(Constraint):
14
+ def __init__(self, m=2):
15
+ self.m = m
16
+
17
+ def __call__(self, p):
18
+ norms = K.sqrt(K.sum(K.square(p), axis=0))
19
+ desired = K.clip(norms, 0, self.m)
20
+ p = p * (desired / (1e-7 + norms))
21
+ return p
22
+
23
+ def get_config(self):
24
+ return {"name": self.__class__.__name__,
25
+ "m": self.m}
26
+
27
+
28
+ class NonNeg(Constraint):
29
+ def __call__(self, p):
30
+ p *= K.cast(p >= 0., K.floatx())
31
+ return p
32
+
33
+
34
+ class UnitNorm(Constraint):
35
+ def __call__(self, p):
36
+ return p / K.sqrt(K.sum(K.square(p), axis=-1, keepdims=True))
37
+
38
+ identity = Constraint
39
+ maxnorm = MaxNorm
40
+ nonneg = NonNeg
41
+ unitnorm = UnitNorm
42
+
43
+ from .utils.generic_utils import get_from_module
44
+ def get(identifier, kwargs=None):
45
+ return get_from_module(identifier, globals(), 'constraint', instantiate=True, kwargs=kwargs)
keras/constraints.pyc ADDED
Binary file
File without changes
Binary file
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import absolute_import
3
+ import sys
4
+ from six.moves import cPickle
5
+ from six.moves import range
6
+
7
+ def load_batch(fpath, label_key='labels'):
8
+ f = open(fpath, 'rb')
9
+ if sys.version_info < (3,):
10
+ d = cPickle.load(f)
11
+ else:
12
+ d = cPickle.load(f, encoding="bytes")
13
+ # decode utf8
14
+ for k, v in d.items():
15
+ del(d[k])
16
+ d[k.decode("utf8")] = v
17
+ f.close()
18
+ data = d["data"]
19
+ labels = d[label_key]
20
+
21
+ data = data.reshape(data.shape[0], 3, 32, 32)
22
+ return data, labels
Binary file
@@ -0,0 +1,31 @@
1
+ from __future__ import absolute_import
2
+ from .cifar import load_batch
3
+ from .data_utils import get_file
4
+ import numpy as np
5
+ import os
6
+
7
+
8
+ def load_data():
9
+ dirname = "cifar-10-batches-py"
10
+ origin = "http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
11
+ path = get_file(dirname, origin=origin, untar=True)
12
+
13
+ nb_test_samples = 10000
14
+ nb_train_samples = 50000
15
+
16
+ X_train = np.zeros((nb_train_samples, 3, 32, 32), dtype="uint8")
17
+ y_train = np.zeros((nb_train_samples,), dtype="uint8")
18
+
19
+ for i in range(1, 6):
20
+ fpath = os.path.join(path, 'data_batch_' + str(i))
21
+ data, labels = load_batch(fpath)
22
+ X_train[(i-1)*10000:i*10000, :, :, :] = data
23
+ y_train[(i-1)*10000:i*10000] = labels
24
+
25
+ fpath = os.path.join(path, 'test_batch')
26
+ X_test, y_test = load_batch(fpath)
27
+
28
+ y_train = np.reshape(y_train, (len(y_train), 1))
29
+ y_test = np.reshape(y_test, (len(y_test), 1))
30
+
31
+ return (X_train, y_train), (X_test, y_test)
Binary file
@@ -0,0 +1,28 @@
1
+ from __future__ import absolute_import
2
+ from .cifar import load_batch
3
+ from .data_utils import get_file
4
+ import numpy as np
5
+ import os
6
+
7
+
8
+ def load_data(label_mode='fine'):
9
+ if label_mode not in ['fine', 'coarse']:
10
+ raise Exception('label_mode must be one of "fine" "coarse".')
11
+
12
+ dirname = "cifar-100-python"
13
+ origin = "http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
14
+ path = get_file(dirname, origin=origin, untar=True)
15
+
16
+ nb_test_samples = 10000
17
+ nb_train_samples = 50000
18
+
19
+ fpath = os.path.join(path, 'train')
20
+ X_train, y_train = load_batch(fpath, label_key=label_mode+'_labels')
21
+
22
+ fpath = os.path.join(path, 'test')
23
+ X_test, y_test = load_batch(fpath, label_key=label_mode+'_labels')
24
+
25
+ y_train = np.reshape(y_train, (len(y_train), 1))
26
+ y_test = np.reshape(y_test, (len(y_test), 1))
27
+
28
+ return (X_train, y_train), (X_test, y_test)
Binary file
@@ -0,0 +1,50 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+
4
+ import tarfile
5
+ import os
6
+ from six.moves.urllib.request import FancyURLopener
7
+
8
+ from ..utils.generic_utils import Progbar
9
+
10
+
11
+ class ParanoidURLopener(FancyURLopener):
12
+ def http_error_default(self, url, fp, errcode, errmsg, headers):
13
+ raise Exception('URL fetch failure on {}: {} -- {}'.format(url, errcode, errmsg))
14
+
15
+
16
+ def get_file(fname, origin, untar=False):
17
+ datadir = os.path.expanduser(os.path.join('~', '.keras', 'datasets'))
18
+ if not os.path.exists(datadir):
19
+ os.makedirs(datadir)
20
+
21
+ if untar:
22
+ untar_fpath = os.path.join(datadir, fname)
23
+ fpath = untar_fpath + '.tar.gz'
24
+ else:
25
+ fpath = os.path.join(datadir, fname)
26
+
27
+ if not os.path.exists(fpath):
28
+ print('Downloading data from', origin)
29
+ global progbar
30
+ progbar = None
31
+
32
+ def dl_progress(count, block_size, total_size):
33
+ global progbar
34
+ if progbar is None:
35
+ progbar = Progbar(total_size)
36
+ else:
37
+ progbar.update(count*block_size)
38
+
39
+ ParanoidURLopener().retrieve(origin, fpath, dl_progress)
40
+ progbar = None
41
+
42
+ if untar:
43
+ if not os.path.exists(untar_fpath):
44
+ print('Untaring file...')
45
+ tfile = tarfile.open(fpath, 'r:gz')
46
+ tfile.extractall(path=datadir)
47
+ tfile.close()
48
+ return untar_fpath
49
+
50
+ return fpath
Binary file
keras/datasets/imdb.py ADDED
@@ -0,0 +1,66 @@
1
+ from __future__ import absolute_import
2
+ from six.moves import cPickle
3
+ import gzip
4
+ from .data_utils import get_file
5
+ import random
6
+ from six.moves import zip
7
+ import numpy as np
8
+
9
+
10
+ def load_data(path="imdb.pkl", nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113,
11
+ start_char=1, oov_char=2, index_from=3):
12
+
13
+ path = get_file(path, origin="https://s3.amazonaws.com/text-datasets/imdb.pkl")
14
+
15
+ if path.endswith(".gz"):
16
+ f = gzip.open(path, 'rb')
17
+ else:
18
+ f = open(path, 'rb')
19
+
20
+ X, labels = cPickle.load(f)
21
+ f.close()
22
+
23
+ np.random.seed(seed)
24
+ np.random.shuffle(X)
25
+ np.random.seed(seed)
26
+ np.random.shuffle(labels)
27
+
28
+ if start_char is not None:
29
+ X = [[start_char] + [w + index_from for w in x] for x in X]
30
+ elif index_from:
31
+ X = [[w + index_from for w in x] for x in X]
32
+
33
+ if maxlen:
34
+ new_X = []
35
+ new_labels = []
36
+ for x, y in zip(X, labels):
37
+ if len(x) < maxlen:
38
+ new_X.append(x)
39
+ new_labels.append(y)
40
+ X = new_X
41
+ labels = new_labels
42
+
43
+ if not nb_words:
44
+ nb_words = max([max(x) for x in X])
45
+
46
+ # by convention, use 2 as OOV word
47
+ # reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)
48
+ if oov_char is not None:
49
+ X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]
50
+ else:
51
+ nX = []
52
+ for x in X:
53
+ nx = []
54
+ for w in x:
55
+ if (w >= nb_words or w < skip_top):
56
+ nx.append(w)
57
+ nX.append(nx)
58
+ X = nX
59
+
60
+ X_train = X[:int(len(X)*(1-test_split))]
61
+ y_train = labels[:int(len(X)*(1-test_split))]
62
+
63
+ X_test = X[int(len(X)*(1-test_split)):]
64
+ y_test = labels[int(len(X)*(1-test_split)):]
65
+
66
+ return (X_train, y_train), (X_test, y_test)
Binary file
@@ -0,0 +1,23 @@
1
+ # -*- coding: utf-8 -*-
2
+ import gzip
3
+ from .data_utils import get_file
4
+ from six.moves import cPickle
5
+ import sys
6
+
7
+
8
+ def load_data(path="mnist.pkl.gz"):
9
+ path = get_file(path, origin="https://s3.amazonaws.com/img-datasets/mnist.pkl.gz")
10
+
11
+ if path.endswith(".gz"):
12
+ f = gzip.open(path, 'rb')
13
+ else:
14
+ f = open(path, 'rb')
15
+
16
+ if sys.version_info < (3,):
17
+ data = cPickle.load(f)
18
+ else:
19
+ data = cPickle.load(f, encoding="bytes")
20
+
21
+ f.close()
22
+
23
+ return data # (X_train, y_train), (X_test, y_test)
Binary file