【问题标题】:Report Keras model evaluation metrics every 10 epochs?每 10 个 epoch 报告一次 Keras 模型评估指标?
【发布时间】:2018-11-07 04:01:34
【问题描述】:

我想知道我的模型的特异性和敏感性。目前,我正在评估所有 epoch 完成后的模型:

from sklearn.metrics import confusion_matrix

predictions = model.predict(x_test)
y_test = np.argmax(y_test, axis=-1)
predictions = np.argmax(predictions, axis=-1)
c = confusion_matrix(y_test, predictions)
print('Confusion matrix:\n', c)
print('sensitivity', c[0, 0] / (c[0, 1] + c[0, 0]))
print('specificity', c[1, 1] / (c[1, 1] + c[1, 0]))

这种方法的缺点是,我只在训练完成后才能得到我关心的输出。宁愿每 10 个 epoch 左右获取一次指标。

顺便说一句:尝试使用 metrics=[] here。可能是callback 是要走的路吗?

【问题讨论】:

  • 自定义回调确实是在训练期间完成自定义操作的好方法,请考虑实现一个并确保将其添加到模型训练中。与每个课程一样,您可以将测试集传递给回调,以便在训练中检查指标时使用它

标签: python tensorflow keras performance-testing keras-2


【解决方案1】:

自定义Callback 将是一个很好的解决方案,让您可以充分控制训练过程。大致如下:

class SensitivitySpecificityCallback(Callback):
    def on_epoch_end(self, epoch, logs=None):
        if epoch % 10 == 1:
            x_test = self.validation_data[0]
            y_test = self.validation_data[1]
            # x_test, y_test = self.validation_data
            predictions = self.model.predict(x_test)
            y_test = np.argmax(y_test, axis=-1)
            predictions = np.argmax(predictions, axis=-1)
            c = confusion_matrix(y_test, predictions)

            print('Confusion matrix:\n', c)
            print('sensitivity', c[0, 0] / (c[0, 1] + c[0, 0]))
            print('specificity', c[1, 1] / (c[1, 1] + c[1, 0]))

其中epoch 是纪元编号,logs 包含通常的指标 + 模型训练的损失。

然后运行:

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          shuffle='batch',
          validation_data=(x_test, y_test),
          callbacks=[SensitivitySpecificityCallback()])

注意:如果您不喜欢根据指标训练模型的方式,您可以缩短训练时间:

self.model.stop_training = True

这将为您停止训练。

【讨论】:

  • 谢谢,这让我找到了正确的方向。编辑您的代码以使其实际工作。
猜你喜欢
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 2020-09-11
  • 2021-12-27
  • 2020-09-26
  • 1970-01-01
相关资源
最近更新 更多