Search code examples
tensorflowkerasautoencoder

How to get output from a specific layer in keras.tf, the bottleneck layer in autoencoder?


I am developing an autoencoder for clustering certain groups of images.

input_images->...->bottleneck->...->output_images

I have calibrated the autoencoder to my satisfaction and saved the model; everything has been developed using keras.tensorflow on python3.

The next step is to apply the autoencoder to a ton of images and cluster them according to cosine distance in the bottleneck layer. Oops, I just realized that I don't know the syntax in keras.tf for running the model on a batch up to a specific layer rather than to the output layer. Thus the question:

How do I run something like Model.predict_on_batch or Model.predict_generator up to the certain "bottleneck" layer and retrieve the values on that layer rather than the values on the output layer?


Solution

  • You need to define a new model (if you didn't define the encoder and decoder as separate models initially, which is usually the easiest option).

    If your model was defined without reusing layers, it's just:

    inputs = model.input   
    outputs= model.get_layer('bottleneck').output
    
    encoder = Model(inputs, outputs)
    

    Use the encoder model as any other model.