我试图在使用 Keras 的功能 API 时获取中间层输出。使用标准 Sequential API 时,我能够获得输出,但不能使用功能 API。
我正在研究这个工作玩具示例:
from keras.models import Sequential
from keras.layers import Input, Dense,TimeDistributed
from keras.models import Model
from keras.layers import Dense, LSTM, Bidirectional,Masking
inputs = [[[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[1,2,3],[4,5,6],[7,8,9],[10,11,12]],[[10,20,30],[40,50,60],[70,80,90],[100,110,120]]]
model = Sequential()
model.add(Masking(mask_value=0., input_shape = (4,3)))
model.add(Bidirectional(LSTM(3,return_sequences = True),merge_mode='concat'))
model.add(TimeDistributed(Dense(3,activation = 'softmax')))
print "First layer:"
intermediate_layer_model = Model(input=model.input,output=model.layers[0].output)
print intermediate_layer_model.predict(inputs)
print ""
print "Second layer:"
intermediate_layer_model = Model(input=model.input,output=model.layers[1].output)
print intermediate_layer_model.predict(inputs)
print ""
print "Third layer:"
intermediate_layer_model = Model(input=model.input,output=model.layers[2].output)
print intermediate_layer_model.predict(inputs)
但是如果我使用功能 API,它就不起作用。输出不正确。例如,它在第二层输出初始输入:
inputs_ = Input(shape=(4,3))
x = Masking(mask_value=0., input_shape = (4,3))(inputs_)
x = Bidirectional(LSTM(3,return_sequences = True),merge_mode='concat')(x)
predictions = TimeDistributed(Dense(3,activation = 'softmax'))(x)
model2 = Model(input=inputs_, output=predictions)
print "First layer:"
intermediate_layer_model = Model(input=model2.input,output=model2.layers[0].output)
print intermediate_layer_model.predict(inputs)
print ""
print "Second layer:"
intermediate_layer_model = Model(input=model2.input,output=model2.layers[1].output)
print intermediate_layer_model.predict(inputs)
print ""
print "Third layer:"
intermediate_layer_model = Model(input=model2.input,output=model2.layers[2].output)
print intermediate_layer_model.predict(inputs)
回答: 显然,当使用功能 API 时,第 0 层是输入本身。所以一切都向前移动了一个位置。