如何获取中间层的输出?
一种简单的方法是创建一个新的Model,使得它的输出是你想要的那个输出
from keras.models import Model
model = … # create the original model
layer_name = ‘my_layer’
intermediate_layer_model = Model(input=model.input,
output=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data
此外,我们也可以建立一个Keras的函数来达到这一目的:
from keras import backend as K
with a Sequential model
get_3rd_layer_output = K.function([model.layers[0].input],
[model.layers[3].output])
layer_output = get_3rd_layer_output([X])[0]
当然,我们也可以直接编写Theano和TensorFlow的函数来完成这件事
注意,如果你的模型在训练和测试两种模式下不完全一致,例如你的模型中含有Dropout层,批规范化(BatchNormalization)层等组件,你需要在函数中传递一个learning_phase的标记,像这样:
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]