【问题标题】:Keras, get output of a layer at each epochsKeras,在每个时期获取一层的输出
【发布时间】:2019-03-28 10:21:11
【问题描述】:

我做了什么?

我实现了一个keras 模型如下:

train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.2, random_state=np.random.seed(7), shuffle=True)

train_X = np.reshape(train_X, (train_X.shape[0], 1, train_X.shape[1]))
test_X = np.reshape(test_X, (test_X.shape[0], 1, test_X.shape[1]))

model = Sequential()
model.add(LSTM(100, return_sequences=False, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(train_Y.shape[1], activation='softmax'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])

model.fit(train_X, train_Y, validation_split=.20,
                        epochs=1000, batch_size=50)

我想要什么?

我想给support vector machine(SVM)倒数第二层(LSTM)的输出,在任意epoch(即1000)到svm也被训练。

但我不知道该怎么做?

有什么想法吗?

更新:

我使用 ModelCheckpoint 如下:

model = Sequential()
model.add(LSTM(100, return_sequences=False, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(train_Y.shape[1], activation='softmax'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])

# checkpoint
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(train_X, train_Y, validation_split=.20,
                    epochs=1000, batch_size=50, callbacks=callbacks_list, verbose=0)

输出:

Epoch 00991: val_acc did not improve
Epoch 00992: val_acc improved from 0.93465 to 0.93900, saving model to weights-992-0.94.hdf5
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

问题:

如@IonicSolutions所说,如何加载所有这些模型以获得LSTM层在每个时期的输出?

【问题讨论】:

    标签: python keras


    【解决方案1】:

    最适合您的情况取决于您设置和训练 SVM 的方式,但至少有两个使用回调的选项:

    您可以使用ModelCheckpoint callback 保存您在每个时期训练的模型的副本,然后加载所有这些模型以获得 LSTM 层的输出。

    您还可以通过实现Callback base class 创建自己的回调。在回调中,可以访问模型,您可以使用on_epoch_end 在每个 epoch 结束时提取 LSTM 输出。

    编辑:要方便地访问倒数第二层,您可以执行以下操作:

    # Create the model with the functional API
    inp = Input((train_X.shape[1], train_X.shape[2],))
    lstm = LSTM(100, return_sequences=False)(inp)
    dense = Dense(train_Y.shape[1], activation='softmax')(lstm)
    
    # Create the full model
    model = Model(inputs=inp, outputs=dense)
    
    # Create the model for access to the LSTM layer
    access = Model(inputs=inp, outputs=lstm)
    

    然后,您可以在实例化它时将access 传递给您的回调。这里要注意的关键是modelaccess 共享相同的LSTM 层,在训练model 时其权重会发生变化。

    【讨论】:

    • 我认为这并不能解决这个问题,因为他还想要倒数第二层的输出。他还必须查看有关此问题的功能 API。
    • 在回调中,您可以通过self.model 访问模型。那么,得到倒数第二层的输出就不是问题了。我添加了另一种方法来实现这一点。
    • @IonicSolutions 感谢您的持续帮助,我更新了我的问题。并从ModelCheckpoint使用,我不知道如何在每个epoch中获取LSTM层的输出?
    • 我相信使用我在答案中输入的access 模型变体更方便,但如果您想使用存储在磁盘上的模型,请参阅How to get the output of each layer?
    【解决方案2】:

    为了在每个时期获得预测输出,我们可以这样做:

    import tensorflow as tf
    import keras
    
    # define your custom callback for prediction
    class PredictionCallback(tf.keras.callbacks.Callback):    
      def on_epoch_end(self, epoch, logs={}):
        y_pred = self.model.predict(self.validation_data[0])
        print('prediction: {} at epoch: {}'.format(y_pred, epoch))
    
    # ...
    
    # register the callback before training starts
    model.fit(X_train, y_train, batch_size=32, epochs=25, 
              validation_data=(X_valid, y_valid), 
              callbacks=[PredictionCallback()])
    

    【讨论】:

      猜你喜欢
      • 2019-03-18
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      相关资源
      最近更新 更多