每10个时期报告一次Keras模型评估指标?

时间:2018-05-28 14:19:35

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

我想知道我的模型的特异性和敏感性。目前,我在所有时期结束后评估模型:

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个纪元左右获得指标。

BTW:尝试metrics=[] here。可能需要callback吗?

1 个答案:

答案 0 :(得分:6)

自定义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

将停止为您进行培训。

相关问题