finish MetricsHeatmapLoggerCallback
This commit is contained in:
1 parent
03ef46b158
commit
a77d9c435e
5 files changed
+46
-23
No files matched your search
@@ -1,4 +1,6 @@
|
||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, multilabel_confusion_matrix
|
||||
from pytorch_lightning.callbacks import Callback
|
||||
from torch.nn.functional import one_hot
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
@@ -52,7 +54,7 @@ class ImagePredictionLoggerCallback(Callback):
|
||||
|
||||
trainer.logger.experiment.log({"examples": [
|
||||
wandb.Image(x, caption=f"Pred:{pred}, Label:{y}") for x, pred, y in zip(val_imgs, preds, self.val_labels)
|
||||
]})
|
||||
]}, commit=False)
|
||||
|
||||
|
||||
class UnfreezeModelCallback(Callback):
|
||||
@@ -66,10 +68,14 @@ class UnfreezeModelCallback(Callback):
|
||||
param.requires_grad = True
|
||||
|
||||
|
||||
class ConfusionMatrixLoggerCallback(Callback):
|
||||
"""Log confusion matrix calculated from each validation epoch."""
|
||||
class MetricsHeatmapLoggerCallback(Callback):
|
||||
"""
|
||||
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
|
||||
Expects validation step to return predictions and targets.
|
||||
"""
|
||||
def __init__(self):
|
||||
self.val_loop_outputs = []
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
self.ready = False
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
@@ -79,10 +85,26 @@ class ConfusionMatrixLoggerCallback(Callback):
|
||||
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||
"""Gather data from single batch."""
|
||||
if self.ready:
|
||||
self.val_loop_outputs.append(outputs)
|
||||
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:
|
||||
for outputs in self.val_loop_outputs:
|
||||
preds, targets = outputs
|
||||
self.val_loop_outputs = []
|
||||
self.preds = torch.cat(self.preds)
|
||||
self.targets = torch.cat(self.targets)
|
||||
f1 = f1_score(self.preds, self.targets, average=None)
|
||||
r = recall_score(self.preds, self.targets, average=None)
|
||||
p = precision_score(self.preds, self.targets, average=None)
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"f1_p_r_heatmap{pl_module.current_epoch}": wandb.plots.HeatMap(
|
||||
x_labels=[str(i) for i in range(len(f1))], # class names can be hardcoded here
|
||||
y_labels=["f1", "precision", "recall"],
|
||||
matrix_values=[f1, p, r],
|
||||
show_text=True,
|
||||
)}, commit=False)
|
||||
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
Reference in new issue
Block a user