如何在Keras中创建自定义回调?

时间:2018-09-11 23:38:10

标签: python callback keras

我对创建适合我的keras模型的回调很感兴趣。更详细地讲,我想在每个纪元结束时从机器人电报中接收带有val_acc的消息。我知道您可以在classifier.fit()中添加callback_list作为参数,但是许多回调是由keras预先构建的,我不知道添加自定义回调是很热门。

谢谢!

2 个答案:

答案 0 :(得分:3)

例如,我为我的自定义回调提供F1指标。它在每个时间段的末尾不是按批次计算F1,而是针对所有传递的列车数据(以及验证)进行计算。可以轻松使用其他所有指标进行自定义

class F1History(tf.keras.callbacks.Callback):

    def __init__(self, train, validation=None):
        super(F1History, self).__init__()
        self.validation = validation
        self.train = train

    def on_epoch_end(self, epoch, logs={}):

        logs['F1_score_train'] = float('-inf')
        X_train, y_train = self.train[0], self.train[1]
        y_pred = (self.model.predict(X_train).ravel()>0.5)+0
        score = f1_score(y_train, y_pred)       

        if (self.validation):
            logs['F1_score_val'] = float('-inf')
            X_valid, y_valid = self.validation[0], self.validation[1]
            y_val_pred = (self.model.predict(X_valid).ravel()>0.5)+0
            val_score = f1_score(y_valid, y_val_pred)
            logs['F1_score_train'] = np.round(score, 5)
            logs['F1_score_val'] = np.round(val_score, 5)
        else:
            logs['F1_score_train'] = np.round(score, 5)

适合:

es = EarlyStopping(patience=3, verbose=1, min_delta=0.001, monitor='F1_score_val', mode='max', restore_best_weights=True)
model.fit(x_train,y_train, epochs=10, 
          callbacks=[F1History(train=(x_train,y_train),validation=(x_val,y_val)),es])

答案 1 :(得分:1)

以下是我如何向回调添加验证准确性的示例:

class AccuracyHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.acc = []

    def on_epoch_end(self, batch, logs={}):
        self.acc.append(logs.get('val_acc'))

history = AccuracyHistory()

model.fit(x, y,
          ...
          callbacks=[history])