astri
astri

Reputation: 17

How get output value in array from each layer Keras

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)

Upvotes: 0

Views: 3371

Answers (2)

Thibault Bacqueyrisses
Thibault Bacqueyrisses

Reputation: 2331

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.

Upvotes: 0

Leevo
Leevo

Reputation: 1753

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.

Upvotes: 2

Related Questions