简体   繁体   English

Keras-保存中间层的输出

[英]Keras - Save output of intermediate layer

What I have done? 我做了什么?

I'm using from this code to implement my keras'model: 我正在使用以下代码来实现我的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) 

OUTPUT: OUTPUT:

Below is a part of the program's output: 以下是程序输出的一部分:

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

PROBLEM: 问题:

I need to save the output of LSTM layer in any epoch but i do not know how? 我需要在任何时期保存LSTM层的输出,但我不知道如何?

Any idea? 任何想法?

You can use Keras functional API . 您可以使用Keras功能性API You will have to rewrite your model creation but it's not much work. 您将不得不重写您的模型创建,但是工作量不大。 Then when you write something like this: 然后,当您编写这样的内容时:

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

the output of the LSTM layer will be in the lstm_output variable and you can save it in every iteration of every epoch. LSTM层的输出将在lstm_output变量中,您可以将其保存在每个时期的每次迭代中。

I hope this answers your question. 我希望这回答了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM