0

I am a beginner in python and Keras. I am using Keras with tensorflow backend. I want to get value in array from each layer (hidden and output layer) in Keras. How can i do it?

This is my sequential model

def baseline_model():
# create model
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation=tempsigmoid))
# Compile model
model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
return model

# build the model
model = baseline_model()

I had tried using this code

hidden_layer = model.layers[4].output
print(hidden_layer)

but the result in tensor

Tensor("dense_1/Relu:0", shape=(?, 128), dtype=float32)

2 Answers 2

2

To extract the i-th layer of a Neural Network you can use Keras functions. Let's assume that you are training a Model on some data df:

from tensorflow.keras import backend as K

# create a Keras function to get i-th layer
get_layer_output = K.function(inputs = Model.layers[0].input, outputs = Model.layers[i].output)

# extract output
layer_output = get_layer_output(df)

You can find a practical application here. Hope this helps, otherwise let me know.

Sign up to request clarification or add additional context in comments.

7 Comments

thankyou for the response. I tried and got error message AttributeError: 'Conv2D' object has no attribute 'inputs' . Could it be because my model is convolutional ?
Reading your error message... did you write inputs instead of input?
This is the right way, should be marked as final solution.
@astri if it worked, please consider accepting the answer as solved
@Leevo thank you , i have revised my code but it still get error TypeError: inputs` to a TensorFlow backend function should be a list or tuple.` I am figuring it now
|
0

You can do the same thing but save the data with that way :

hidden_layer = model.layers[4].output
hidden_layer = hidden_layer.eval(session=tf.Session())
print(hidden_layer)

That will save directly the Tensor data in the hidden_layer variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.