Keras-保存中间层的输出

时间:2018-10-25 08:12:19

标签: python neural-network keras

我做了什么?

我正在使用此代码来实现我的keras模型:

X, tx, Y, ty = train_test_split(X, Y, test_size=0.2, random_state=np.random.seed(7), shuffle=True)

X = np.reshape(X, (X.shape[0], 1, X.shape[1]))
tx = np.reshape(tx, (tx.shape[0], 1, tx.shape[1]))

model = Sequential()
model.add(LSTM(100, return_sequences=False, input_shape=(X.shape[1], X.shape[2])))
model.add(Dense(Y.shape[1], activation='softmax'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
filepath="weights-{epoch:02d}-{val_acc:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

model.fit(X, Y, validation_split=.20,
                    epochs=1000, batch_size=50, callbacks=callbacks_list, verbose=0) 

输出:

以下是程序输出的一部分:

Epoch 00993: val_acc did not improve
Epoch 00994: val_acc did not improve
Epoch 00995: val_acc did not improve
Epoch 00996: val_acc did not improve
Epoch 00997: val_acc did not improve
Epoch 00998: val_acc improved from 0.93900 to 0.94543, saving model to weights-998-0.94.hdf5
Epoch 00999: val_acc did not improve

问题:

我需要在任何时期保存LSTM层的输出,但是我不知道如何?

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Keras functional API。您将不得不重写您的模型创建,但是工作量不大。然后,当您编写这样的内容时:

lstm_output = LSTM(128, ...)(x)

LSTM层的输出将在lstm_output变量中,您可以将其保存在每个时期的每次迭代中。

我希望这能回答您的问题。