add ConfusionMatrixLoggerCallback

This commit is contained in:
hobogalaxy committed 2020-12-08 00:20:56 +01:00
1 parent 41b66d43b7
commit 03055295e6
3 files changed
+50 -4

No files matched your search

+44 -3
View File
@@ -86,11 +86,12 @@ class UnfreezeModelCallback(pl.Callback):
class MetricsHeatmapLoggerCallback(pl.Callback):
"""
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
Generate f1, precision and recall heatmap from validation epoch outputs.
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
def __init__(self):
def __init__(self, class_names):
self.class_names = class_names
self.preds = []
self.targets = []
self.ready = False
@@ -117,7 +118,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
trainer.logger.experiment.log({
f"f1_p_r_heatmap_{trainer.current_epoch}": wandb.plots.HeatMap(
x_labels=[str(i) for i in range(len(f1))], # class names can be hardcoded here
x_labels=self.class_names,
y_labels=["f1", "precision", "recall"],
matrix_values=[f1, p, r],
show_text=True,
@@ -127,6 +128,46 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
self.targets = []
class ConfusionMatrixLoggerCallback(pl.Callback):
"""
Generate Confusion Matrix.
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
def __init__(self, class_names):
self.class_names = class_names
self.preds = []
self.targets = []
self.ready = False
def on_sanity_check_end(self, trainer, pl_module):
"""Start executing this callback only after all validation sanity checks end."""
self.ready = True
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
"""Gather data from single batch."""
if self.ready:
preds, targets = outputs
self.preds.append(preds)
self.targets.append(targets)
def on_validation_epoch_end(self, trainer, pl_module):
"""Generate f1, precision and recall heatmap."""
if self.ready:
self.preds = torch.cat(self.preds).tolist()
self.targets = torch.cat(self.targets).tolist()
trainer.logger.experiment.log({
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
self.preds,
self.targets,
class_names=self.class_names)
}, commit=False)
self.preds = []
self.targets = []
class SaveCodeToWandbCallback(pl.Callback):
"""
Upload specified code files to wandb at the beginning of the run.