keras 0.2.0__tar.gz

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 (58) hide show
  1. Keras-0.2.0/Keras.egg-info/PKG-INFO +11 -0
  2. Keras-0.2.0/Keras.egg-info/SOURCES.txt +57 -0
  3. Keras-0.2.0/Keras.egg-info/dependency_links.txt +1 -0
  4. Keras-0.2.0/Keras.egg-info/requires.txt +5 -0
  5. Keras-0.2.0/Keras.egg-info/top_level.txt +2 -0
  6. Keras-0.2.0/PKG-INFO +11 -0
  7. Keras-0.2.0/keras/__init__.py +0 -0
  8. Keras-0.2.0/keras/activations.py +44 -0
  9. Keras-0.2.0/keras/callbacks.py +276 -0
  10. Keras-0.2.0/keras/constraints.py +48 -0
  11. Keras-0.2.0/keras/datasets/__init__.py +0 -0
  12. Keras-0.2.0/keras/datasets/cifar.py +22 -0
  13. Keras-0.2.0/keras/datasets/cifar10.py +31 -0
  14. Keras-0.2.0/keras/datasets/cifar100.py +28 -0
  15. Keras-0.2.0/keras/datasets/data_utils.py +50 -0
  16. Keras-0.2.0/keras/datasets/imdb.py +66 -0
  17. Keras-0.2.0/keras/datasets/mnist.py +23 -0
  18. Keras-0.2.0/keras/datasets/reuters.py +148 -0
  19. Keras-0.2.0/keras/initializations.py +89 -0
  20. Keras-0.2.0/keras/layers/__init__.py +0 -0
  21. Keras-0.2.0/keras/layers/advanced_activations.py +138 -0
  22. Keras-0.2.0/keras/layers/containers.py +269 -0
  23. Keras-0.2.0/keras/layers/convolutional.py +504 -0
  24. Keras-0.2.0/keras/layers/core.py +872 -0
  25. Keras-0.2.0/keras/layers/embeddings.py +153 -0
  26. Keras-0.2.0/keras/layers/noise.py +57 -0
  27. Keras-0.2.0/keras/layers/normalization.py +117 -0
  28. Keras-0.2.0/keras/layers/recurrent.py +815 -0
  29. Keras-0.2.0/keras/models.py +728 -0
  30. Keras-0.2.0/keras/objectives.py +64 -0
  31. Keras-0.2.0/keras/optimizers.py +228 -0
  32. Keras-0.2.0/keras/preprocessing/__init__.py +0 -0
  33. Keras-0.2.0/keras/preprocessing/image.py +251 -0
  34. Keras-0.2.0/keras/preprocessing/sequence.py +122 -0
  35. Keras-0.2.0/keras/preprocessing/text.py +176 -0
  36. Keras-0.2.0/keras/regularizers.py +84 -0
  37. Keras-0.2.0/keras/utils/__init__.py +0 -0
  38. Keras-0.2.0/keras/utils/generic_utils.py +133 -0
  39. Keras-0.2.0/keras/utils/io_utils.py +71 -0
  40. Keras-0.2.0/keras/utils/layer_utils.py +131 -0
  41. Keras-0.2.0/keras/utils/np_utils.py +54 -0
  42. Keras-0.2.0/keras/utils/test_utils.py +27 -0
  43. Keras-0.2.0/keras/utils/theano_utils.py +44 -0
  44. Keras-0.2.0/keras/utils/visualize_util.py +41 -0
  45. Keras-0.2.0/keras/wrappers/__init__.py +0 -0
  46. Keras-0.2.0/keras/wrappers/scikit_learn.py +266 -0
  47. Keras-0.2.0/setup.cfg +8 -0
  48. Keras-0.2.0/setup.py +17 -0
  49. Keras-0.2.0/tests/__init__.py +0 -0
  50. Keras-0.2.0/tests/manual/__init__.py +0 -0
  51. Keras-0.2.0/tests/manual/check_autoencoder.py +134 -0
  52. Keras-0.2.0/tests/manual/check_callbacks.py +236 -0
  53. Keras-0.2.0/tests/manual/check_constraints.py +100 -0
  54. Keras-0.2.0/tests/manual/check_masked_recurrent.py +130 -0
  55. Keras-0.2.0/tests/manual/check_model_utils.py +44 -0
  56. Keras-0.2.0/tests/manual/check_save_weights.py +40 -0
  57. Keras-0.2.0/tests/manual/check_wrappers.py +126 -0
  58. Keras-0.2.0/tests/manual/check_yaml.py +101 -0
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 1.1
2
+ Name: Keras
3
+ Version: 0.2.0
4
+ Summary: Theano-based Deep Learning library
5
+ Home-page: https://github.com/fchollet/keras
6
+ Author: Francois Chollet
7
+ Author-email: francois.chollet@gmail.com
8
+ License: MIT
9
+ Download-URL: https://github.com/fchollet/keras/tarball/0.2.0
10
+ Description: UNKNOWN
11
+ Platform: UNKNOWN
@@ -0,0 +1,57 @@
1
+ setup.cfg
2
+ setup.py
3
+ Keras.egg-info/PKG-INFO
4
+ Keras.egg-info/SOURCES.txt
5
+ Keras.egg-info/dependency_links.txt
6
+ Keras.egg-info/requires.txt
7
+ Keras.egg-info/top_level.txt
8
+ keras/__init__.py
9
+ keras/activations.py
10
+ keras/callbacks.py
11
+ keras/constraints.py
12
+ keras/initializations.py
13
+ keras/models.py
14
+ keras/objectives.py
15
+ keras/optimizers.py
16
+ keras/regularizers.py
17
+ keras/datasets/__init__.py
18
+ keras/datasets/cifar.py
19
+ keras/datasets/cifar10.py
20
+ keras/datasets/cifar100.py
21
+ keras/datasets/data_utils.py
22
+ keras/datasets/imdb.py
23
+ keras/datasets/mnist.py
24
+ keras/datasets/reuters.py
25
+ keras/layers/__init__.py
26
+ keras/layers/advanced_activations.py
27
+ keras/layers/containers.py
28
+ keras/layers/convolutional.py
29
+ keras/layers/core.py
30
+ keras/layers/embeddings.py
31
+ keras/layers/noise.py
32
+ keras/layers/normalization.py
33
+ keras/layers/recurrent.py
34
+ keras/preprocessing/__init__.py
35
+ keras/preprocessing/image.py
36
+ keras/preprocessing/sequence.py
37
+ keras/preprocessing/text.py
38
+ keras/utils/__init__.py
39
+ keras/utils/generic_utils.py
40
+ keras/utils/io_utils.py
41
+ keras/utils/layer_utils.py
42
+ keras/utils/np_utils.py
43
+ keras/utils/test_utils.py
44
+ keras/utils/theano_utils.py
45
+ keras/utils/visualize_util.py
46
+ keras/wrappers/__init__.py
47
+ keras/wrappers/scikit_learn.py
48
+ tests/__init__.py
49
+ tests/manual/__init__.py
50
+ tests/manual/check_autoencoder.py
51
+ tests/manual/check_callbacks.py
52
+ tests/manual/check_constraints.py
53
+ tests/manual/check_masked_recurrent.py
54
+ tests/manual/check_model_utils.py
55
+ tests/manual/check_save_weights.py
56
+ tests/manual/check_wrappers.py
57
+ tests/manual/check_yaml.py
@@ -0,0 +1,5 @@
1
+ theano
2
+ pyyaml
3
+
4
+ [h5py]
5
+ h5py
@@ -0,0 +1,2 @@
1
+ keras
2
+ tests
Keras-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 1.1
2
+ Name: Keras
3
+ Version: 0.2.0
4
+ Summary: Theano-based Deep Learning library
5
+ Home-page: https://github.com/fchollet/keras
6
+ Author: Francois Chollet
7
+ Author-email: francois.chollet@gmail.com
8
+ License: MIT
9
+ Download-URL: https://github.com/fchollet/keras/tarball/0.2.0
10
+ Description: UNKNOWN
11
+ Platform: UNKNOWN
File without changes
@@ -0,0 +1,44 @@
1
+ from __future__ import absolute_import
2
+ import theano.tensor as T
3
+
4
+
5
+ def softmax(x):
6
+ return T.nnet.softmax(x.reshape((-1, x.shape[-1]))).reshape(x.shape)
7
+
8
+
9
+ def time_distributed_softmax(x):
10
+ import warnings
11
+ warnings.warn("time_distributed_softmax is deprecated. Just use softmax!", DeprecationWarning)
12
+ return softmax(x)
13
+
14
+
15
+ def softplus(x):
16
+ return T.nnet.softplus(x)
17
+
18
+
19
+ def relu(x):
20
+ return T.nnet.relu(x)
21
+
22
+
23
+ def tanh(x):
24
+ return T.tanh(x)
25
+
26
+
27
+ def sigmoid(x):
28
+ return T.nnet.sigmoid(x)
29
+
30
+
31
+ def hard_sigmoid(x):
32
+ return T.nnet.hard_sigmoid(x)
33
+
34
+
35
+ def linear(x):
36
+ '''
37
+ The function returns the variable that is passed in, so all types work
38
+ '''
39
+ return x
40
+
41
+
42
+ from .utils.generic_utils import get_from_module
43
+ def get(identifier):
44
+ return get_from_module(identifier, globals(), 'activation function')
@@ -0,0 +1,276 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+
4
+ import numpy as np
5
+ import time, json, warnings
6
+
7
+ from collections import deque
8
+ from .utils.generic_utils import Progbar
9
+
10
+
11
+ class CallbackList(object):
12
+ def __init__(self, callbacks=[], queue_length=10):
13
+ self.callbacks = [c for c in callbacks]
14
+ self.queue_length = queue_length
15
+
16
+ def append(self, callback):
17
+ self.callbacks.append(callback)
18
+
19
+ def _set_params(self, params):
20
+ for callback in self.callbacks:
21
+ callback._set_params(params)
22
+
23
+ def _set_model(self, model):
24
+ for callback in self.callbacks:
25
+ callback._set_model(model)
26
+
27
+ def on_epoch_begin(self, epoch, logs={}):
28
+ for callback in self.callbacks:
29
+ callback.on_epoch_begin(epoch, logs)
30
+ self._delta_t_batch = 0.
31
+ self._delta_ts_batch_begin = deque([], maxlen=self.queue_length)
32
+ self._delta_ts_batch_end = deque([], maxlen=self.queue_length)
33
+
34
+ def on_epoch_end(self, epoch, logs={}):
35
+ for callback in self.callbacks:
36
+ callback.on_epoch_end(epoch, logs)
37
+
38
+ def on_batch_begin(self, batch, logs={}):
39
+ t_before_callbacks = time.time()
40
+ for callback in self.callbacks:
41
+ callback.on_batch_begin(batch, logs)
42
+ self._delta_ts_batch_begin.append(time.time() - t_before_callbacks)
43
+ delta_t_median = np.median(self._delta_ts_batch_begin)
44
+ if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1:
45
+ warnings.warn('Method on_batch_begin() is slow compared '
46
+ 'to the batch update (%f). Check your callbacks.' % delta_t_median)
47
+ self._t_enter_batch = time.time()
48
+
49
+ def on_batch_end(self, batch, logs={}):
50
+ self._delta_t_batch = time.time() - self._t_enter_batch
51
+ t_before_callbacks = time.time()
52
+ for callback in self.callbacks:
53
+ callback.on_batch_end(batch, logs)
54
+ self._delta_ts_batch_end.append(time.time() - t_before_callbacks)
55
+ delta_t_median = np.median(self._delta_ts_batch_end)
56
+ if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1:
57
+ warnings.warn('Method on_batch_end() is slow compared '
58
+ 'to the batch update (%f). Check your callbacks.' % delta_t_median)
59
+
60
+ def on_train_begin(self, logs={}):
61
+ for callback in self.callbacks:
62
+ callback.on_train_begin(logs)
63
+
64
+ def on_train_end(self, logs={}):
65
+ for callback in self.callbacks:
66
+ callback.on_train_end(logs)
67
+
68
+
69
+ class Callback(object):
70
+
71
+ def __init__(self):
72
+ pass
73
+
74
+ def _set_params(self, params):
75
+ self.params = params
76
+
77
+ def _set_model(self, model):
78
+ self.model = model
79
+
80
+ def on_epoch_begin(self, epoch, logs={}):
81
+ pass
82
+
83
+ def on_epoch_end(self, epoch, logs={}):
84
+ pass
85
+
86
+ def on_batch_begin(self, batch, logs={}):
87
+ pass
88
+
89
+ def on_batch_end(self, batch, logs={}):
90
+ pass
91
+
92
+ def on_train_begin(self, logs={}):
93
+ pass
94
+
95
+ def on_train_end(self, logs={}):
96
+ pass
97
+
98
+
99
+ class BaseLogger(Callback):
100
+ def on_train_begin(self, logs={}):
101
+ self.verbose = self.params['verbose']
102
+ self.nb_epoch = self.params['nb_epoch']
103
+
104
+ def on_epoch_begin(self, epoch, logs={}):
105
+ if self.verbose:
106
+ print('Epoch %d/%d' % (epoch + 1, self.nb_epoch))
107
+ self.progbar = Progbar(target=self.params['nb_sample'],
108
+ verbose=self.verbose)
109
+ self.seen = 0
110
+ self.totals = {}
111
+
112
+ def on_batch_begin(self, batch, logs={}):
113
+ if self.seen < self.params['nb_sample']:
114
+ self.log_values = []
115
+
116
+ def on_batch_end(self, batch, logs={}):
117
+ batch_size = logs.get('size', 0)
118
+ self.seen += batch_size
119
+
120
+ for k, v in logs.items():
121
+ if k in self.totals:
122
+ self.totals[k] += v * batch_size
123
+ else:
124
+ self.totals[k] = v * batch_size
125
+ for k in self.params['metrics']:
126
+ if k in logs:
127
+ self.log_values.append((k, logs[k]))
128
+
129
+ # skip progbar update for the last batch; will be handled by on_epoch_end
130
+ if self.verbose and self.seen < self.params['nb_sample']:
131
+ self.progbar.update(self.seen, self.log_values)
132
+
133
+ def on_epoch_end(self, epoch, logs={}):
134
+ for k in self.params['metrics']:
135
+ if k in self.totals:
136
+ self.log_values.append((k, self.totals[k] / self.seen))
137
+ if k in logs:
138
+ self.log_values.append((k, logs[k]))
139
+ if self.verbose:
140
+ self.progbar.update(self.seen, self.log_values)
141
+
142
+
143
+ class History(Callback):
144
+
145
+ def on_train_begin(self, logs={}):
146
+ self.epoch = []
147
+ self.history = {}
148
+
149
+ def on_epoch_begin(self, epoch, logs={}):
150
+ self.seen = 0
151
+ self.totals = {}
152
+
153
+ def on_batch_end(self, batch, logs={}):
154
+ batch_size = logs.get('size', 0)
155
+ self.seen += batch_size
156
+ for k, v in logs.items():
157
+ if k in self.totals:
158
+ self.totals[k] += v * batch_size
159
+ else:
160
+ self.totals[k] = v * batch_size
161
+
162
+ def on_epoch_end(self, epoch, logs={}):
163
+ self.epoch.append(epoch)
164
+ for k, v in self.totals.items():
165
+ if k not in self.history:
166
+ self.history[k] = []
167
+ self.history[k].append(v / self.seen)
168
+
169
+ for k, v in logs.items():
170
+ if k not in self.history:
171
+ self.history[k] = []
172
+ self.history[k].append(v)
173
+
174
+
175
+ class ModelCheckpoint(Callback):
176
+ def __init__(self, filepath, monitor='val_loss', verbose=0, save_best_only=False):
177
+
178
+ super(Callback, self).__init__()
179
+ self.monitor = monitor
180
+ self.verbose = verbose
181
+ self.filepath = filepath
182
+ self.save_best_only = save_best_only
183
+ self.best = np.Inf
184
+
185
+ def on_epoch_end(self, epoch, logs={}):
186
+ filepath = self.filepath.format(epoch=epoch, **logs)
187
+ if self.save_best_only:
188
+ current = logs.get(self.monitor)
189
+ if current is None:
190
+ warnings.warn("Can save best model only with %s available, skipping." % (self.monitor), RuntimeWarning)
191
+ else:
192
+ if current < self.best:
193
+ if self.verbose > 0:
194
+ print("Epoch %05d: %s improved from %0.5f to %0.5f, saving model to %s"
195
+ % (epoch, self.monitor, self.best, current, filepath))
196
+ self.best = current
197
+ self.model.save_weights(filepath, overwrite=True)
198
+ else:
199
+ if self.verbose > 0:
200
+ print("Epoch %05d: %s did not improve" % (epoch, self.monitor))
201
+ else:
202
+ if self.verbose > 0:
203
+ print("Epoch %05d: saving model to %s" % (epoch, filepath))
204
+ self.model.save_weights(filepath, overwrite=True)
205
+
206
+
207
+ class EarlyStopping(Callback):
208
+ def __init__(self, monitor='val_loss', patience=0, verbose=0):
209
+ super(Callback, self).__init__()
210
+
211
+ self.monitor = monitor
212
+ self.patience = patience
213
+ self.verbose = verbose
214
+ self.best = np.Inf
215
+ self.wait = 0
216
+
217
+ def on_epoch_end(self, epoch, logs={}):
218
+ current = logs.get(self.monitor)
219
+ if current is None:
220
+ warnings.warn("Early stopping requires %s available!" % (self.monitor), RuntimeWarning)
221
+
222
+ if current < self.best:
223
+ self.best = current
224
+ self.wait = 0
225
+ else:
226
+ if self.wait >= self.patience:
227
+ if self.verbose > 0:
228
+ print("Epoch %05d: early stopping" % (epoch))
229
+ self.model.stop_training = True
230
+ self.wait += 1
231
+
232
+
233
+ class RemoteMonitor(Callback):
234
+ def __init__(self, root='http://localhost:9000'):
235
+ self.root = root
236
+
237
+ def on_epoch_begin(self, epoch, logs={}):
238
+ self.seen = 0
239
+ self.totals = {}
240
+
241
+ def on_batch_end(self, batch, logs={}):
242
+ batch_size = logs.get('size', 0)
243
+ self.seen += batch_size
244
+ for k, v in logs.items():
245
+ if k in self.totals:
246
+ self.totals[k] += v * batch_size
247
+ else:
248
+ self.totals[k] = v * batch_size
249
+
250
+ def on_epoch_end(self, epoch, logs={}):
251
+ import requests
252
+ send = {}
253
+ send['epoch'] = epoch
254
+
255
+ for k, v in self.totals.items():
256
+ send[k] = v / self.seen
257
+ for k, v in logs.items():
258
+ send[k] = v
259
+
260
+ try:
261
+ r = requests.post(self.root + '/publish/epoch/end/', {'data': json.dumps(send)})
262
+ except:
263
+ print('Warning: could not reach RemoteMonitor root server at ' + str(self.root))
264
+
265
+
266
+ class LearningRateScheduler(Callback):
267
+ '''LearningRateScheduler
268
+ schedule is a function that gets an epoch number as input and returns a new
269
+ learning rate as output.
270
+ '''
271
+ def __init__(self, schedule):
272
+ super(LearningRateScheduler, self).__init__()
273
+ self.schedule = schedule
274
+
275
+ def on_epoch_begin(self, epoch, logs={}):
276
+ self.model.optimizer.lr.set_value(self.schedule(epoch))
@@ -0,0 +1,48 @@
1
+ from __future__ import absolute_import
2
+ import theano
3
+ import theano.tensor as T
4
+ import numpy as np
5
+
6
+
7
+ class Constraint(object):
8
+ def __call__(self, p):
9
+ return p
10
+
11
+ def get_config(self):
12
+ return {"name": self.__class__.__name__}
13
+
14
+
15
+ class MaxNorm(Constraint):
16
+ def __init__(self, m=2):
17
+ self.m = m
18
+
19
+ def __call__(self, p):
20
+ norms = T.sqrt(T.sum(T.sqr(p), axis=0))
21
+ desired = T.clip(norms, 0, self.m)
22
+ p = p * (desired / (1e-7 + norms))
23
+ return p
24
+
25
+ def get_config(self):
26
+ return {"name": self.__class__.__name__,
27
+ "m": self.m}
28
+
29
+
30
+ class NonNeg(Constraint):
31
+ def __call__(self, p):
32
+ p = theano.shared(p)
33
+ p *= T.ge(p, 0.)
34
+ return p
35
+
36
+
37
+ class UnitNorm(Constraint):
38
+ def __call__(self, p):
39
+ return p / T.sqrt(T.sum(p**2, axis=-1, keepdims=True))
40
+
41
+ identity = Constraint
42
+ maxnorm = MaxNorm
43
+ nonneg = NonNeg
44
+ unitnorm = UnitNorm
45
+
46
+ from .utils.generic_utils import get_from_module
47
+ def get(identifier, kwargs=None):
48
+ return get_from_module(identifier, globals(), 'constraint', instantiate=True, kwargs=kwargs)
File without changes
@@ -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
@@ -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)
@@ -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)
@@ -0,0 +1,50 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+
4
+ import tarfile, inspect, os
5
+ from six.moves.urllib.request import FancyURLopener
6
+
7
+ from ..utils.generic_utils import Progbar
8
+
9
+ class ParanoidURLopener(FancyURLopener):
10
+ def http_error_default(self, url, fp, errcode, errmsg, headers):
11
+ raise Exception('URL fetch failure on {}: {} -- {}'.format(url, errcode, errmsg))
12
+
13
+ def get_file(fname, origin, untar=False):
14
+ datadir = os.path.expanduser(os.path.join('~', '.keras', 'datasets'))
15
+ if not os.path.exists(datadir):
16
+ os.makedirs(datadir)
17
+
18
+ if untar:
19
+ untar_fpath = os.path.join(datadir, fname)
20
+ fpath = untar_fpath + '.tar.gz'
21
+ else:
22
+ fpath = os.path.join(datadir, fname)
23
+
24
+ try:
25
+ f = open(fpath)
26
+ except:
27
+ print('Downloading data from', origin)
28
+
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
@@ -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)
@@ -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)