从LSTM Keras的每个纪元的最后一层获取输出

时间:2018-10-13 09:52:38

标签: python machine-learning keras deep-learning lstm

我们已经知道可以从以下代码获得每一层的输出:

def get_layer(model,x):
    from keras import backend as K

    get_3rd_layer_output = K.function([model.layers[0].input],
                                      [model.layers[2].output])
    layer_output = get_3rd_layer_output([x])[0]
    print(layer_output.shape)
    return layer_output

LSTM模型适用于:

history = model.fit(X_train, y_train, batch_size=batch_size,verbose=1, nb_epoch=10,validation_data=(X_test,y_test))

但是如何从10个历元中的每个历元获取模型中最后一层的输出?

1 个答案:

答案 0 :(得分:2)

您可以创建自定义回调(see Documentation),然后通过from keras.callbacks import Callback class LogThirdLayerOutput(Callback): def on_epoch_end(self, epoch, logs=None): layer_output = get_3rd_layer_output(self.validation_data)[0] print(layer_output.shape) 方法将其传递给回调列表。

示例:

history = model.fit(X_train, y_train, batch_size=batch_size, verbose=1, nb_epoch=10, validation_data=(X_test,y_test), callbacks=[LogThirdLayerOutput()])

在拟合模型时:

NgOnChanges

如果您不想在单独的类中创建回调,则还应该能够使用Lambda callbacks