Building an autoencoder using Keras.
In [1]:
!apt-get install graphviz -qq
!pip install graphviz -q
!pip install pydot -q
# restart runtime
In [2]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from keras.layers import Input, Dense
from keras.models import Model
from keras.datasets import mnist
In [3]:
# copy-paste from ml-stuff/kaggle/utils_keras.py
# delete before saving for brevity
# ...
In [4]:
# this is the size of our encoded representations
encoding_dim = 32 # 32 floats -> compression of factor 24.5, assuming the input is 784 floats
# this is our input placeholder
input_img = Input(shape=(784,))
# encoded representation of the input
encoded = Dense(encoding_dim, activation='relu')(input_img)
# lossy reconstruction of the input
decoded = Dense(784, activation='sigmoid')(encoded)
# maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
# maps an input to its encoded representation
encoder = Model(input_img, encoded)
# placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(encoding_dim,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
In [5]:
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
In [6]:
(x_train, _), (x_test, _) = mnist.load_data()
In [7]:
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
print(x_train.shape)
print(x_test.shape)
In [8]:
autoencoder.fit(x_train, x_train,
epochs=20,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
Out[8]:
In [9]:
# encode and decode some digits
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
In [10]:
plt.figure(figsize=(20, 4))
n = 10 # no of digits to display
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.savefig('plot_predict_vs_reconstructed.png')
plt.show()
In [11]:
models = {
'autoencoder': autoencoder,
'encoder': encoder,
'decoder': decoder
}
model_save_mult(models)
In [12]:
spool = model_summary_spool_mult(models)
print(spool)
In [13]:
model_plot_save_mult(models)
model_display('autoencoder')
In [14]:
!ls -l
In [15]:
!zip -r data.zip ./ -x "datalab/*" "\.*"
In [16]:
from google.colab import files
files.download('data.zip')
In [ ]: