Search code examples
pythonkeras-layer

Getting the tensor values of a layer after calling model.predict once


How would i get the tensor of the output activations of one of the layers in a neural network after running the following code.

  x= model.predict(frame)

Solution

  • Here's a short example of how you could do it using Keras' functional API:

    inputs = Input(shape=(10,))
    x = Dense(5)(inputs)
    latent_outputs = Dense(2)(x)
    x = Dense(5)(latent_outputs)
    outputs = Dense(10)(x)
    
    encoder = Model(inputs, latent_outputs)
    autoencoder = Model(inputs, outputs)
    
    autoencoder.compile(optimizer='adam', loss='mse')
    autoencoder.fit(np.zeros((10, 10)), np.zeros((10, 10)))
    
    latent_output = encoder.predict(np.zeros((1, 10)))
    print(latent_output)