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.
- EGG-INFO/PKG-INFO +11 -0
- EGG-INFO/SOURCES.txt +51 -0
- EGG-INFO/dependency_links.txt +1 -0
- EGG-INFO/requires.txt +6 -0
- EGG-INFO/top_level.txt +1 -0
- EGG-INFO/zip-safe +1 -0
- keras/__init__.py +15 -0
- keras/__init__.pyc +0 -0
- keras/activations.py +49 -0
- keras/activations.pyc +0 -0
- keras/backend/__init__.py +39 -0
- keras/backend/__init__.pyc +0 -0
- keras/backend/common.py +31 -0
- keras/backend/common.pyc +0 -0
- keras/backend/tensorflow_backend.py +602 -0
- keras/backend/tensorflow_backend.pyc +0 -0
- keras/backend/theano_backend.py +622 -0
- keras/backend/theano_backend.pyc +0 -0
- keras/callbacks.py +295 -0
- keras/callbacks.pyc +0 -0
- keras/constraints.py +45 -0
- keras/constraints.pyc +0 -0
- keras/datasets/__init__.py +0 -0
- keras/datasets/__init__.pyc +0 -0
- keras/datasets/cifar.py +22 -0
- keras/datasets/cifar.pyc +0 -0
- keras/datasets/cifar10.py +31 -0
- keras/datasets/cifar10.pyc +0 -0
- keras/datasets/cifar100.py +28 -0
- keras/datasets/cifar100.pyc +0 -0
- keras/datasets/data_utils.py +50 -0
- keras/datasets/data_utils.pyc +0 -0
- keras/datasets/imdb.py +66 -0
- keras/datasets/imdb.pyc +0 -0
- keras/datasets/mnist.py +23 -0
- keras/datasets/mnist.pyc +0 -0
- keras/datasets/reuters.py +148 -0
- keras/datasets/reuters.pyc +0 -0
- keras/initializations.py +86 -0
- keras/initializations.pyc +0 -0
- keras/layers/__init__.py +0 -0
- keras/layers/__init__.pyc +0 -0
- keras/layers/advanced_activations.py +156 -0
- keras/layers/advanced_activations.pyc +0 -0
- keras/layers/containers.py +405 -0
- keras/layers/containers.pyc +0 -0
- keras/layers/convolutional.py +505 -0
- keras/layers/convolutional.pyc +0 -0
- keras/layers/core.py +1428 -0
- keras/layers/core.pyc +0 -0
- keras/layers/embeddings.py +88 -0
- keras/layers/embeddings.pyc +0 -0
- keras/layers/noise.py +55 -0
- keras/layers/noise.pyc +0 -0
- keras/layers/normalization.py +123 -0
- keras/layers/normalization.pyc +0 -0
- keras/layers/ntm.py +326 -0
- keras/layers/ntm.pyc +0 -0
- keras/layers/recurrent.py +354 -0
- keras/layers/recurrent.pyc +0 -0
- keras/models.py +743 -0
- keras/models.pyc +0 -0
- keras/objectives.py +59 -0
- keras/objectives.pyc +0 -0
- keras/optimizers.py +229 -0
- keras/optimizers.pyc +0 -0
- keras/preprocessing/__init__.py +0 -0
- keras/preprocessing/__init__.pyc +0 -0
- keras/preprocessing/image.py +246 -0
- keras/preprocessing/image.pyc +0 -0
- keras/preprocessing/sequence.py +124 -0
- keras/preprocessing/sequence.pyc +0 -0
- keras/preprocessing/text.py +176 -0
- keras/preprocessing/text.pyc +0 -0
- keras/regularizers.py +86 -0
- keras/regularizers.pyc +0 -0
- keras/utils/__init__.py +0 -0
- keras/utils/__init__.pyc +0 -0
- keras/utils/generic_utils.py +133 -0
- keras/utils/generic_utils.pyc +0 -0
- keras/utils/io_utils.py +71 -0
- keras/utils/io_utils.pyc +0 -0
- keras/utils/layer_utils.py +93 -0
- keras/utils/layer_utils.pyc +0 -0
- keras/utils/np_utils.py +53 -0
- keras/utils/np_utils.pyc +0 -0
- keras/utils/test_utils.py +27 -0
- keras/utils/test_utils.pyc +0 -0
- keras/utils/theano_utils.py +44 -0
- keras/utils/theano_utils.pyc +0 -0
- keras/utils/visualize_util.py +41 -0
- keras/utils/visualize_util.pyc +0 -0
- keras/wrappers/__init__.py +0 -0
- keras/wrappers/__init__.pyc +0 -0
- keras/wrappers/scikit_learn.py +266 -0
- keras/wrappers/scikit_learn.pyc +0 -0
- tests/__init__.py +0 -0
- tests/__init__.pyc +0 -0
- tests/manual/__init__.py +0 -0
- tests/manual/__init__.pyc +0 -0
- tests/manual/check_autoencoder.py +134 -0
- tests/manual/check_autoencoder.pyc +0 -0
- tests/manual/check_callbacks.py +236 -0
- tests/manual/check_callbacks.pyc +0 -0
- tests/manual/check_constraints.py +100 -0
- tests/manual/check_constraints.pyc +0 -0
- tests/manual/check_masked_recurrent.py +130 -0
- tests/manual/check_masked_recurrent.pyc +0 -0
- tests/manual/check_model_utils.py +44 -0
- tests/manual/check_model_utils.pyc +0 -0
- tests/manual/check_save_weights.py +40 -0
- tests/manual/check_save_weights.pyc +0 -0
- tests/manual/check_wrappers.py +126 -0
- tests/manual/check_wrappers.pyc +0 -0
- tests/manual/check_yaml.py +101 -0
- tests/manual/check_yaml.pyc +0 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
import numpy as np
|
|
3
|
+
import theano
|
|
4
|
+
import theano.tensor as T
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def floatX(X):
|
|
8
|
+
return np.asarray(X, dtype=theano.config.floatX)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def sharedX(X, dtype=theano.config.floatX, name=None):
|
|
12
|
+
return theano.shared(np.asarray(X, dtype=dtype), name=name)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def shared_zeros(shape, dtype=theano.config.floatX, name=None):
|
|
16
|
+
return sharedX(np.zeros(shape), dtype=dtype, name=name)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def shared_scalar(val=0., dtype=theano.config.floatX, name=None):
|
|
20
|
+
return theano.shared(np.cast[dtype](val))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def shared_ones(shape, dtype=theano.config.floatX, name=None):
|
|
24
|
+
return sharedX(np.ones(shape), dtype=dtype, name=name)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def alloc_zeros_matrix(*dims):
|
|
28
|
+
return T.alloc(np.cast[theano.config.floatX](0.), *dims)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ndim_tensor(ndim):
|
|
32
|
+
if ndim == 1:
|
|
33
|
+
return T.vector()
|
|
34
|
+
elif ndim == 2:
|
|
35
|
+
return T.matrix()
|
|
36
|
+
elif ndim == 3:
|
|
37
|
+
return T.tensor3()
|
|
38
|
+
elif ndim == 4:
|
|
39
|
+
return T.tensor4()
|
|
40
|
+
return T.matrix()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def on_gpu():
|
|
44
|
+
return theano.config.device[:3] == 'gpu'
|
|
Binary file
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import pydot
|
|
2
|
+
# old pydot will not work with python3, must use one
|
|
3
|
+
# that works with python3 such as pydot2 or pydot
|
|
4
|
+
from keras.models import Sequential, Graph
|
|
5
|
+
|
|
6
|
+
def to_graph(model):
|
|
7
|
+
graph = pydot.Dot(graph_type='digraph')
|
|
8
|
+
if type(model) == Sequential:
|
|
9
|
+
previous_node = None
|
|
10
|
+
written_nodes = []
|
|
11
|
+
n = 1
|
|
12
|
+
for node in model.get_config()['layers']:
|
|
13
|
+
# append number in case layers have same name to differentiate
|
|
14
|
+
if (node['name'] + str(n)) in written_nodes:
|
|
15
|
+
n += 1
|
|
16
|
+
current_node = pydot.Node(node['name'] + str(n))
|
|
17
|
+
written_nodes.append(node['name'] + str(n))
|
|
18
|
+
graph.add_node(current_node)
|
|
19
|
+
if previous_node:
|
|
20
|
+
graph.add_edge(pydot.Edge(previous_node, current_node))
|
|
21
|
+
previous_node = current_node
|
|
22
|
+
elif type(model) == Graph:
|
|
23
|
+
# don't need to append number for names since all nodes labeled
|
|
24
|
+
for input_node in model.input_config:
|
|
25
|
+
graph.add_node(pydot.Node(input_node['name']))
|
|
26
|
+
|
|
27
|
+
# intermediate and output nodes have input defined
|
|
28
|
+
for layer_config in [model.node_config, model.output_config]:
|
|
29
|
+
for node in layer_config:
|
|
30
|
+
graph.add_node(pydot.Node(node['name']))
|
|
31
|
+
# possible to have multiple 'inputs' vs 1 'input'
|
|
32
|
+
if node['inputs']:
|
|
33
|
+
for e in node['inputs']:
|
|
34
|
+
graph.add_edge(pydot.Edge(e, node['name']))
|
|
35
|
+
else:
|
|
36
|
+
graph.add_edge(pydot.Edge(node['input'], node['name']))
|
|
37
|
+
return graph
|
|
38
|
+
|
|
39
|
+
def plot(model, to_file='model.png'):
|
|
40
|
+
graph = to_graph(model)
|
|
41
|
+
graph.write_png(to_file)
|
|
Binary file
|
|
File without changes
|
|
Binary file
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
import abc
|
|
3
|
+
import copy
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from ..utils.np_utils import to_categorical
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BaseWrapper(object):
|
|
10
|
+
"""
|
|
11
|
+
Base class for the Keras scikit-learn wrapper.
|
|
12
|
+
|
|
13
|
+
Warning: This class should not be used directly. Use derived classes instead.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
train_batch_size : int, optional
|
|
18
|
+
Number of training samples evaluated at a time.
|
|
19
|
+
test_batch_size : int, optional
|
|
20
|
+
Number of test samples evaluated at a time.
|
|
21
|
+
nb_epochs : int, optional
|
|
22
|
+
Number of training epochs.
|
|
23
|
+
shuffle : boolean, optional
|
|
24
|
+
Whether to shuffle the samples at each epoch.
|
|
25
|
+
show_accuracy : boolean, optional
|
|
26
|
+
Whether to display class accuracy in the logs at each epoch.
|
|
27
|
+
validation_split : float [0, 1], optional
|
|
28
|
+
Fraction of the data to use as held-out validation data.
|
|
29
|
+
validation_data : tuple (X, y), optional
|
|
30
|
+
Data to be used as held-out validation data. Will override validation_split.
|
|
31
|
+
callbacks : list, optional
|
|
32
|
+
List of callbacks to apply during training.
|
|
33
|
+
verbose : int, optional
|
|
34
|
+
Verbosity level.
|
|
35
|
+
"""
|
|
36
|
+
__metaclass__ = abc.ABCMeta
|
|
37
|
+
|
|
38
|
+
@abc.abstractmethod
|
|
39
|
+
def __init__(self, model, optimizer, loss,
|
|
40
|
+
train_batch_size=128, test_batch_size=128,
|
|
41
|
+
nb_epoch=100, shuffle=True, show_accuracy=False,
|
|
42
|
+
validation_split=0, validation_data=None, callbacks=None,
|
|
43
|
+
verbose=0,):
|
|
44
|
+
self.model = model
|
|
45
|
+
self.optimizer = optimizer
|
|
46
|
+
self.loss = loss
|
|
47
|
+
self.compiled_model_ = None
|
|
48
|
+
self.classes_ = []
|
|
49
|
+
self.config_ = []
|
|
50
|
+
self.weights_ = []
|
|
51
|
+
|
|
52
|
+
self.train_batch_size = train_batch_size
|
|
53
|
+
self.test_batch_size = test_batch_size
|
|
54
|
+
self.nb_epoch = nb_epoch
|
|
55
|
+
self.shuffle = shuffle
|
|
56
|
+
self.show_accuracy = show_accuracy
|
|
57
|
+
self.validation_split = validation_split
|
|
58
|
+
self.validation_data = validation_data
|
|
59
|
+
self.callbacks = [] if callbacks is None else callbacks
|
|
60
|
+
|
|
61
|
+
self.verbose = verbose
|
|
62
|
+
|
|
63
|
+
def get_params(self, deep=True):
|
|
64
|
+
"""
|
|
65
|
+
Get parameters for this estimator.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
deep: boolean, optional
|
|
70
|
+
If True, will return the parameters for this estimator and
|
|
71
|
+
contained subobjects that are estimators.
|
|
72
|
+
|
|
73
|
+
Returns
|
|
74
|
+
-------
|
|
75
|
+
params : dict
|
|
76
|
+
Dictionary of parameter names mapped to their values.
|
|
77
|
+
"""
|
|
78
|
+
return {'model': self.model, 'optimizer': self.optimizer, 'loss': self.loss}
|
|
79
|
+
|
|
80
|
+
def set_params(self, **params):
|
|
81
|
+
"""
|
|
82
|
+
Set the parameters of this estimator.
|
|
83
|
+
|
|
84
|
+
Parameters
|
|
85
|
+
----------
|
|
86
|
+
params: dict
|
|
87
|
+
Dictionary of parameter names mapped to their values.
|
|
88
|
+
|
|
89
|
+
Returns
|
|
90
|
+
-------
|
|
91
|
+
self
|
|
92
|
+
"""
|
|
93
|
+
for parameter, value in params.items():
|
|
94
|
+
setattr(self, parameter, value)
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
def fit(self, X, y):
|
|
98
|
+
"""
|
|
99
|
+
Fit the model according to the given training data.
|
|
100
|
+
|
|
101
|
+
Makes a copy of the un-compiled model definition to use for
|
|
102
|
+
compilation and fitting, leaving the original definition
|
|
103
|
+
intact.
|
|
104
|
+
|
|
105
|
+
Parameters
|
|
106
|
+
----------
|
|
107
|
+
X : array-like, shape = (n_samples, n_features)
|
|
108
|
+
Training samples where n_samples in the number of samples
|
|
109
|
+
and n_features is the number of features.
|
|
110
|
+
y : array-like, shape = (n_samples) or (n_samples, n_outputs)
|
|
111
|
+
True labels for X.
|
|
112
|
+
|
|
113
|
+
Returns
|
|
114
|
+
-------
|
|
115
|
+
history : object
|
|
116
|
+
Returns details about the training history at each epoch.
|
|
117
|
+
"""
|
|
118
|
+
if len(y.shape) == 1:
|
|
119
|
+
self.classes_ = list(np.unique(y))
|
|
120
|
+
if self.loss == 'categorical_crossentropy':
|
|
121
|
+
y = to_categorical(y)
|
|
122
|
+
else:
|
|
123
|
+
self.classes_ = np.arange(0, y.shape[1])
|
|
124
|
+
|
|
125
|
+
self.compiled_model_ = copy.deepcopy(self.model)
|
|
126
|
+
self.compiled_model_.compile(optimizer=self.optimizer, loss=self.loss)
|
|
127
|
+
history = self.compiled_model_.fit(
|
|
128
|
+
X, y, batch_size=self.train_batch_size, nb_epoch=self.nb_epoch, verbose=self.verbose,
|
|
129
|
+
shuffle=self.shuffle, show_accuracy=self.show_accuracy,
|
|
130
|
+
validation_split=self.validation_split, validation_data=self.validation_data,
|
|
131
|
+
callbacks=self.callbacks)
|
|
132
|
+
|
|
133
|
+
self.config_ = self.model.get_config()
|
|
134
|
+
self.weights_ = self.model.get_weights()
|
|
135
|
+
|
|
136
|
+
return history
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class KerasClassifier(BaseWrapper):
|
|
140
|
+
"""
|
|
141
|
+
Implementation of the scikit-learn classifier API for Keras.
|
|
142
|
+
|
|
143
|
+
Parameters
|
|
144
|
+
----------
|
|
145
|
+
model : object
|
|
146
|
+
An un-compiled Keras model object is required to use the scikit-learn wrapper.
|
|
147
|
+
optimizer : string
|
|
148
|
+
Optimization method used by the model during compilation/training.
|
|
149
|
+
loss : string
|
|
150
|
+
Loss function used by the model during compilation/training.
|
|
151
|
+
"""
|
|
152
|
+
def __init__(self, model, optimizer='adam', loss='categorical_crossentropy', **kwargs):
|
|
153
|
+
super(KerasClassifier, self).__init__(model, optimizer, loss, **kwargs)
|
|
154
|
+
|
|
155
|
+
def predict(self, X):
|
|
156
|
+
"""
|
|
157
|
+
Returns the class predictions for the given test data.
|
|
158
|
+
|
|
159
|
+
Parameters
|
|
160
|
+
----------
|
|
161
|
+
X : array-like, shape = (n_samples, n_features)
|
|
162
|
+
Test samples where n_samples in the number of samples
|
|
163
|
+
and n_features is the number of features.
|
|
164
|
+
|
|
165
|
+
Returns
|
|
166
|
+
-------
|
|
167
|
+
preds : array-like, shape = (n_samples)
|
|
168
|
+
Class predictions.
|
|
169
|
+
"""
|
|
170
|
+
return self.compiled_model_.predict_classes(
|
|
171
|
+
X, batch_size=self.test_batch_size, verbose=self.verbose)
|
|
172
|
+
|
|
173
|
+
def predict_proba(self, X):
|
|
174
|
+
"""
|
|
175
|
+
Returns class probability estimates for the given test data.
|
|
176
|
+
|
|
177
|
+
Parameters
|
|
178
|
+
----------
|
|
179
|
+
X : array-like, shape = (n_samples, n_features)
|
|
180
|
+
Test samples where n_samples in the number of samples
|
|
181
|
+
and n_features is the number of features.
|
|
182
|
+
|
|
183
|
+
Returns
|
|
184
|
+
-------
|
|
185
|
+
proba : array-like, shape = (n_samples, n_outputs)
|
|
186
|
+
Class probability estimates.
|
|
187
|
+
"""
|
|
188
|
+
return self.compiled_model_.predict_proba(
|
|
189
|
+
X, batch_size=self.test_batch_size, verbose=self.verbose)
|
|
190
|
+
|
|
191
|
+
def score(self, X, y):
|
|
192
|
+
"""
|
|
193
|
+
Returns the mean accuracy on the given test data and labels.
|
|
194
|
+
|
|
195
|
+
Parameters
|
|
196
|
+
----------
|
|
197
|
+
X : array-like, shape = (n_samples, n_features)
|
|
198
|
+
Test samples where n_samples in the number of samples
|
|
199
|
+
and n_features is the number of features.
|
|
200
|
+
y : array-like, shape = (n_samples) or (n_samples, n_outputs)
|
|
201
|
+
True labels for X.
|
|
202
|
+
|
|
203
|
+
Returns
|
|
204
|
+
-------
|
|
205
|
+
score : float
|
|
206
|
+
Mean accuracy of predictions on X wrt. y.
|
|
207
|
+
"""
|
|
208
|
+
loss, accuracy = self.compiled_model_.evaluate(
|
|
209
|
+
X, y, batch_size=self.test_batch_size, show_accuracy=True, verbose=self.verbose)
|
|
210
|
+
return accuracy
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class KerasRegressor(BaseWrapper):
|
|
214
|
+
"""
|
|
215
|
+
Implementation of the scikit-learn regressor API for Keras.
|
|
216
|
+
|
|
217
|
+
Parameters
|
|
218
|
+
----------
|
|
219
|
+
model : object
|
|
220
|
+
An un-compiled Keras model object is required to use the scikit-learn wrapper.
|
|
221
|
+
optimizer : string
|
|
222
|
+
Optimization method used by the model during compilation/training.
|
|
223
|
+
loss : string
|
|
224
|
+
Loss function used by the model during compilation/training.
|
|
225
|
+
"""
|
|
226
|
+
def __init__(self, model, optimizer='adam', loss='mean_squared_error', **kwargs):
|
|
227
|
+
super(KerasRegressor, self).__init__(model, optimizer, loss, **kwargs)
|
|
228
|
+
|
|
229
|
+
def predict(self, X):
|
|
230
|
+
"""
|
|
231
|
+
Returns predictions for the given test data.
|
|
232
|
+
|
|
233
|
+
Parameters
|
|
234
|
+
----------
|
|
235
|
+
X : array-like, shape = (n_samples, n_features)
|
|
236
|
+
Test samples where n_samples in the number of samples
|
|
237
|
+
and n_features is the number of features.
|
|
238
|
+
|
|
239
|
+
Returns
|
|
240
|
+
-------
|
|
241
|
+
preds : array-like, shape = (n_samples)
|
|
242
|
+
Predictions.
|
|
243
|
+
"""
|
|
244
|
+
return self.compiled_model_.predict(
|
|
245
|
+
X, batch_size=self.test_batch_size, verbose=self.verbose).ravel()
|
|
246
|
+
|
|
247
|
+
def score(self, X, y):
|
|
248
|
+
"""
|
|
249
|
+
Returns the mean accuracy on the given test data and labels.
|
|
250
|
+
|
|
251
|
+
Parameters
|
|
252
|
+
----------
|
|
253
|
+
X : array-like, shape = (n_samples, n_features)
|
|
254
|
+
Test samples where n_samples in the number of samples
|
|
255
|
+
and n_features is the number of features.
|
|
256
|
+
y : array-like, shape = (n_samples)
|
|
257
|
+
True labels for X.
|
|
258
|
+
|
|
259
|
+
Returns
|
|
260
|
+
-------
|
|
261
|
+
score : float
|
|
262
|
+
Loss from predictions on X wrt. y.
|
|
263
|
+
"""
|
|
264
|
+
loss = self.compiled_model_.evaluate(
|
|
265
|
+
X, y, batch_size=self.test_batch_size, show_accuracy=False, verbose=self.verbose)
|
|
266
|
+
return loss
|
|
Binary file
|
tests/__init__.py
ADDED
|
File without changes
|
tests/__init__.pyc
ADDED
|
Binary file
|
tests/manual/__init__.py
ADDED
|
File without changes
|
|
Binary file
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
from __future__ import print_function
|
|
3
|
+
from keras.datasets import mnist
|
|
4
|
+
from keras.models import Sequential, model_from_config
|
|
5
|
+
from keras.layers.core import AutoEncoder, Dense, Activation, TimeDistributedDense, Flatten
|
|
6
|
+
from keras.layers.recurrent import LSTM
|
|
7
|
+
from keras.layers.embeddings import Embedding
|
|
8
|
+
from keras.layers.core import Layer
|
|
9
|
+
from keras.layers import containers
|
|
10
|
+
from keras.utils import np_utils
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
nb_classes = 10
|
|
14
|
+
batch_size = 128
|
|
15
|
+
nb_epoch = 5
|
|
16
|
+
activation = 'linear'
|
|
17
|
+
|
|
18
|
+
input_dim = 784
|
|
19
|
+
hidden_dim = 392
|
|
20
|
+
|
|
21
|
+
max_train_samples = 5000
|
|
22
|
+
max_test_samples = 1000
|
|
23
|
+
|
|
24
|
+
# the data, shuffled and split between tran and test sets
|
|
25
|
+
(X_train, y_train), (X_test, y_test) = mnist.load_data()
|
|
26
|
+
|
|
27
|
+
X_train = X_train.reshape(60000, input_dim)[:max_train_samples]
|
|
28
|
+
X_test = X_test.reshape(10000, input_dim)[: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
|
+
# convert class vectors to binary class matrices
|
|
35
|
+
Y_train = np_utils.to_categorical(y_train, nb_classes)[:max_train_samples]
|
|
36
|
+
Y_test = np_utils.to_categorical(y_test, nb_classes)[:max_test_samples]
|
|
37
|
+
|
|
38
|
+
print("X_train: ", X_train.shape)
|
|
39
|
+
print("X_test: ", X_test.shape)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
##########################
|
|
43
|
+
# dense model test #
|
|
44
|
+
##########################
|
|
45
|
+
|
|
46
|
+
print("Training classical fully connected layer for classification")
|
|
47
|
+
model_classical = Sequential()
|
|
48
|
+
model_classical.add(Dense(input_dim, 10, activation=activation))
|
|
49
|
+
model_classical.add(Activation('softmax'))
|
|
50
|
+
model_classical.get_config(verbose=1)
|
|
51
|
+
model_classical.compile(loss='categorical_crossentropy', optimizer='adam')
|
|
52
|
+
model_classical.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=(X_test, Y_test))
|
|
53
|
+
classical_score = model_classical.evaluate(X_test, Y_test, verbose=0, show_accuracy=True)
|
|
54
|
+
print('\nclassical_score:', classical_score)
|
|
55
|
+
|
|
56
|
+
##########################
|
|
57
|
+
# autoencoder model test #
|
|
58
|
+
##########################
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def build_lstm_autoencoder(autoencoder, X_train, X_test):
|
|
62
|
+
X_train = X_train[:, np.newaxis, :]
|
|
63
|
+
X_test = X_test[:, np.newaxis, :]
|
|
64
|
+
print("Modified X_train: ", X_train.shape)
|
|
65
|
+
print("Modified X_test: ", X_test.shape)
|
|
66
|
+
|
|
67
|
+
# The TimeDistributedDense isn't really necessary, however you need a lot of GPU memory to do 784x394-394x784
|
|
68
|
+
autoencoder.add(TimeDistributedDense(input_dim, 16))
|
|
69
|
+
autoencoder.add(AutoEncoder(encoder=LSTM(16, 8, activation=activation, return_sequences=True),
|
|
70
|
+
decoder=LSTM(8, input_dim, activation=activation, return_sequences=True),
|
|
71
|
+
output_reconstruction=False))
|
|
72
|
+
return autoencoder, X_train, X_test
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def build_deep_classical_autoencoder(autoencoder):
|
|
76
|
+
encoder = containers.Sequential([Dense(input_dim, hidden_dim, activation=activation), Dense(hidden_dim, hidden_dim/2, activation=activation)])
|
|
77
|
+
decoder = containers.Sequential([Dense(hidden_dim/2, hidden_dim, activation=activation), Dense(hidden_dim, input_dim, activation=activation)])
|
|
78
|
+
autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=False))
|
|
79
|
+
return autoencoder
|
|
80
|
+
|
|
81
|
+
# Try different things here: 'lstm' or 'classical' or 'denoising'
|
|
82
|
+
# or 'deep_denoising'
|
|
83
|
+
|
|
84
|
+
for autoencoder_type in ['classical', 'lstm']:
|
|
85
|
+
print(autoencoder_type)
|
|
86
|
+
print('-'*40)
|
|
87
|
+
# Build our autoencoder model
|
|
88
|
+
autoencoder = Sequential()
|
|
89
|
+
if autoencoder_type == 'lstm':
|
|
90
|
+
print("Training LSTM AutoEncoder")
|
|
91
|
+
autoencoder, X_train, X_test = build_lstm_autoencoder(autoencoder, X_train, X_test)
|
|
92
|
+
elif autoencoder_type == 'classical':
|
|
93
|
+
print("Training Classical AutoEncoder")
|
|
94
|
+
autoencoder = build_deep_classical_autoencoder(autoencoder)
|
|
95
|
+
else:
|
|
96
|
+
print("Error: unknown autoencoder type!")
|
|
97
|
+
exit(-1)
|
|
98
|
+
|
|
99
|
+
autoencoder.compile(loss='mean_squared_error', optimizer='adam')
|
|
100
|
+
# Do NOT use validation data with return output_reconstruction=True
|
|
101
|
+
autoencoder.fit(X_train, X_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=1)
|
|
102
|
+
|
|
103
|
+
# Do an inference pass
|
|
104
|
+
prefilter_train = autoencoder.predict(X_train, verbose=0)
|
|
105
|
+
prefilter_test = autoencoder.predict(X_test, verbose=0)
|
|
106
|
+
print("prefilter_train: ", prefilter_train.shape)
|
|
107
|
+
print("prefilter_test: ", prefilter_test.shape)
|
|
108
|
+
|
|
109
|
+
# Classify results from Autoencoder
|
|
110
|
+
print("Building classical fully connected layer for classification")
|
|
111
|
+
model = Sequential()
|
|
112
|
+
if autoencoder_type == 'lstm':
|
|
113
|
+
model.add(TimeDistributedDense(8, nb_classes, activation=activation))
|
|
114
|
+
model.add(Flatten())
|
|
115
|
+
elif autoencoder_type == 'classical':
|
|
116
|
+
model.add(Dense(prefilter_train.shape[1], nb_classes, activation=activation))
|
|
117
|
+
else:
|
|
118
|
+
model.add(Dense(prefilter_train.shape[1], nb_classes, activation=activation))
|
|
119
|
+
|
|
120
|
+
model.add(Activation('softmax'))
|
|
121
|
+
|
|
122
|
+
model.get_config(verbose=1)
|
|
123
|
+
model.compile(loss='categorical_crossentropy', optimizer='adam')
|
|
124
|
+
model.fit(prefilter_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=False, verbose=0, validation_data=(prefilter_test, Y_test))
|
|
125
|
+
|
|
126
|
+
score = model.evaluate(prefilter_test, Y_test, verbose=0, show_accuracy=True)
|
|
127
|
+
print('\nscore:', score)
|
|
128
|
+
|
|
129
|
+
print('Loss change:', (score[0] - classical_score[0])/classical_score[0], '%')
|
|
130
|
+
print('Accuracy change:', (score[1] - classical_score[1])/classical_score[1], '%')
|
|
131
|
+
|
|
132
|
+
# check serialization
|
|
133
|
+
config = autoencoder.get_config(verbose=1)
|
|
134
|
+
autoencoder = model_from_config(config)
|
|
Binary file
|