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]
注意匿级,如果你的模型在訓(xùn)練和測試兩種模式下不完全一致茫死,例如你的模型中含有Dropout層屯烦,批規(guī)范化(BatchNormalization)層等組件舔株,你需要在函數(shù)中傳遞一個(gè)learning_phase的標(biāo)記洁灵,像這樣:
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
每個(gè)model都是一個(gè)可調(diào)用對象