Instantly share code, notes, and snippets.

Embed
What would you like to do?
from __future__ import division
import json
import numpy as np
import keras
from keras.datasets import mnist
from keras import backend as K, layers as L
from keras.models import load_model, Model, model_from_config
def load_mnist():
(x_train, _), (x_test, _) = mnist.load_data()
return [
np.reshape(x.astype(np.float32) / 255, (len(x), 28, 28, 1))
for x in [x_train, x_test]
]
def load_autoencoder(filename='autoencoder.h5', code_layer=6):
# assumes a basic structure for the layers
# also probably assumes tensorflow backend
autoencoder = load_model(filename)
encoder = Model(inputs=autoencoder.input, outputs=autoencoder.layers[code_layer].output)
spec = autoencoder._updated_config()
spec['config']['layers'] = spec['config']['layers'][code_layer+1:]
spec['config']['layers'].insert(
0,
{'class_name': 'InputLayer',
'config': {
'batch_input_shape': [s.value for s in encoder.output.shape],
'dtype': 'float32',
'name': 'input_1',
'sparse': False,
},
'inbound_nodes': [],
'name': 'input_1'})
first = spec['config']['layers'][1]
assert len(first['inbound_nodes']) == 1
assert len(first['inbound_nodes'][0]) == 1
assert len(first['inbound_nodes'][0][0]) == 4
first['inbound_nodes'][0][0][0] = 'input_1'
decoder = model_from_config(spec)
weights = []
for layer in autoencoder.layers[code_layer + 1:]:
weights += layer.weights
decoder.set_weights(K.batch_get_value(weights))
return autoencoder, encoder, decoder
def _show_mnist(img, ax=None):
if ax is None:
import matplotlib.pyplot as plt
ax = plt.gca()
ax.imshow(img.reshape(28, 28), cmap='gray')
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
def plot_groups(*arrays):
import matplotlib.pyplot as plt
n_rows = len(arrays)
n_cols = len(arrays[0])
for a in arrays[1:]:
assert len(a) == n_cols
plt.figure(figsize=(2 * n_cols, 2 * n_rows))
for i in range(n_cols):
for j in range(n_rows):
ax = plt.subplot(n_rows, n_cols, j * n_cols + i + 1)
_show_mnist(arrays[j][i], ax)
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment