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/objectives.py ADDED
@@ -0,0 +1,67 @@
1
+ from __future__ import absolute_import
2
+ import theano
3
+ import theano.tensor as T
4
+ import numpy as np
5
+ from six.moves import range
6
+
7
+ if theano.config.floatX == 'float64':
8
+ epsilon = 1.0e-9
9
+ else:
10
+ epsilon = 1.0e-7
11
+
12
+
13
+ def mean_squared_error(y_true, y_pred):
14
+ return T.sqr(y_pred - y_true).mean(axis=-1)
15
+
16
+ def root_mean_squared_error(y_true, y_pred):
17
+ return T.sqrt(T.sqr(y_pred - y_true).mean(axis=-1))
18
+
19
+ def mean_absolute_error(y_true, y_pred):
20
+ return T.abs_(y_pred - y_true).mean(axis=-1)
21
+
22
+
23
+ def mean_absolute_percentage_error(y_true, y_pred):
24
+ return T.abs_((y_true - y_pred) / T.clip(T.abs_(y_true), epsilon, np.inf)).mean(axis=-1) * 100.
25
+
26
+
27
+ def mean_squared_logarithmic_error(y_true, y_pred):
28
+ return T.sqr(T.log(T.clip(y_pred, epsilon, np.inf) + 1.) - T.log(T.clip(y_true, epsilon, np.inf) + 1.)).mean(axis=-1)
29
+
30
+
31
+ def squared_hinge(y_true, y_pred):
32
+ return T.sqr(T.maximum(1. - y_true * y_pred, 0.)).mean(axis=-1)
33
+
34
+
35
+ def hinge(y_true, y_pred):
36
+ return T.maximum(1. - y_true * y_pred, 0.).mean(axis=-1)
37
+
38
+
39
+ def categorical_crossentropy(y_true, y_pred):
40
+ '''Expects a binary class matrix instead of a vector of scalar classes
41
+ '''
42
+ y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
43
+ # scale preds so that the class probas of each sample sum to 1
44
+ y_pred /= y_pred.sum(axis=-1, keepdims=True)
45
+ cce = T.nnet.categorical_crossentropy(y_pred, y_true)
46
+ return cce
47
+
48
+
49
+ def binary_crossentropy(y_true, y_pred):
50
+ y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
51
+ bce = T.nnet.binary_crossentropy(y_pred, y_true).mean(axis=-1)
52
+ return bce
53
+
54
+
55
+ def poisson_loss(y_true, y_pred):
56
+ return T.mean(y_pred - y_true * T.log(y_pred + epsilon), axis=-1)
57
+
58
+ # aliases
59
+ mse = MSE = mean_squared_error
60
+ rmse = RMSE = root_mean_squared_error
61
+ mae = MAE = mean_absolute_error
62
+ mape = MAPE = mean_absolute_percentage_error
63
+ msle = MSLE = mean_squared_logarithmic_error
64
+
65
+ from .utils.generic_utils import get_from_module
66
+ def get(identifier):
67
+ return get_from_module(identifier, globals(), 'objective')
keras/optimizers.py ADDED
@@ -0,0 +1,228 @@
1
+ from __future__ import absolute_import
2
+ import theano
3
+ import theano.tensor as T
4
+
5
+ from .utils.theano_utils import shared_zeros, shared_scalar, floatX
6
+ from .utils.generic_utils import get_from_module
7
+ from six.moves import zip
8
+
9
+
10
+ def clip_norm(g, c, n):
11
+ if c > 0:
12
+ g = T.switch(T.ge(n, c), g * c / n, g)
13
+ return g
14
+
15
+
16
+ def kl_divergence(p, p_hat):
17
+ return p_hat - p + p * T.log(p / p_hat)
18
+
19
+
20
+ class Optimizer(object):
21
+ def __init__(self, **kwargs):
22
+ self.__dict__.update(kwargs)
23
+ self.updates = []
24
+
25
+ def get_state(self):
26
+ return [u[0].get_value() for u in self.updates]
27
+
28
+ def set_state(self, value_list):
29
+ assert len(self.updates) == len(value_list)
30
+ for u, v in zip(self.updates, value_list):
31
+ u[0].set_value(floatX(v))
32
+
33
+ def get_updates(self, params, constraints, loss):
34
+ raise NotImplementedError
35
+
36
+ def get_gradients(self, loss, params):
37
+
38
+ grads = T.grad(loss, params)
39
+
40
+ if hasattr(self, 'clipnorm') and self.clipnorm > 0:
41
+ norm = T.sqrt(sum([T.sum(g ** 2) for g in grads]))
42
+ grads = [clip_norm(g, self.clipnorm, norm) for g in grads]
43
+
44
+ if hasattr(self, 'clipvalue') and self.clipvalue > 0:
45
+ grads = [T.clip(g, -self.clipvalue, self.clipvalue) for g in grads]
46
+
47
+ return grads
48
+
49
+ def get_config(self):
50
+ return {"name": self.__class__.__name__}
51
+
52
+
53
+ class SGD(Optimizer):
54
+
55
+ def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False, *args, **kwargs):
56
+ super(SGD, self).__init__(**kwargs)
57
+ self.__dict__.update(locals())
58
+ self.iterations = shared_scalar(0)
59
+ self.lr = shared_scalar(lr)
60
+ self.momentum = shared_scalar(momentum)
61
+ self.decay = shared_scalar(decay)
62
+
63
+ def get_updates(self, params, constraints, loss):
64
+ grads = self.get_gradients(loss, params)
65
+ lr = self.lr * (1.0 / (1.0 + self.decay * self.iterations))
66
+ self.updates = [(self.iterations, self.iterations + 1.)]
67
+
68
+ for p, g, c in zip(params, grads, constraints):
69
+ m = shared_zeros(p.get_value().shape) # momentum
70
+ v = self.momentum * m - lr * g # velocity
71
+ self.updates.append((m, v))
72
+
73
+ if self.nesterov:
74
+ new_p = p + self.momentum * v - lr * g
75
+ else:
76
+ new_p = p + v
77
+
78
+ self.updates.append((p, c(new_p))) # apply constraints
79
+ return self.updates
80
+
81
+ def get_config(self):
82
+ return {"name": self.__class__.__name__,
83
+ "lr": float(self.lr.get_value()),
84
+ "momentum": float(self.momentum.get_value()),
85
+ "decay": float(self.decay.get_value()),
86
+ "nesterov": self.nesterov}
87
+
88
+
89
+ class RMSprop(Optimizer):
90
+ def __init__(self, lr=0.001, rho=0.9, epsilon=1e-6, *args, **kwargs):
91
+ super(RMSprop, self).__init__(**kwargs)
92
+ self.__dict__.update(locals())
93
+ self.lr = shared_scalar(lr)
94
+ self.rho = shared_scalar(rho)
95
+
96
+ def get_updates(self, params, constraints, loss):
97
+ grads = self.get_gradients(loss, params)
98
+ accumulators = [shared_zeros(p.get_value().shape) for p in params]
99
+ self.updates = []
100
+
101
+ for p, g, a, c in zip(params, grads, accumulators, constraints):
102
+ new_a = self.rho * a + (1 - self.rho) * g ** 2 # update accumulator
103
+ self.updates.append((a, new_a))
104
+
105
+ new_p = p - self.lr * g / T.sqrt(new_a + self.epsilon)
106
+ self.updates.append((p, c(new_p))) # apply constraints
107
+ return self.updates
108
+
109
+ def get_config(self):
110
+ return {"name": self.__class__.__name__,
111
+ "lr": float(self.lr.get_value()),
112
+ "rho": float(self.rho.get_value()),
113
+ "epsilon": self.epsilon}
114
+
115
+
116
+ class Adagrad(Optimizer):
117
+ def __init__(self, lr=0.01, epsilon=1e-6, *args, **kwargs):
118
+ super(Adagrad, self).__init__(**kwargs)
119
+ self.__dict__.update(locals())
120
+ self.lr = shared_scalar(lr)
121
+
122
+ def get_updates(self, params, constraints, loss):
123
+ grads = self.get_gradients(loss, params)
124
+ accumulators = [shared_zeros(p.get_value().shape) for p in params]
125
+ self.updates = []
126
+
127
+ for p, g, a, c in zip(params, grads, accumulators, constraints):
128
+ new_a = a + g ** 2 # update accumulator
129
+ self.updates.append((a, new_a))
130
+ new_p = p - self.lr * g / T.sqrt(new_a + self.epsilon)
131
+ self.updates.append((p, c(new_p))) # apply constraints
132
+ return self.updates
133
+
134
+ def get_config(self):
135
+ return {"name": self.__class__.__name__,
136
+ "lr": float(self.lr.get_value()),
137
+ "epsilon": self.epsilon}
138
+
139
+
140
+ class Adadelta(Optimizer):
141
+ '''
142
+ Reference: http://arxiv.org/abs/1212.5701
143
+ '''
144
+ def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, *args, **kwargs):
145
+ super(Adadelta, self).__init__(**kwargs)
146
+ self.__dict__.update(locals())
147
+ self.lr = shared_scalar(lr)
148
+
149
+ def get_updates(self, params, constraints, loss):
150
+ grads = self.get_gradients(loss, params)
151
+ accumulators = [shared_zeros(p.get_value().shape) for p in params]
152
+ delta_accumulators = [shared_zeros(p.get_value().shape) for p in params]
153
+ self.updates = []
154
+
155
+ for p, g, a, d_a, c in zip(params, grads, accumulators,
156
+ delta_accumulators, constraints):
157
+ new_a = self.rho * a + (1 - self.rho) * g ** 2 # update accumulator
158
+ self.updates.append((a, new_a))
159
+
160
+ # use the new accumulator and the *old* delta_accumulator
161
+ update = g * T.sqrt(d_a + self.epsilon) / T.sqrt(new_a +
162
+ self.epsilon)
163
+
164
+ new_p = p - self.lr * update
165
+ self.updates.append((p, c(new_p))) # apply constraints
166
+
167
+ # update delta_accumulator
168
+ new_d_a = self.rho * d_a + (1 - self.rho) * update ** 2
169
+ self.updates.append((d_a, new_d_a))
170
+ return self.updates
171
+
172
+ def get_config(self):
173
+ return {"name": self.__class__.__name__,
174
+ "lr": float(self.lr.get_value()),
175
+ "rho": self.rho,
176
+ "epsilon": self.epsilon}
177
+
178
+
179
+ class Adam(Optimizer):
180
+ '''
181
+ Reference: http://arxiv.org/abs/1412.6980v8
182
+
183
+ Default parameters follow those provided in the original paper.
184
+ '''
185
+ def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, *args, **kwargs):
186
+ super(Adam, self).__init__(**kwargs)
187
+ self.__dict__.update(locals())
188
+ self.iterations = shared_scalar(0)
189
+ self.lr = shared_scalar(lr)
190
+
191
+ def get_updates(self, params, constraints, loss):
192
+ grads = self.get_gradients(loss, params)
193
+ self.updates = [(self.iterations, self.iterations+1.)]
194
+
195
+ t = self.iterations + 1
196
+ lr_t = self.lr * T.sqrt(1-self.beta_2**t)/(1-self.beta_1**t)
197
+
198
+ for p, g, c in zip(params, grads, constraints):
199
+ m = theano.shared(p.get_value() * 0.) # zero init of moment
200
+ v = theano.shared(p.get_value() * 0.) # zero init of velocity
201
+
202
+ m_t = (self.beta_1 * m) + (1 - self.beta_1) * g
203
+ v_t = (self.beta_2 * v) + (1 - self.beta_2) * (g**2)
204
+ p_t = p - lr_t * m_t / (T.sqrt(v_t) + self.epsilon)
205
+
206
+ self.updates.append((m, m_t))
207
+ self.updates.append((v, v_t))
208
+ self.updates.append((p, c(p_t))) # apply constraints
209
+ return self.updates
210
+
211
+ def get_config(self):
212
+ return {"name": self.__class__.__name__,
213
+ "lr": float(self.lr.get_value()),
214
+ "beta_1": self.beta_1,
215
+ "beta_2": self.beta_2,
216
+ "epsilon": self.epsilon}
217
+
218
+ # aliases
219
+ sgd = SGD
220
+ rmsprop = RMSprop
221
+ adagrad = Adagrad
222
+ adadelta = Adadelta
223
+ adam = Adam
224
+
225
+
226
+ def get(identifier, kwargs=None):
227
+ return get_from_module(identifier, globals(), 'optimizer', instantiate=True,
228
+ kwargs=kwargs)
File without changes
@@ -0,0 +1,251 @@
1
+ from __future__ import absolute_import
2
+
3
+ import numpy as np
4
+ import re
5
+ from scipy import ndimage
6
+ from scipy import linalg
7
+
8
+ from os import listdir
9
+ from os.path import isfile, join
10
+ import random, math
11
+ from six.moves import range
12
+
13
+ '''
14
+ Fairly basic set of tools for realtime data augmentation on image data.
15
+ Can easily be extended to include new transforms, new preprocessing methods, etc...
16
+ '''
17
+
18
+ def random_rotation(x, rg, fill_mode="nearest", cval=0.):
19
+ angle = random.uniform(-rg, rg)
20
+ x = ndimage.interpolation.rotate(x, angle, axes=(1,2), reshape=False, mode=fill_mode, cval=cval)
21
+ return x
22
+
23
+ def random_shift(x, wrg, hrg, fill_mode="nearest", cval=0.):
24
+ crop_left_pixels = 0
25
+ crop_right_pixels = 0
26
+ crop_top_pixels = 0
27
+ crop_bottom_pixels = 0
28
+
29
+ original_w = x.shape[1]
30
+ original_h = x.shape[2]
31
+
32
+ if wrg:
33
+ crop = random.uniform(0., wrg)
34
+ split = random.uniform(0, 1)
35
+ crop_left_pixels = int(split*crop*x.shape[1])
36
+ crop_right_pixels = int((1-split)*crop*x.shape[1])
37
+
38
+ if hrg:
39
+ crop = random.uniform(0., hrg)
40
+ split = random.uniform(0, 1)
41
+ crop_top_pixels = int(split*crop*x.shape[2])
42
+ crop_bottom_pixels = int((1-split)*crop*x.shape[2])
43
+
44
+ x = ndimage.interpolation.shift(x, (0, crop_left_pixels, crop_top_pixels), mode=fill_mode, cval=cval)
45
+ return x
46
+
47
+ def horizontal_flip(x):
48
+ for i in range(x.shape[0]):
49
+ x[i] = np.fliplr(x[i])
50
+ return x
51
+
52
+ def vertical_flip(x):
53
+ for i in range(x.shape[0]):
54
+ x[i] = np.flipud(x[i])
55
+ return x
56
+
57
+
58
+ def random_barrel_transform(x, intensity):
59
+ # TODO
60
+ pass
61
+
62
+ def random_shear(x, intensity):
63
+ # TODO
64
+ pass
65
+
66
+ def random_channel_shift(x, rg):
67
+ # TODO
68
+ pass
69
+
70
+ def random_zoom(x, rg, fill_mode="nearest", cval=0.):
71
+ zoom_w = random.uniform(1.-rg, 1.)
72
+ zoom_h = random.uniform(1.-rg, 1.)
73
+ x = ndimage.interpolation.zoom(x, zoom=(1., zoom_w, zoom_h), mode=fill_mode, cval=cval)
74
+ return x # shape of result will be different from shape of input!
75
+
76
+
77
+
78
+
79
+ def array_to_img(x, scale=True):
80
+ from PIL import Image
81
+ x = x.transpose(1, 2, 0)
82
+ if scale:
83
+ x += max(-np.min(x), 0)
84
+ x /= np.max(x)
85
+ x *= 255
86
+ if x.shape[2] == 3:
87
+ # RGB
88
+ return Image.fromarray(x.astype("uint8"), "RGB")
89
+ else:
90
+ # grayscale
91
+ return Image.fromarray(x[:,:,0].astype("uint8"), "L")
92
+
93
+
94
+ def img_to_array(img):
95
+ x = np.asarray(img, dtype='float32')
96
+ if len(x.shape)==3:
97
+ # RGB: height, width, channel -> channel, height, width
98
+ x = x.transpose(2, 0, 1)
99
+ else:
100
+ # grayscale: height, width -> channel, height, width
101
+ x = x.reshape((1, x.shape[0], x.shape[1]))
102
+ return x
103
+
104
+
105
+ def load_img(path, grayscale=False):
106
+ from PIL import Image
107
+ img = Image.open(path)
108
+ if grayscale:
109
+ img = img.convert('L')
110
+ else: # Assure 3 channel even when loaded image is grayscale
111
+ img = img.convert('RGB')
112
+ return img
113
+
114
+
115
+ def list_pictures(directory, ext='jpg|jpeg|bmp|png'):
116
+ return [join(directory,f) for f in listdir(directory) \
117
+ if isfile(join(directory,f)) and re.match('([\w]+\.(?:' + ext + '))', f)]
118
+
119
+
120
+
121
+ class ImageDataGenerator(object):
122
+ '''
123
+ Generate minibatches with
124
+ realtime data augmentation.
125
+ '''
126
+ def __init__(self,
127
+ featurewise_center=True, # set input mean to 0 over the dataset
128
+ samplewise_center=False, # set each sample mean to 0
129
+ featurewise_std_normalization=True, # divide inputs by std of the dataset
130
+ samplewise_std_normalization=False, # divide each input by its std
131
+
132
+ zca_whitening=False, # apply ZCA whitening
133
+ rotation_range=0., # degrees (0 to 180)
134
+ width_shift_range=0., # fraction of total width
135
+ height_shift_range=0., # fraction of total height
136
+ horizontal_flip=False,
137
+ vertical_flip=False,
138
+ ):
139
+ self.__dict__.update(locals())
140
+ self.mean = None
141
+ self.std = None
142
+ self.principal_components = None
143
+
144
+
145
+ def flow(self, X, y, batch_size=32, shuffle=False, seed=None, save_to_dir=None, save_prefix="", save_format="jpeg"):
146
+ if seed:
147
+ random.seed(seed)
148
+
149
+ if shuffle:
150
+ seed = random.randint(1, 10e6)
151
+ np.random.seed(seed)
152
+ np.random.shuffle(X)
153
+ np.random.seed(seed)
154
+ np.random.shuffle(y)
155
+
156
+ nb_batch = int(math.ceil(float(X.shape[0])/batch_size))
157
+ for b in range(nb_batch):
158
+ batch_end = (b+1)*batch_size
159
+ if batch_end > X.shape[0]:
160
+ nb_samples = X.shape[0] - b*batch_size
161
+ else:
162
+ nb_samples = batch_size
163
+
164
+ bX = np.zeros(tuple([nb_samples]+list(X.shape)[1:]))
165
+ for i in range(nb_samples):
166
+ x = X[b*batch_size+i]
167
+ x = self.random_transform(x.astype("float32"))
168
+ x = self.standardize(x)
169
+ bX[i] = x
170
+
171
+ if save_to_dir:
172
+ for i in range(nb_samples):
173
+ img = array_to_img(bX[i], scale=True)
174
+ img.save(save_to_dir + "/" + save_prefix + "_" + str(i) + "." + save_format)
175
+
176
+ yield bX, y[b*batch_size:b*batch_size+nb_samples]
177
+
178
+
179
+ def standardize(self, x):
180
+ if self.featurewise_center:
181
+ x -= self.mean
182
+ if self.featurewise_std_normalization:
183
+ x /= self.std
184
+
185
+ if self.zca_whitening:
186
+ flatx = np.reshape(x, (x.shape[0]*x.shape[1]*x.shape[2]))
187
+ whitex = np.dot(flatx, self.principal_components)
188
+ x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))
189
+
190
+ if self.samplewise_center:
191
+ x -= np.mean(x)
192
+ if self.samplewise_std_normalization:
193
+ x /= np.std(x)
194
+
195
+ return x
196
+
197
+
198
+ def random_transform(self, x):
199
+ if self.rotation_range:
200
+ x = random_rotation(x, self.rotation_range)
201
+ if self.width_shift_range or self.height_shift_range:
202
+ x = random_shift(x, self.width_shift_range, self.height_shift_range)
203
+ if self.horizontal_flip:
204
+ if random.random() < 0.5:
205
+ x = horizontal_flip(x)
206
+ if self.vertical_flip:
207
+ if random.random() < 0.5:
208
+ x = vertical_flip(x)
209
+
210
+ # TODO:
211
+ # zoom
212
+ # barrel/fisheye
213
+ # shearing
214
+ # channel shifting
215
+ return x
216
+
217
+
218
+ def fit(self, X,
219
+ augment=False, # fit on randomly augmented samples
220
+ rounds=1, # if augment, how many augmentation passes over the data do we use
221
+ seed=None
222
+ ):
223
+ '''
224
+ Required for featurewise_center, featurewise_std_normalization and zca_whitening.
225
+ '''
226
+ X = np.copy(X)
227
+
228
+ if augment:
229
+ aX = np.zeros(tuple([rounds*X.shape[0]]+list(X.shape)[1:]))
230
+ for r in range(rounds):
231
+ for i in range(X.shape[0]):
232
+ img = array_to_img(X[i])
233
+ img = self.random_transform(img)
234
+ aX[i+r*X.shape[0]] = img_to_array(img)
235
+ X = aX
236
+
237
+ if self.featurewise_center:
238
+ self.mean = np.mean(X, axis=0)
239
+ X -= self.mean
240
+ if self.featurewise_std_normalization:
241
+ self.std = np.std(X, axis=0)
242
+ X /= self.std
243
+
244
+ if self.zca_whitening:
245
+ flatX = np.reshape(X, (X.shape[0], X.shape[1]*X.shape[2]*X.shape[3]))
246
+ fudge = 10e-6
247
+ sigma = np.dot(flatX.T, flatX) / flatX.shape[1]
248
+ U, S, V = linalg.svd(sigma)
249
+ self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + fudge))), U.T)
250
+
251
+
@@ -0,0 +1,124 @@
1
+ from __future__ import absolute_import
2
+ # -*- coding: utf-8 -*-
3
+ import numpy as np
4
+ import random
5
+ from six.moves import range
6
+
7
+ def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.):
8
+ """
9
+ Pad each sequence to the same length:
10
+ the length of the longest sequence.
11
+
12
+ If maxlen is provided, any sequence longer
13
+ than maxlen is truncated to maxlen. Truncation happens off either the beginning (default) or
14
+ the end of the sequence.
15
+
16
+ Supports post-padding and pre-padding (default).
17
+
18
+ """
19
+ lengths = [len(s) for s in sequences]
20
+
21
+ nb_samples = len(sequences)
22
+ if maxlen is None:
23
+ maxlen = np.max(lengths)
24
+
25
+ x = (np.ones((nb_samples, maxlen)) * value).astype(dtype)
26
+ for idx, s in enumerate(sequences):
27
+ if len(s) == 0:
28
+ continue # empty list was found
29
+ if truncating == 'pre':
30
+ trunc = s[-maxlen:]
31
+ elif truncating == 'post':
32
+ trunc = s[:maxlen]
33
+ else:
34
+ raise ValueError("Truncating type '%s' not understood" % padding)
35
+
36
+ if padding == 'post':
37
+ x[idx, :len(trunc)] = trunc
38
+ elif padding == 'pre':
39
+ x[idx, -len(trunc):] = trunc
40
+ else:
41
+ raise ValueError("Padding type '%s' not understood" % padding)
42
+ return x
43
+
44
+
45
+ def make_sampling_table(size, sampling_factor=1e-5):
46
+ '''
47
+ This generates an array where the ith element
48
+ is the probability that a word of rank i would be sampled,
49
+ according to the sampling distribution used in word2vec.
50
+
51
+ The word2vec formula is:
52
+ p(word) = min(1, sqrt(word.frequency/sampling_factor) / (word.frequency/sampling_factor))
53
+
54
+ We assume that the word frequencies follow Zipf's law (s=1) to derive
55
+ a numerical approximation of frequency(rank):
56
+ frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank))
57
+ where gamma is the Euler-Mascheroni constant.
58
+ '''
59
+ gamma = 0.577
60
+ rank = np.array(list(range(size)))
61
+ rank[0] = 1
62
+ inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1./(12.*rank)
63
+ f = sampling_factor * inv_fq
64
+ return np.minimum(1., f / np.sqrt(f))
65
+
66
+
67
+ def skipgrams(sequence, vocabulary_size,
68
+ window_size=4, negative_samples=1., shuffle=True,
69
+ categorical=False, sampling_table=None):
70
+ '''
71
+ Take a sequence (list of indexes of words),
72
+ returns couples of [word_index, other_word index] and labels (1s or 0s),
73
+ where label = 1 if 'other_word' belongs to the context of 'word',
74
+ and label=0 if 'other_word' is ramdomly sampled
75
+
76
+ @param vocabulary_size: int. maximum possible word index + 1
77
+ @param window_size: int. actually half-window. The window of a word wi will be [i-window_size, i+window_size+1]
78
+ @param negative_samples: float >= 0. 0 for no negative (=random) samples. 1 for same number as positive samples. etc.
79
+ @param categorical: bool. if False, labels will be integers (eg. [0, 1, 1 .. ]),
80
+ if True labels will be categorical eg. [[1,0],[0,1],[0,1] .. ]
81
+
82
+ Note: by convention, index 0 in the vocabulary is a non-word and will be skipped.
83
+ '''
84
+ couples = []
85
+ labels = []
86
+ for i, wi in enumerate(sequence):
87
+ if not wi:
88
+ continue
89
+ if sampling_table is not None:
90
+ if sampling_table[wi] < random.random():
91
+ continue
92
+
93
+ window_start = max(0, i-window_size)
94
+ window_end = min(len(sequence), i+window_size+1)
95
+ for j in range(window_start, window_end):
96
+ if j != i:
97
+ wj = sequence[j]
98
+ if not wj:
99
+ continue
100
+ couples.append([wi, wj])
101
+ if categorical:
102
+ labels.append([0,1])
103
+ else:
104
+ labels.append(1)
105
+
106
+ if negative_samples > 0:
107
+ nb_negative_samples = int(len(labels) * negative_samples)
108
+ words = [c[0] for c in couples]
109
+ random.shuffle(words)
110
+
111
+ couples += [[words[i%len(words)], random.randint(1, vocabulary_size-1)] for i in range(nb_negative_samples)]
112
+ if categorical:
113
+ labels += [[1,0]]*nb_negative_samples
114
+ else:
115
+ labels += [0]*nb_negative_samples
116
+
117
+ if shuffle:
118
+ seed = random.randint(0,10e6)
119
+ random.seed(seed)
120
+ random.shuffle(couples)
121
+ random.seed(seed)
122
+ random.shuffle(labels)
123
+
124
+ return couples, labels