Last active
September 24, 2019 17:00
-
-
Save parmarsuraj99/28c9a7dbb8577c36ee6ba4e3ae9dceb8 to your computer and use it in GitHub Desktop.
A simple Deep Autoencoder using keras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
from tensorflow import keras | |
from matplotlib import pyplot as plt | |
from keras.datasets import mnist | |
from keras.layers import Input, Dense | |
from keras.models import Model | |
(x_train, y_train), (x_test, y_test) = mnist.load_data() | |
x_train = x_train.astype('float32')/255.0 | |
x_test = x_test.astype('float32')/255.0 | |
x_train = x_train.reshape(len(x_train), (x_train.shape[1]*x_train.shape[2])) | |
x_test = x_test.reshape(len(x_test), (x_test.shape[1]*x_test.shape[2])) | |
encoding_dim = 32 | |
input_img = Input(shape = (784, )) | |
encoded = Dense(encodin_dim, activation='relu')(input_img) | |
decoded = Dense(784, activation='sigmoid')(encoded) | |
autoencoder = Model(input_img, decoded) | |
encoder = Model(input_img, encoded) | |
enncoded_input = Input(shape=(encoding_dim, )) | |
decode_layer = autoencoder.layers[-1] | |
decoder = Model(encoded_input, decode_layer(encoded_input)) | |
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy', metrics=['accuracy']) | |
autoencoder.fit(x_train, x_train, epochs=20, validation_data=(x_test, x_test)) | |
encoded_images = encoder.predict(x_test) | |
encoded_images.shape | |
predicted = decoder.predict(encoded_images) | |
plt.imshow(predicted[0].reshape(28, 28)) | |
def plot_imgs(index=0): | |
f = plt.figure() | |
f.add_subplot(1,3, 1) | |
plt.imshow(x_test[index].reshape(28, 28)) | |
f.add_subplot(1,3, 2) | |
plt.imshow(encoded_images[index].reshape(-1, 1)) | |
f.add_subplot(1,3, 3) | |
plt.imshow(predicted[index].reshape(28, 28)) | |
plt.show(block=True) | |
plot_imgs(2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment