Sequential
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]
注意,如果你的模型在训练和测试两种模式下不完全一致,例如你的模型中含有Dropout层,批规范化(BatchNormalization)层等组件,你需要在函数中传递一个learning_phase的标记,像这样:
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]
Functional
每个model都是一个可调用对象