如何设置 keras 自定义指标仅在纪元结束时调用?

Loi*_* L. 5 python keras tensorflow

我正在尝试为我的神经网络使用自定义指标,并且该指标只能在纪元结束时进行评估。我遇到的问题是,每批都会评估指标,这不是想要的行为。请注意,我正在使用生成器和fit_generatorkeras。

validation_data 加载了一个实现的生成器 keras.utils.Sequence

class DataGenerator(keras.utils.Sequence): 
   def __init__(self, inputs, labels, batch_size):
    self.inputs = inputs
    self.labels = labels
    self.batch_size = batch_size

   def __getitem__(self, index):
    #some processing done here
    return batch_inputs, batch_labels

   def __len__(self):
    return int(np.floor(len(self.inputs) / self.batch_size))
Run Code Online (Sandbox Code Playgroud)

我尝试实现 keras 文档建议的内容,但我没有找到任何信息来指定该指标只能在纪元结束时使用。

def auc_roc(y_true, y_pred):
   auc, up_opt = tf.metrics.auc(y_true, y_pred)
   K.get_session().run(tf.local_variables_initializer())
   with tf.control_dependencies([up_opt]):
       auc = tf.identity(auc)
   return auc
Run Code Online (Sandbox Code Playgroud)

因此,现在auc_roc在每个批次之后调用 ,而不是在 末尾调用一次epoch

ixe*_*ion 3

from sklearn.metrics import roc_auc_score
from keras.callbacks import Callback

class IntervalEvaluation(Callback):
    def __init__(self, validation_data=(), interval=10):
        super(Callback, self).__init__()

        self.interval = interval
        self.X_val, self.y_val = validation_data

    def on_epoch_end(self, epoch, logs={}):
        if epoch % self.interval == 0:
            y_pred = self.model.predict_proba(self.X_val, verbose=0)
            score = roc_auc_score(self.y_val, y_pred)
            print("interval evaluation - epoch: {:d} - score: {:.6f}".format(epoch, score))
Run Code Online (Sandbox Code Playgroud)

用法:

ival = IntervalEvaluation(validation_data=(x_test2, y_test2), interval=1)
Run Code Online (Sandbox Code Playgroud)

更多信息: http://digital-thinking.de/keras- Three-ways- to-use-custom-validation-metrics-in-keras/