How to get output of hidden layer given an input, weights and biases of the hidden layer in keras?
deep-learning, keras, neural-network, python, tensorflow
Solution
The easiest way is to use the keras backend. With the keras backend you can define a function that gives you the intermediate output of a keras model as defined here (https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer).
So in essence:
get_1st_layer_output = K.function([model.layers[0].input],
[model.layers[1].output])
layer_output = get_1st_layer_output([X])
Problem
Suppose I have trained the model below for an epoch: ``` model = Sequential([ Dense(32, input_dim=784), # first number is output_dim Activation('relu'), Dense(10), # output_dim, input_dim is taken for granted from above Activation('softmax'), ]) ``` And I got the weights `dense1_w`, biases `dense1_b` of first hidden layer (named it `dense1`) and a single data sample `sample`. How do I use these to get the output of `dense1` on the `sample` in `keras`? Thanks!