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.pyc ADDED
Binary file
keras/objectives.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import absolute_import
2
+ import numpy as np
3
+ from . import backend as K
4
+
5
+
6
+ def mean_squared_error(y_true, y_pred):
7
+ return K.mean(K.square(y_pred - y_true), axis=-1)
8
+
9
+
10
+ def root_mean_squared_error(y_true, y_pred):
11
+ return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))
12
+
13
+
14
+ def mean_absolute_error(y_true, y_pred):
15
+ return K.mean(K.abs(y_pred - y_true), axis=-1)
16
+
17
+
18
+ def mean_absolute_percentage_error(y_true, y_pred):
19
+ diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), K._EPSILON, np.inf))
20
+ return 100. * K.mean(diff, axis=-1)
21
+
22
+
23
+ def mean_squared_logarithmic_error(y_true, y_pred):
24
+ first_log = K.log(K.clip(y_pred, K._EPSILON, np.inf) + 1.)
25
+ second_log = K.log(K.clip(y_true, K._EPSILON, np.inf) + 1.)
26
+ return K.mean(K.square(first_log - second_log), axis=-1)
27
+
28
+
29
+ def squared_hinge(y_true, y_pred):
30
+ return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1)
31
+
32
+
33
+ def hinge(y_true, y_pred):
34
+ return K.mean(K.maximum(1. - y_true * y_pred, 0.), axis=-1)
35
+
36
+
37
+ def categorical_crossentropy(y_true, y_pred):
38
+ '''Expects a binary class matrix instead of a vector of scalar classes
39
+ '''
40
+ return K.mean(K.categorical_crossentropy(y_pred, y_true), axis=-1)
41
+
42
+
43
+ def binary_crossentropy(y_true, y_pred):
44
+ return K.mean(K.binary_crossentropy(y_pred, y_true), axis=-1)
45
+
46
+
47
+ def poisson_loss(y_true, y_pred):
48
+ return K.mean(y_pred - y_true * K.log(y_pred + K._EPSILON), axis=-1)
49
+
50
+ # aliases
51
+ mse = MSE = mean_squared_error
52
+ rmse = RMSE = root_mean_squared_error
53
+ mae = MAE = mean_absolute_error
54
+ mape = MAPE = mean_absolute_percentage_error
55
+ msle = MSLE = mean_squared_logarithmic_error
56
+
57
+ from .utils.generic_utils import get_from_module
58
+ def get(identifier):
59
+ return get_from_module(identifier, globals(), 'objective')
keras/objectives.pyc ADDED
Binary file
keras/optimizers.py ADDED
@@ -0,0 +1,229 @@
1
+ from __future__ import absolute_import
2
+ from . import backend as K
3
+ import numpy as np
4
+ from .utils.generic_utils import get_from_module
5
+ from six.moves import zip
6
+
7
+
8
+ def clip_norm(g, c, n):
9
+ if c > 0:
10
+ g = K.switch(n >= c, g * c / n, g)
11
+ return g
12
+
13
+
14
+ def kl_divergence(p, p_hat):
15
+ return p_hat - p + p * K.log(p / p_hat)
16
+
17
+
18
+ class Optimizer(object):
19
+ def __init__(self, **kwargs):
20
+ self.__dict__.update(kwargs)
21
+ self.updates = []
22
+
23
+ def get_state(self):
24
+ return [K.get_value(u[0]) for u in self.updates]
25
+
26
+ def set_state(self, value_list):
27
+ assert len(self.updates) == len(value_list)
28
+ for u, v in zip(self.updates, value_list):
29
+ K.set_value(u[0], v)
30
+
31
+ def get_updates(self, params, constraints, loss):
32
+ raise NotImplementedError
33
+
34
+ def get_gradients(self, loss, params):
35
+ grads = K.gradients(loss, params)
36
+ if hasattr(self, 'clipnorm') and self.clipnorm > 0:
37
+ norm = K.sqrt(sum([K.sum(K.square(g)) for g in grads]))
38
+ grads = [clip_norm(g, self.clipnorm, norm) for g in grads]
39
+ if hasattr(self, 'clipvalue') and self.clipvalue > 0:
40
+ grads = [K.clip(g, -self.clipvalue, self.clipvalue) for g in grads]
41
+ return grads
42
+
43
+ def get_config(self):
44
+ return {"name": self.__class__.__name__}
45
+
46
+
47
+ class SGD(Optimizer):
48
+
49
+ def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False,
50
+ *args, **kwargs):
51
+ super(SGD, self).__init__(**kwargs)
52
+ self.__dict__.update(locals())
53
+ self.iterations = K.variable(0.)
54
+ self.lr = K.variable(lr)
55
+ self.momentum = K.variable(momentum)
56
+ self.decay = K.variable(decay)
57
+
58
+ def get_updates(self, params, constraints, loss):
59
+ grads = self.get_gradients(loss, params)
60
+ lr = self.lr * (1.0 / (1.0 + self.decay * self.iterations))
61
+ self.updates = [(self.iterations, self.iterations + 1.)]
62
+
63
+ for p, g, c in zip(params, grads, constraints):
64
+ m = K.variable(np.zeros(K.get_value(p).shape)) # momentum
65
+ v = self.momentum * m - lr * g # velocity
66
+ self.updates.append((m, v))
67
+
68
+ if self.nesterov:
69
+ new_p = p + self.momentum * v - lr * g
70
+ else:
71
+ new_p = p + v
72
+
73
+ self.updates.append((p, c(new_p))) # apply constraints
74
+ return self.updates
75
+
76
+ def get_config(self):
77
+ return {"name": self.__class__.__name__,
78
+ "lr": float(K.get_value(self.lr)),
79
+ "momentum": float(K.get_value(self.momentum)),
80
+ "decay": float(K.get_value(self.decay)),
81
+ "nesterov": self.nesterov}
82
+
83
+
84
+ class RMSprop(Optimizer):
85
+ def __init__(self, lr=0.001, rho=0.9, epsilon=1e-6, *args, **kwargs):
86
+ super(RMSprop, self).__init__(**kwargs)
87
+ self.__dict__.update(locals())
88
+ self.lr = K.variable(lr)
89
+ self.rho = K.variable(rho)
90
+
91
+ def get_updates(self, params, constraints, loss):
92
+ grads = self.get_gradients(loss, params)
93
+ accumulators = [K.variable(np.zeros(K.get_value(p).shape)) for p in params]
94
+ self.updates = []
95
+
96
+ for p, g, a, c in zip(params, grads, accumulators, constraints):
97
+ # update accumulator
98
+ new_a = self.rho * a + (1 - self.rho) * K.square(g)
99
+ self.updates.append((a, new_a))
100
+
101
+ new_p = p - self.lr * g / K.sqrt(new_a + self.epsilon)
102
+ self.updates.append((p, c(new_p))) # apply constraints
103
+ return self.updates
104
+
105
+ def get_config(self):
106
+ return {"name": self.__class__.__name__,
107
+ "lr": float(K.get_value(self.lr)),
108
+ "rho": float(K.get_value(self.rho)),
109
+ "epsilon": self.epsilon}
110
+
111
+
112
+ class Adagrad(Optimizer):
113
+ def __init__(self, lr=0.01, epsilon=1e-6, *args, **kwargs):
114
+ super(Adagrad, self).__init__(**kwargs)
115
+ self.__dict__.update(locals())
116
+ self.lr = K.variable(lr)
117
+
118
+ def get_updates(self, params, constraints, loss):
119
+ grads = self.get_gradients(loss, params)
120
+ accumulators = [K.variable(np.zeros(K.get_value(p).shape)) for p in params]
121
+ self.updates = []
122
+
123
+ for p, g, a, c in zip(params, grads, accumulators, constraints):
124
+ new_a = a + K.square(g) # update accumulator
125
+ self.updates.append((a, new_a))
126
+ new_p = p - self.lr * g / K.sqrt(new_a + self.epsilon)
127
+ self.updates.append((p, c(new_p))) # apply constraints
128
+ return self.updates
129
+
130
+ def get_config(self):
131
+ return {"name": self.__class__.__name__,
132
+ "lr": float(K.get_value(self.lr)),
133
+ "epsilon": self.epsilon}
134
+
135
+
136
+ class Adadelta(Optimizer):
137
+ '''
138
+ Reference: http://arxiv.org/abs/1212.5701
139
+ '''
140
+ def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, *args, **kwargs):
141
+ super(Adadelta, self).__init__(**kwargs)
142
+ self.__dict__.update(locals())
143
+ self.lr = K.variable(lr)
144
+
145
+ def get_updates(self, params, constraints, loss):
146
+ grads = self.get_gradients(loss, params)
147
+ accumulators = [K.variable(np.zeros(K.get_value(p).shape)) for p in params]
148
+ delta_accumulators = [K.variable(np.zeros(K.get_value(p).shape)) for p in params]
149
+ self.updates = []
150
+
151
+ for p, g, a, d_a, c in zip(params, grads, accumulators,
152
+ delta_accumulators, constraints):
153
+ # update accumulator
154
+ new_a = self.rho * a + (1 - self.rho) * K.square(g)
155
+ self.updates.append((a, new_a))
156
+
157
+ # use the new accumulator and the *old* delta_accumulator
158
+ update = g * K.sqrt(d_a + self.epsilon) / K.sqrt(new_a + self.epsilon)
159
+
160
+ new_p = p - self.lr * update
161
+ self.updates.append((p, c(new_p))) # apply constraints
162
+
163
+ # update delta_accumulator
164
+ new_d_a = self.rho * d_a + (1 - self.rho) * K.square(update)
165
+ self.updates.append((d_a, new_d_a))
166
+ return self.updates
167
+
168
+ def get_config(self):
169
+ return {"name": self.__class__.__name__,
170
+ "lr": float(K.get_value(self.lr)),
171
+ "rho": float(K.get_value(self.rho)),
172
+ "epsilon": self.epsilon}
173
+
174
+
175
+ class Adam(Optimizer):
176
+ '''
177
+ Reference: http://arxiv.org/abs/1412.6980v8
178
+
179
+ Default parameters follow those provided in the original paper.
180
+ '''
181
+ def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8,
182
+ *args, **kwargs):
183
+ super(Adam, self).__init__(**kwargs)
184
+ self.__dict__.update(locals())
185
+ self.iterations = K.variable(0)
186
+ self.lr = K.variable(lr)
187
+ self.beta_1 = K.variable(beta_1)
188
+ self.beta_2 = K.variable(beta_2)
189
+
190
+ def get_updates(self, params, constraints, loss):
191
+ grads = self.get_gradients(loss, params)
192
+ self.updates = [(self.iterations, self.iterations+1.)]
193
+
194
+ t = self.iterations + 1
195
+ lr_t = self.lr * K.sqrt(1 - K.pow(self.beta_2, t)) / (1 - K.pow(self.beta_1, t))
196
+
197
+ for p, g, c in zip(params, grads, constraints):
198
+ # zero init of moment
199
+ m = K.variable(np.zeros(K.get_value(p).shape))
200
+ # zero init of velocity
201
+ v = K.variable(np.zeros(K.get_value(p).shape))
202
+
203
+ m_t = (self.beta_1 * m) + (1 - self.beta_1) * g
204
+ v_t = (self.beta_2 * v) + (1 - self.beta_2) * K.square(g)
205
+ p_t = p - lr_t * m_t / (K.sqrt(v_t) + self.epsilon)
206
+
207
+ self.updates.append((m, m_t))
208
+ self.updates.append((v, v_t))
209
+ self.updates.append((p, c(p_t))) # apply constraints
210
+ return self.updates
211
+
212
+ def get_config(self):
213
+ return {"name": self.__class__.__name__,
214
+ "lr": float(K.get_value(self.lr)),
215
+ "beta_1": float(K.get_value(self.beta_1)),
216
+ "beta_2": float(K.get_value(self.beta_2)),
217
+ "epsilon": self.epsilon}
218
+
219
+ # aliases
220
+ sgd = SGD
221
+ rmsprop = RMSprop
222
+ adagrad = Adagrad
223
+ adadelta = Adadelta
224
+ adam = Adam
225
+
226
+
227
+ def get(identifier, kwargs=None):
228
+ return get_from_module(identifier, globals(), 'optimizer',
229
+ instantiate=True, kwargs=kwargs)
keras/optimizers.pyc ADDED
Binary file
File without changes
Binary file
@@ -0,0 +1,246 @@
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
+ def fit(self, X,
218
+ augment=False, # fit on randomly augmented samples
219
+ rounds=1, # if augment, how many augmentation passes over the data do we use
220
+ seed=None):
221
+ '''
222
+ Required for featurewise_center, featurewise_std_normalization and zca_whitening.
223
+ '''
224
+ X = np.copy(X)
225
+ if augment:
226
+ aX = np.zeros(tuple([rounds*X.shape[0]]+list(X.shape)[1:]))
227
+ for r in range(rounds):
228
+ for i in range(X.shape[0]):
229
+ img = array_to_img(X[i])
230
+ img = self.random_transform(img)
231
+ aX[i+r*X.shape[0]] = img_to_array(img)
232
+ X = aX
233
+
234
+ if self.featurewise_center:
235
+ self.mean = np.mean(X, axis=0)
236
+ X -= self.mean
237
+ if self.featurewise_std_normalization:
238
+ self.std = np.std(X, axis=0)
239
+ X /= self.std
240
+
241
+ if self.zca_whitening:
242
+ flatX = np.reshape(X, (X.shape[0], X.shape[1]*X.shape[2]*X.shape[3]))
243
+ fudge = 10e-6
244
+ sigma = np.dot(flatX.T, flatX) / flatX.shape[1]
245
+ U, S, V = linalg.svd(sigma)
246
+ self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + fudge))), U.T)
Binary file
@@ -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
Binary file