How keras obtains the output of the intermediate layer (in Sequential and Functional cases)

How keras obtains the output of the intermediate layer

There are detailed links in the Chinese and English documents of Keras, refer to: How to get the output of the middle layer?

Example

Build model

from keras.models import Model
from keras.layers import Input,Dense,Permute,Flatten

inputs_v = Input(shape=(2,5))
model_v  = Permute((2, 1))(inputs_v)
flatten = Flatten()(model_v)
output = Dense(1)(flatten)

model = Model(inputs_v, output)
model.summary()
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x, y, epochs=1, batch_size=2, validation_split=0.1)

Insert picture description here

Take out the middle layer output

After training the model, take out the output of the middle layer.

method one:

permute_layer_model = Model(input=model.input,output=model.get_layer('flatten_6').output)
permute_layer_output = permute_layer_model.predict(x)
print(permute_layer_output)

Method Two:

from keras import backend as K

# with a Sequential model
get_2rd_layer_output = K.function([model.layers[0].input], [model.layers[2].output])
permute_layer_output = get_2rd_layer_output([x])[0]
print(permute_layer_output)

Note that if your model is not completely consistent in the training and testing modes, for example, your model contains components such as the Dropout layer and the Batch Normalization layer, you need to pass a learning_phase mark in the function, like this:

from keras import backend as K

# with a Sequential model
get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()], [model.layers[3].output])

# output in test mode = 0
layer_output = get_3rd_layer_output([X, 0])[0]

# output in train mode = 1
layer_output = get_3rd_layer_output([X, 1])[0]

 reference:

https://blog.csdn.net/xqz_437278616/article/details/97001648

https://www.jianshu.com/p/9f3a2c9cc786

Guess you like

Origin blog.csdn.net/ch206265/article/details/107608423