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
@@ -0,0 +1,236 @@
1
+ import numpy as np
2
+ import random
3
+ import theano
4
+
5
+ from keras.models import Sequential
6
+ from keras.callbacks import Callback
7
+ from keras.layers.core import Dense, Dropout, Activation, Flatten
8
+ from keras.regularizers import l2
9
+ from keras.layers.convolutional import Convolution2D, MaxPooling2D
10
+ from keras.utils import np_utils
11
+ from keras.datasets import mnist
12
+ import keras.callbacks as cbks
13
+
14
+ from matplotlib import pyplot as plt
15
+ from matplotlib import animation
16
+
17
+ ##############################
18
+ # model DrawActivations test #
19
+ ##############################
20
+
21
+ print('Running DrawActivations test')
22
+
23
+ nb_classes = 10
24
+ batch_size = 128
25
+ nb_epoch = 10
26
+
27
+ max_train_samples = 512
28
+ max_test_samples = 1
29
+
30
+ np.random.seed(1337)
31
+
32
+ # the data, shuffled and split between tran and test sets
33
+ (X_train, y_train), (X_test, y_test) = mnist.load_data()
34
+
35
+ X_train = X_train.reshape(-1,1,28,28)[:max_train_samples]
36
+ X_train = X_train.astype("float32")
37
+ X_train /= 255
38
+
39
+ X_test = X_test.reshape(-1,1,28,28)[:max_test_samples]
40
+ X_test = X_test.astype("float32")
41
+ X_test /= 255
42
+
43
+ # convert class vectors to binary class matrices
44
+ Y_train = np_utils.to_categorical(y_train, nb_classes)[:max_train_samples]
45
+
46
+ class Frames(object):
47
+ def __init__(self, n_plots=16):
48
+ self._n_frames = 0
49
+ self._framedata = []
50
+ self._titles = []
51
+ for i in range(n_plots):
52
+ self._framedata.append([])
53
+
54
+ def add_frame(self, i, frame):
55
+ self._framedata[i].append(frame)
56
+
57
+ def set_title(self, title):
58
+ self._titles.append(title)
59
+
60
+ class SubplotTimedAnimation(animation.TimedAnimation):
61
+
62
+ def __init__(self, fig, frames, grid=(4, 4), interval=10, blit=False, **kwargs):
63
+ self.n_plots = grid[0] * grid[1]
64
+ self.axes = [fig.add_subplot(grid[0], grid[1], i + 1) for i in range(self.n_plots)]
65
+ for axis in self.axes:
66
+ axis.get_xaxis().set_ticks([])
67
+ axis.get_yaxis().set_ticks([])
68
+ self.frames = frames
69
+ self.imgs = [self.axes[i].imshow(frames._framedata[i][0], interpolation='nearest', cmap='bone') for i in range(self.n_plots)]
70
+ self.title = fig.suptitle('')
71
+ super(SubplotTimedAnimation, self).__init__(fig, interval=interval, blit=blit, **kwargs)
72
+
73
+ def _draw_frame(self, j):
74
+ for i in range(self.n_plots):
75
+ self.imgs[i].set_data(self.frames._framedata[i][j])
76
+ if len(self.frames._titles) > j:
77
+ self.title.set_text(self.frames._titles[j])
78
+ self._drawn_artists = self.imgs
79
+
80
+ def new_frame_seq(self):
81
+ return iter(range(len(self.frames._framedata[0])))
82
+
83
+ def _init_draw(self):
84
+ for img in self.imgs:
85
+ img.set_data([[]])
86
+
87
+ def combine_imgs(imgs, grid=(1,1)):
88
+ n_imgs, img_h, img_w = imgs.shape
89
+ if n_imgs != grid[0] * grid[1]:
90
+ raise ValueError()
91
+ combined = np.zeros((grid[0] * img_h, grid[1] * img_w))
92
+ for i in range(grid[0]):
93
+ for j in range(grid[1]):
94
+ combined[img_h*i:img_h*(i+1),img_w*j:img_w*(j+1)] = imgs[grid[0] * i + j]
95
+ return combined
96
+
97
+ class DrawActivations(Callback):
98
+ def __init__(self, figsize):
99
+ self.fig = plt.figure(figsize=figsize)
100
+
101
+ def on_train_begin(self, logs={}):
102
+ self.imgs = Frames(n_plots=5)
103
+
104
+ layers_0_ids = np.random.choice(32, 16, replace=False)
105
+ self.test_layer0 = theano.function([self.model.get_input()], self.model.layers[1].get_output(train=False)[0, layers_0_ids])
106
+
107
+ layers_1_ids = np.random.choice(64, 36, replace=False)
108
+ self.test_layer1 = theano.function([self.model.get_input()], self.model.layers[5].get_output(train=False)[0, layers_1_ids])
109
+
110
+ self.test_layer2 = theano.function([self.model.get_input()], self.model.layers[10].get_output(train=False)[0])
111
+
112
+ def on_epoch_begin(self, epoch, logs={}):
113
+ self.epoch = epoch
114
+
115
+ def on_batch_end(self, batch, logs={}):
116
+ if batch % 5 == 0:
117
+ self.imgs.add_frame(0, X_test[0,0])
118
+ self.imgs.add_frame(1, combine_imgs(self.test_layer0(X_test), grid=(4, 4)))
119
+ self.imgs.add_frame(2, combine_imgs(self.test_layer1(X_test), grid=(6, 6)))
120
+ self.imgs.add_frame(3, self.test_layer2(X_test).reshape((16,16)))
121
+ self.imgs.add_frame(4, self.model._predict(X_test)[0].reshape((1,10)))
122
+ self.imgs.set_title('Epoch #%d - Batch #%d' % (self.epoch, batch))
123
+
124
+ def on_train_end(self, logs={}):
125
+ anim = SubplotTimedAnimation(self.fig, self.imgs, grid=(1,5), interval=10, blit=False, repeat_delay=1000)
126
+ # anim.save('test_gif.gif', fps=15, writer='imagemagick')
127
+ plt.show()
128
+
129
+ # model = Sequential()
130
+ # model.add(Dense(784, 50))
131
+ # model.add(Activation('relu'))
132
+ # model.add(Dense(50, 10))
133
+ # model.add(Activation('softmax'))
134
+
135
+ model = Sequential()
136
+ model.add(Convolution2D(32, 1, 3, 3, border_mode='full'))
137
+ model.add(Activation('relu'))
138
+ model.add(MaxPooling2D(pool_size=(2, 2)))
139
+ model.add(Dropout(0.25))
140
+
141
+ model.add(Convolution2D(64, 32, 3, 3, border_mode='full'))
142
+ model.add(Activation('relu'))
143
+ model.add(MaxPooling2D(pool_size=(2, 2)))
144
+ model.add(Dropout(0.25))
145
+
146
+ model.add(Flatten())
147
+ model.add(Dense(64*8*8, 256))
148
+ model.add(Activation('relu'))
149
+ model.add(Dropout(0.5))
150
+
151
+ model.add(Dense(256, 10, W_regularizer = l2(0.1)))
152
+ model.add(Activation('softmax'))
153
+
154
+ model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
155
+
156
+ # Fit the model
157
+ draw_weights = DrawActivations(figsize=(5.4, 1.35))
158
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, callbacks=[draw_weights])
159
+
160
+
161
+ ##########################
162
+ # model checkpoint tests #
163
+ ##########################
164
+
165
+ print('Running ModelCheckpoint test')
166
+
167
+ nb_classes = 10
168
+ batch_size = 128
169
+ nb_epoch = 20
170
+
171
+ # small sample size to overfit on training data
172
+ max_train_samples = 50
173
+ max_test_samples = 1000
174
+
175
+ np.random.seed(1337) # for reproducibility
176
+
177
+ # the data, shuffled and split between tran and test sets
178
+ (X_train, y_train), (X_test, y_test) = mnist.load_data()
179
+
180
+ X_train = X_train.reshape(60000,784)[:max_train_samples]
181
+ X_test = X_test.reshape(10000,784)[:max_test_samples]
182
+ X_train = X_train.astype("float32")
183
+ X_test = X_test.astype("float32")
184
+ X_train /= 255
185
+ X_test /= 255
186
+
187
+ # convert class vectors to binary class matrices
188
+ Y_train = np_utils.to_categorical(y_train, nb_classes)[:max_train_samples]
189
+ Y_test = np_utils.to_categorical(y_test, nb_classes)[:max_test_samples]
190
+
191
+
192
+ # Create a slightly larger network than required to test best validation save only
193
+ model = Sequential()
194
+ model.add(Dense(784, 500))
195
+ model.add(Activation('relu'))
196
+ model.add(Dense(500, 10))
197
+ model.add(Activation('softmax'))
198
+ model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
199
+
200
+ # test file location
201
+ path = "/tmp"
202
+ filename = "model_weights.hdf5"
203
+ import os
204
+ f = os.path.join(path, filename)
205
+
206
+ print("Test model checkpointer")
207
+ # only store best validation model in checkpointer
208
+ checkpointer = cbks.ModelCheckpoint(filepath=f, verbose=1, save_best_only=True)
209
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, validation_data=(X_test, Y_test), callbacks =[checkpointer])
210
+
211
+ if not os.path.isfile(f):
212
+ raise Exception("Model weights were not saved to %s" % (f))
213
+
214
+ print("Test model checkpointer without validation data")
215
+ import warnings
216
+ warnings.filterwarnings('error')
217
+ try:
218
+ passed = False
219
+ # this should issue a warning
220
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0, callbacks =[checkpointer])
221
+ except:
222
+ passed = True
223
+ if not passed:
224
+ raise Exception("Modelcheckpoint tests did not pass")
225
+
226
+ print("Test model checkpointer with pattern")
227
+ filename = "model_weights.{epoch:04d}.hdf5"
228
+ f = os.path.join(path, filename)
229
+ nb_epoch = 3
230
+ checkpointer = cbks.ModelCheckpoint(f)
231
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, callbacks=[checkpointer])
232
+ for i in range(nb_epoch):
233
+ if not os.path.isfile(f.format(epoch=i)):
234
+ raise Exception("Model weights were not saved separately for each epoch")
235
+
236
+ print("Tests passed")
@@ -0,0 +1,100 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+ import keras
4
+ from keras.datasets import mnist
5
+ import keras.models
6
+ from keras.models import Sequential
7
+ from keras.layers.core import Dense, Dropout, Activation
8
+ from keras.regularizers import l2, l1
9
+ from keras.constraints import maxnorm, nonneg
10
+ from keras.optimizers import SGD, Adam, RMSprop
11
+ from keras.utils import np_utils, generic_utils
12
+ import theano
13
+ import theano.tensor as T
14
+ import numpy as np
15
+ import scipy
16
+
17
+ batch_size = 100
18
+ nb_classes = 10
19
+ nb_epoch = 10
20
+
21
+ # the data, shuffled and split between tran and test sets
22
+ (X_train, y_train), (X_test, y_test) = mnist.load_data()
23
+ X_train=X_train.reshape(60000,784)
24
+ X_test=X_test.reshape(10000,784)
25
+ X_train = X_train.astype("float32")
26
+ X_test = X_test.astype("float32")
27
+ X_train /= 255
28
+ X_test /= 255
29
+
30
+ # convert class vectors to binary class matrices
31
+ Y_train = np_utils.to_categorical(y_train, nb_classes)
32
+ Y_test = np_utils.to_categorical(y_test, nb_classes)
33
+
34
+ model = Sequential()
35
+ model.add(Dense(784, 20, W_constraint=maxnorm(1)))
36
+ model.add(Activation('relu'))
37
+ model.add(Dropout(0.1))
38
+ model.add(Dense(20, 20, W_constraint=nonneg()))
39
+ model.add(Activation('relu'))
40
+ model.add(Dropout(0.1))
41
+ model.add(Dense(20, 10, W_constraint=maxnorm(1)))
42
+ model.add(Activation('softmax'))
43
+
44
+
45
+ rms = RMSprop()
46
+ model.compile(loss='categorical_crossentropy', optimizer=rms)
47
+
48
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=0)
49
+
50
+ a=model.params[0].eval()
51
+ if np.isclose(np.max(np.sqrt(np.sum(a**2, axis=0))),1):
52
+ print('Maxnorm test passed')
53
+ else:
54
+ raise ValueError('Maxnorm test failed!')
55
+
56
+ b=model.params[2].eval()
57
+ if np.min(b)==0 and np.min(a)!=0:
58
+ print('Nonneg test passed')
59
+ else:
60
+ raise ValueError('Nonneg test failed!')
61
+
62
+
63
+ model = Sequential()
64
+ model.add(Dense(784, 20))
65
+ model.add(Activation('relu'))
66
+ model.add(Dense(20, 20, W_regularizer=l1(.01)))
67
+ model.add(Activation('relu'))
68
+ model.add(Dense(20, 10))
69
+ model.add(Activation('softmax'))
70
+
71
+
72
+ rms = RMSprop()
73
+ model.compile(loss='categorical_crossentropy', optimizer=rms)
74
+
75
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=20, show_accuracy=True, verbose=0)
76
+
77
+ a=model.params[2].eval().reshape(400)
78
+ (D, p1) = scipy.stats.kurtosistest(a)
79
+
80
+ model = Sequential()
81
+ model.add(Dense(784, 20))
82
+ model.add(Activation('relu'))
83
+ model.add(Dense(20, 20, W_regularizer=l2(.01)))
84
+ model.add(Activation('relu'))
85
+ model.add(Dense(20, 10))
86
+ model.add(Activation('softmax'))
87
+
88
+
89
+ rms = RMSprop()
90
+ model.compile(loss='categorical_crossentropy', optimizer=rms)
91
+
92
+ model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=20, show_accuracy=True, verbose=0)
93
+
94
+ a=model.params[2].eval().reshape(400)
95
+ (D, p2) = scipy.stats.kurtosistest(a)
96
+
97
+ if p1<.01 and p2>.01:
98
+ print('L1 and L2 regularization tests passed')
99
+ else:
100
+ raise ValueError('L1 and L2 regularization tests failed!')
@@ -0,0 +1,130 @@
1
+ # Dummy test data as input to RNN. This input is 3 timesteps long where the third timestep always matches the
2
+ # first. Without masking it should be able to learn it, with masking it should fail.
3
+
4
+ import numpy as np
5
+ from keras.utils.theano_utils import sharedX
6
+ from keras.models import Sequential
7
+ from keras.layers.core import Dense, Activation, Merge, Dropout, TimeDistributedDense
8
+ from keras.layers.embeddings import Embedding
9
+ from keras.layers.recurrent import SimpleRNN, SimpleDeepRNN, LSTM, GRU
10
+ import theano
11
+
12
+ theano.config.exception_verbosity = 'high'
13
+
14
+ # (nb_samples, timesteps, dimensions)
15
+ X = np.random.random_integers(1, 4, size=(500000, 15))
16
+
17
+ print("About to compile the first model")
18
+ model = Sequential()
19
+ model.add(Embedding(5, 4, mask_zero=True))
20
+ model.add(TimeDistributedDense(4, 4)) # obviously this is redundant. Just testing.
21
+ model.add(SimpleRNN(4, 4, activation='relu', return_sequences=True))
22
+ model.add(Dropout(0.5))
23
+ model.add(SimpleDeepRNN(4, 4, depth=2, activation='relu'))
24
+ model.add(Dropout(0.5))
25
+ model.add(Dense(4, 4, activation='softmax'))
26
+ model.compile(loss='categorical_crossentropy',
27
+ optimizer='rmsprop', theano_mode=theano.compile.mode.FAST_RUN)
28
+ print("Compiled model")
29
+
30
+ W = model.get_weights() # We'll save these so we can reset it later
31
+
32
+ X[:, : 10] = 0
33
+ Xmask0 = X.copy()
34
+ Xmask0[:, 10] = 0
35
+
36
+ Xmask12 = X.copy()
37
+ Xmask12[:, 11] = 0
38
+ Xmask12[:, 12] = 0
39
+
40
+ X0_onehot = np.zeros((X.shape[0], 4))
41
+ X1_onehot = np.zeros((X.shape[0], 4))
42
+ for i, row in enumerate(X):
43
+ X0_onehot[i, row[10] - 1] = 1
44
+ X1_onehot[i, row[11] - 1] = 1
45
+
46
+ # Uniform score: 4 options = ln(4) nats (2 bits)
47
+ # we should not do better than this when we mask out the part of the input
48
+ # that gives us the correct answer
49
+ uniform_score = np.log(4)
50
+ batch_size=512
51
+
52
+ # Train it to guess 0th dim
53
+ model.fit(X, X0_onehot, nb_epoch=1, batch_size=batch_size)
54
+ score = model.evaluate(X, X0_onehot, batch_size=batch_size)
55
+ if score > uniform_score * 0.9:
56
+ raise Exception('Failed to learn to copy timestep 0, score %f' % score)
57
+
58
+
59
+ model.set_weights(W)
60
+
61
+ # Train without showing it the 0th dim to learn 1st dim
62
+ model.fit(X[: , 1:], X1_onehot, nb_epoch=1, batch_size=batch_size)
63
+ score = model.evaluate(X[:, 1:], X1_onehot, batch_size=batch_size)
64
+ if score > uniform_score * 0.9:
65
+ raise Exception('Failed to learn to copy timestep 1, score %f' % score)
66
+
67
+ model.set_weights(W)
68
+
69
+ # Train to guess 0th dim when 0th dim has been masked (should fail)
70
+ model.fit(Xmask0, X0_onehot, nb_epoch=1, batch_size=batch_size)
71
+ score = model.evaluate(Xmask0, X0_onehot, batch_size=batch_size)
72
+ if score < uniform_score * 0.9:
73
+ raise Exception('Somehow learned to copy timestep 0 despite mask, score %f' % score)
74
+
75
+ model.set_weights(W)
76
+
77
+ # Train to guess 1st dim when 0th dim has been masked (should succeed)
78
+ model.fit(Xmask0, X1_onehot, nb_epoch=1, batch_size=batch_size)
79
+ score = model.evaluate(Xmask0, X1_onehot, batch_size=batch_size)
80
+ if score > uniform_score * 0.9:
81
+ raise Exception('Failed to learn to copy timestep 1 in masked model, score %f' % score)
82
+
83
+ model.set_weights(W)
84
+
85
+ # Finally, make sure the mask is actually blocking input, mask out timesteps 1 and 2, and see if
86
+ # it can learn timestep 0 (should fail)
87
+ model.fit(Xmask12, X0_onehot, nb_epoch=1, batch_size=batch_size)
88
+
89
+ score = model.evaluate(Xmask12, X0_onehot, batch_size=batch_size)
90
+ if score < uniform_score * 0.9:
91
+ raise Exception('Somehow learned to copy timestep 0 despite masking 1, score %f' % score)
92
+
93
+ # Another testing approach, just initialize models and make sure that prepending zeros doesn't affect
94
+ # their output
95
+ print("About to compile the second model")
96
+ model2 = Sequential()
97
+ model2.add(Embedding(5, 4, mask_zero=True))
98
+ model2.add(TimeDistributedDense(4, 4))
99
+ model2.add(Activation('time_distributed_softmax'))
100
+ model2.add(LSTM(4, 4, return_sequences=True))
101
+ model2.add(Activation('tanh'))
102
+ model2.add(GRU(4, 4, activation='softmax', return_sequences=True))
103
+ model2.add(SimpleDeepRNN(4, 4, depth=2, activation='relu', return_sequences=True))
104
+ model2.add(SimpleRNN(4, 4, activation='relu', return_sequences=True))
105
+ model2.compile(loss='categorical_crossentropy',
106
+ optimizer='rmsprop', theano_mode=theano.compile.mode.FAST_RUN)
107
+ print("Compiled model2")
108
+
109
+ X2 = np.random.random_integers(1, 4, size=(2, 5))
110
+ y2 = np.random.random((X2.shape[0], X2.shape[1], 4))
111
+
112
+ ref = model2.predict(X2)
113
+ ref_eval = model2.evaluate(X2, y2)
114
+ mask = np.ones((y2.shape[0], y2.shape[1], 1))
115
+
116
+ for pre_zeros in range(1, 10):
117
+ padded_X2 = np.concatenate((np.zeros((X2.shape[0], pre_zeros)), X2), axis=1)
118
+ padded_mask = np.concatenate((np.zeros((mask.shape[0], pre_zeros, mask.shape[2])), mask), axis=1)
119
+ padded_y2 = np.concatenate((np.zeros((y2.shape[0], pre_zeros, y2.shape[2])), y2), axis=1)
120
+
121
+ pred = model2.predict(padded_X2)
122
+ if not np.allclose(ref[:, -1, :], pred[:, -1, :]):
123
+ raise Exception("Different result after left-padding %d zeros. Ref: %s, Pred: %s" % (pre_zeros, ref, pred))
124
+
125
+ pad_eval = model2.evaluate(padded_X2, padded_y2, weights=padded_mask)
126
+ if not np.allclose([pad_eval], [ref_eval]):
127
+ raise Exception("Got dissimilar categorical_crossentropy after left-padding %d zeros. Ref: %f, Pred %f" %\
128
+ (pref_eval, pred_val))
129
+
130
+
@@ -0,0 +1,44 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+ from keras.models import Sequential, Graph
4
+ from keras.layers.core import Layer, Activation, Dense, Flatten, Reshape, Merge
5
+ from keras.layers.convolutional import Convolution2D, MaxPooling2D
6
+ import keras.utils.layer_utils as layer_utils
7
+
8
+ print('-- Sequential model')
9
+ left = Sequential()
10
+ left.add(Convolution2D(32, 1, 3, 3, border_mode='valid'))
11
+ left.add(MaxPooling2D(pool_size=(2, 2)))
12
+ left.add(Flatten())
13
+ left.add(Dense(32 * 13 * 13, 50))
14
+ left.add(Activation('relu'))
15
+
16
+ right = Sequential()
17
+ right.add(Dense(784, 30))
18
+ right.add(Activation('relu'))
19
+
20
+ model = Sequential()
21
+ model.add(Merge([left, right], mode='concat'))
22
+
23
+ model.add(Dense(80, 10))
24
+ model.add(Activation('softmax'))
25
+
26
+ layer_utils.print_layer_shapes(model, [(1, 1, 28, 28), (1, 784)])
27
+
28
+ print('-- Graph model')
29
+ graph = Graph()
30
+ graph.add_input(name='input1', ndim=2)
31
+ graph.add_input(name='input2', ndim=4)
32
+ graph.add_node(Dense(32, 16), name='dense1', input='input1')
33
+ graph.add_node(Dense(16, 4), name='dense3', input='dense1')
34
+
35
+ graph.add_node(Convolution2D(32, 1, 3, 3), name='conv1', input='input2')
36
+ graph.add_node(Flatten(), name='flatten1', input='conv1')
37
+ graph.add_node(Dense(32 * 13 * 13, 10), name='dense4', input='flatten1')
38
+
39
+ graph.add_output(name='output1', inputs=['dense1', 'dense3'], merge_mode='sum')
40
+ graph.add_output(name='output2', inputs=['dense1', 'dense4'], merge_mode='concat')
41
+
42
+ layer_utils.print_layer_shapes(graph, {'input1': (1, 32), 'input2': (1, 1, 28, 28)})
43
+
44
+ print('Test script complete')
@@ -0,0 +1,40 @@
1
+ from keras.models import Sequential
2
+ from keras.layers.core import Dense, Dropout, Activation
3
+ from keras.optimizers import SGD
4
+
5
+ import sys
6
+ sys.setrecursionlimit(10000) # to be able to pickle Theano compiled functions
7
+
8
+ import pickle, numpy
9
+
10
+ def create_model():
11
+ model = Sequential()
12
+ model.add(Dense(256, 2048, init='uniform', activation='relu'))
13
+ model.add(Dropout(0.5))
14
+ model.add(Dense(2048, 2048, init='uniform', activation='relu'))
15
+ model.add(Dropout(0.5))
16
+ model.add(Dense(2048, 2048, init='uniform', activation='relu'))
17
+ model.add(Dropout(0.5))
18
+ model.add(Dense(2048, 2048, init='uniform', activation='relu'))
19
+ model.add(Dropout(0.5))
20
+ model.add(Dense(2048, 256, init='uniform', activation='linear'))
21
+ return model
22
+
23
+ model = create_model()
24
+ sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
25
+ model.compile(loss='mse', optimizer=sgd)
26
+
27
+ pickle.dump(model, open('/tmp/model.pkl', 'wb'))
28
+ model.save_weights('/tmp/model_weights.hdf5')
29
+
30
+ model_loaded = create_model()
31
+ model_loaded.load_weights('/tmp/model_weights.hdf5')
32
+
33
+ for k in range(len(model.layers)):
34
+ weights_orig = model.layers[k].get_weights()
35
+ weights_loaded = model_loaded.layers[k].get_weights()
36
+ for x, y in zip(weights_orig, weights_loaded):
37
+ if numpy.any(x != y):
38
+ raise ValueError('Loaded weights are different from pickled weights!')
39
+
40
+
@@ -0,0 +1,126 @@
1
+ from __future__ import absolute_import
2
+ from __future__ import print_function
3
+ from keras.datasets import mnist
4
+ from keras.models import Sequential
5
+ from keras.layers.core import Dense, Activation
6
+ from keras.utils import np_utils
7
+ from keras.wrappers.scikit_learn import *
8
+ import numpy as np
9
+
10
+ batch_size = 128
11
+ nb_epoch = 1
12
+
13
+ nb_classes = 10
14
+ max_train_samples = 5000
15
+ max_test_samples = 1000
16
+
17
+ np.random.seed(1337) # for reproducibility
18
+
19
+ ############################################
20
+ # scikit-learn classification wrapper test #
21
+ ############################################
22
+ print('Beginning scikit-learn classification wrapper test')
23
+
24
+ print('Loading data')
25
+ (X_train, y_train), (X_test, y_test) = mnist.load_data()
26
+
27
+ X_train = X_train.reshape(60000, 784)[:max_train_samples]
28
+ X_test = X_test.reshape(10000, 784)[:max_test_samples]
29
+ X_train = X_train.astype('float32')
30
+ X_test = X_test.astype('float32')
31
+ X_train /= 255
32
+ X_test /= 255
33
+
34
+ Y_train = np_utils.to_categorical(y_train, nb_classes)[:max_train_samples]
35
+ Y_test = np_utils.to_categorical(y_test, nb_classes)[:max_test_samples]
36
+
37
+ print('Defining model')
38
+ model = Sequential()
39
+ model.add(Dense(784, 50))
40
+ model.add(Activation('relu'))
41
+ model.add(Dense(50, 10))
42
+ model.add(Activation('softmax'))
43
+
44
+ print('Creating wrapper')
45
+ classifier = KerasClassifier(model, train_batch_size=batch_size, nb_epoch=nb_epoch)
46
+
47
+ print('Fitting model')
48
+ classifier.fit(X_train, Y_train)
49
+
50
+ print('Testing score function')
51
+ score = classifier.score(X_train, Y_train)
52
+ print('Score: ', score)
53
+
54
+ print('Testing predict function')
55
+ preds = classifier.predict(X_test)
56
+ print('Preds.shape: ', preds.shape)
57
+
58
+ print('Testing predict proba function')
59
+ proba = classifier.predict_proba(X_test)
60
+ print('Proba.shape: ', proba.shape)
61
+
62
+ print('Testing get params')
63
+ print(classifier.get_params())
64
+
65
+ print('Testing set params')
66
+ classifier.set_params(optimizer='sgd', loss='binary_crossentropy')
67
+ print(classifier.get_params())
68
+
69
+ print('Testing attributes')
70
+ print('Classes')
71
+ print(classifier.classes_)
72
+ print('Config')
73
+ print(classifier.config_)
74
+ print('Weights')
75
+ print(classifier.weights_)
76
+ print('Compiled model')
77
+ print(classifier.compiled_model_)
78
+
79
+ ########################################
80
+ # scikit-learn regression wrapper test #
81
+ ########################################
82
+ print('Beginning scikit-learn regression wrapper test')
83
+
84
+ print('Generating data')
85
+ X_train = np.random.random((5000, 100))
86
+ X_test = np.random.random((1000, 100))
87
+ y_train = np.random.random(5000)
88
+ y_test = np.random.random(1000)
89
+
90
+ print('Defining model')
91
+ model = Sequential()
92
+ model.add(Dense(100, 50))
93
+ model.add(Activation('relu'))
94
+ model.add(Dense(50, 1))
95
+ model.add(Activation('linear'))
96
+
97
+ print('Creating wrapper')
98
+ regressor = KerasRegressor(model, train_batch_size=batch_size, nb_epoch=nb_epoch)
99
+
100
+ print('Fitting model')
101
+ regressor.fit(X_train, y_train)
102
+
103
+ print('Testing score function')
104
+ score = regressor.score(X_train, y_train)
105
+ print('Score: ', score)
106
+
107
+ print('Testing predict function')
108
+ preds = regressor.predict(X_test)
109
+ print('Preds.shape: ', preds.shape)
110
+
111
+ print('Testing get params')
112
+ print(regressor.get_params())
113
+
114
+ print('Testing set params')
115
+ regressor.set_params(optimizer='sgd', loss='mean_absolute_error')
116
+ print(regressor.get_params())
117
+
118
+ print('Testing attributes')
119
+ print('Config')
120
+ print(regressor.config_)
121
+ print('Weights')
122
+ print(regressor.weights_)
123
+ print('Compiled model')
124
+ print(regressor.compiled_model_)
125
+
126
+ print('Test script complete.')