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

A T*_*A T 4 python performance-testing keras tensorflow 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]))
Run Code Online (Sandbox Code Playgroud)

这种方法的缺点是,我只能在训练结束时得到我关心的输出.宁愿每10个纪元左右获得指标.

BTW:和metrics=[]这里一起试过.可能回调是要走的路?

nur*_*ric 7

自定义回调将是一个很好的解决方案,让您足够的控制训练过程.有点像:

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]))
Run Code Online (Sandbox Code Playgroud)

哪里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()])
Run Code Online (Sandbox Code Playgroud)

注意:如果您不喜欢您的模型根据您的指标进行培训,您可以通过以下方式缩短培训时间:

self.model.stop_training = True
Run Code Online (Sandbox Code Playgroud)

这会停止你的训练.