Code to run a simple encoder

This portion of this recipe will go over the steps needed to build the encoder script:

  1. Gather all of the necessary imports to create an autoencoder—notice how few packages we need to make this happen:
from keras.datasets import mnist
import numpy as np
from keras.layers import Input, Dense
from keras.models import Model
  1. Download the mnist data through the Keras API and convert the values to be between 0 and 1:
# Download the data and format for learning
(x_train, y_train), (x_test, y_test) = mnist.load_data()
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:])))
  1. In this step, create the encoding dimension—how many numbers we need to represent the MNIST dataset:
# How much encoding do we want for our setup?
encoding_dimension = 256

Choose a larger number in this instance to mimic a latent space sample, as  we would in a traditional GAN architecture.

  1. The Keras MNIST data has an input shape of 784, so we use that in the input later. We're also creating an encoded and decoded set of layers—notice that this model is very simple:
input_layer = Input(shape=(784,))
encoded_layer = Dense(encoding_dimension, activation='relu')(input_layer)
decoded = Dense(784, activation='sigmoid')(encoded_layer)
  1. Build the autoencoder model by using input_layer as the input layer and decoded as the output layer:
# Build the Model
ac = Model(input_layer, decoded)

  1. Create an encoder model that we'll save for later:
# Create an encoder model that we'll save later
encoder = Model(input_layer, encoded_layer)
  1. Train the autoencoder for 100 epochs and use the test data to validate:
# Train the autoencoder model, ac
ac.compile(optimizer='adadelta', loss='binary_crossentropy')
ac.fit(x_train, x_train,
epochs=100,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
  1. Now that we have a trained autoencoder model, we can use the encoder model to predict encodings for the entire x_train dataset—save it to use in our training recipe:
# Save the Predicted Data x_train
x_train_encoded = encoder.predict(x_train)
np.save('/src/x_train_encoded.npy',x_train_encoded)
  1. Do the same action for the test set—save the encoded x_test dataset into an npy file:
# Save the Predicted Data x_test
x_test_encoded = encoder.predict(x_test)
np.save('/src/x_test_encoded.npy',x_test_encoded)
  1. In case we need the encoder again, save an h5 model file with the model data:
# Save the Encoder model
encoder.save('/src/encoder_model.h5')

The next steps will show you how to run this script to produce the model and npy files.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.144.56