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,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'
@@ -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
+
5
+
6
+ def plot(model, to_file='model.png'):
7
+
8
+ graph = pydot.Dot(graph_type='digraph')
9
+ if type(model) == Sequential:
10
+ previous_node = None
11
+ written_nodes = []
12
+ n = 1
13
+ for node in model.get_config()['layers']:
14
+ # append number in case layers have same name to differentiate
15
+ if (node['name'] + str(n)) in written_nodes:
16
+ n += 1
17
+ current_node = pydot.Node(node['name'] + str(n))
18
+ written_nodes.append(node['name'] + str(n))
19
+ graph.add_node(current_node)
20
+ if previous_node:
21
+ graph.add_edge(pydot.Edge(previous_node, current_node))
22
+ previous_node = current_node
23
+ graph.write_png(to_file)
24
+
25
+ elif type(model) == Graph:
26
+ # don't need to append number for names since all nodes labeled
27
+ for input_node in model.input_config:
28
+ graph.add_node(pydot.Node(input_node['name']))
29
+
30
+ # intermediate and output nodes have input defined
31
+ for layer_config in [model.node_config, model.output_config]:
32
+ for node in layer_config:
33
+ graph.add_node(pydot.Node(node['name']))
34
+ # possible to have multiple 'inputs' vs 1 'input'
35
+ if node['inputs']:
36
+ for e in node['inputs']:
37
+ graph.add_edge(pydot.Edge(e, node['name']))
38
+ else:
39
+ graph.add_edge(pydot.Edge(node['input'], node['name']))
40
+
41
+ graph.write_png(to_file)
File without changes
@@ -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
tests/__init__.py ADDED
File without changes
File without changes
@@ -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)