Search code examples
pythontensorflowkerasautoencoder

Tensorflow - Get hidden layer output of an autoencoder


I have a stacked autoencoder that is structured like 500-250-100-50-100-250-500. I now want to take out the 50-dimensional hidden layer and use it to classify my input data in 2 classes using a softmax layer.

That means I need my autoencoder to compress my 500-dimensional input vectors from my training dataset into 50-dimensional vectors and use it to train the softmax layer. In addition to that I also need the 50-dimensional hidden layer.

How I would get the hidden layer: autoencoder.layers[3]

But how do I get the compressed 50-dimensional vectors of the 500-dimensional input vectors? I would need to get the output of that hidden layer when using autoencoder.predict(x_train).


Solution

  • If you want to have another output from a hidden layer, you can get the output and add it to a new model like this:

    new_model = tf.keras.Model(inputs=autoencoder.input, outputs=[autoencoder.layers[3].output, autoencoder.output])
    

    Then you can get the predictions like this:

    hidden_layer_pred, last_layer_pred = new_model.predict(x_train)