finish MetricsHeatmapLoggerCallback
This commit is contained in:
1 parent
03ef46b158
commit
a77d9c435e
5 files changed
+46
-23
No files matched your search
+4
-4
@@ -225,7 +225,7 @@ ipython_config.py
|
|||||||
# git rm -r .ipynb_checkpoints/
|
# git rm -r .ipynb_checkpoints/
|
||||||
|
|
||||||
.idea/
|
.idea/
|
||||||
data/
|
project/data/
|
||||||
logs/
|
project/lightning_logs/
|
||||||
lightning_logs/
|
project/wandb/
|
||||||
wandb/
|
project/logs/
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
num_of_gpus: -1
|
num_of_gpus: -1
|
||||||
|
|
||||||
hparams:
|
hparams:
|
||||||
max_epochs: 10
|
max_epochs: 3
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
accumulate_grad_batches: 1
|
accumulate_grad_batches: 1
|
||||||
|
|||||||
@@ -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 pytorch_lightning.callbacks import Callback
|
||||||
|
from torch.nn.functional import one_hot
|
||||||
import torch
|
import torch
|
||||||
import wandb
|
import wandb
|
||||||
import os
|
import os
|
||||||
@@ -52,7 +54,7 @@ class ImagePredictionLoggerCallback(Callback):
|
|||||||
|
|
||||||
trainer.logger.experiment.log({"examples": [
|
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)
|
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):
|
class UnfreezeModelCallback(Callback):
|
||||||
@@ -66,10 +68,14 @@ class UnfreezeModelCallback(Callback):
|
|||||||
param.requires_grad = True
|
param.requires_grad = True
|
||||||
|
|
||||||
|
|
||||||
class ConfusionMatrixLoggerCallback(Callback):
|
class MetricsHeatmapLoggerCallback(Callback):
|
||||||
"""Log confusion matrix calculated from each validation epoch."""
|
"""
|
||||||
|
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
|
||||||
|
Expects validation step to return predictions and targets.
|
||||||
|
"""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.val_loop_outputs = []
|
self.preds = []
|
||||||
|
self.targets = []
|
||||||
self.ready = False
|
self.ready = False
|
||||||
|
|
||||||
def on_sanity_check_end(self, trainer, pl_module):
|
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):
|
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||||
"""Gather data from single batch."""
|
"""Gather data from single batch."""
|
||||||
if self.ready:
|
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):
|
def on_validation_epoch_end(self, trainer, pl_module):
|
||||||
|
"""Generate f1, precision and recall heatmap."""
|
||||||
if self.ready:
|
if self.ready:
|
||||||
for outputs in self.val_loop_outputs:
|
self.preds = torch.cat(self.preds)
|
||||||
preds, targets = outputs
|
self.targets = torch.cat(self.targets)
|
||||||
self.val_loop_outputs = []
|
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 = []
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
||||||
from pl_bolts.models.regression import LogisticRegression
|
from pl_bolts.models.regression import LogisticRegression
|
||||||
from pl_bolts.models.regression import LinearRegression
|
from pl_bolts.models.regression import LinearRegression
|
||||||
|
from torch.nn.functional import one_hot
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
import torch
|
import torch
|
||||||
@@ -31,10 +32,10 @@ class LitModel(pl.LightningModule):
|
|||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
preds, y = preds.cpu(), y.cpu()
|
||||||
acc = accuracy_score(preds, y)
|
acc = accuracy_score(preds, y)
|
||||||
f1 = f1_score(preds, y, average="micro")
|
|
||||||
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('train_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
# f1 = f1_score(preds, y, average="micro")
|
||||||
|
# self.log('train_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
|
|
||||||
return loss
|
return loss
|
||||||
|
|
||||||
@@ -48,10 +49,10 @@ class LitModel(pl.LightningModule):
|
|||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
preds, y = preds.cpu(), y.cpu()
|
||||||
acc = accuracy_score(preds, y)
|
acc = accuracy_score(preds, y)
|
||||||
f1 = f1_score(preds, y, average="micro")
|
|
||||||
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('val_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
# f1 = f1_score(preds, y, average="micro")
|
||||||
|
# self.log('val_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
|
|
||||||
return preds, y
|
return preds, y
|
||||||
|
|
||||||
@@ -65,10 +66,10 @@ class LitModel(pl.LightningModule):
|
|||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
preds, y = preds.cpu(), y.cpu()
|
||||||
acc = accuracy_score(preds, y)
|
acc = accuracy_score(preds, y)
|
||||||
f1 = f1_score(preds, y, average="micro")
|
|
||||||
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('test_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
# f1 = f1_score(preds, y, average="micro")
|
||||||
|
# self.log('test_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
|
|
||||||
return loss
|
return loss
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -38,9 +38,8 @@ def train(config):
|
|||||||
mode=config["callbacks"]["checkpoint"]["mode"],
|
mode=config["callbacks"]["checkpoint"]["mode"],
|
||||||
save_last=config["callbacks"]["checkpoint"]["save_last"],
|
save_last=config["callbacks"]["checkpoint"]["save_last"],
|
||||||
),
|
),
|
||||||
# ExampleCallback(),
|
MetricsHeatmapLoggerCallback(),
|
||||||
# ConfusionMatrixLoggerCallback(),
|
UnfreezeModelCallback(wait_epochs=1),
|
||||||
# UnfreezeModelCallback(wait_epochs=5),
|
|
||||||
# SaveModelOnnxCallback(datamodule=datamodule, save_dir=wandb_logger.save_dir)
|
# SaveModelOnnxCallback(datamodule=datamodule, save_dir=wandb_logger.save_dir)
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -57,9 +56,10 @@ def train(config):
|
|||||||
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
||||||
weights_summary=config["printing"]["weights_summary"],
|
weights_summary=config["printing"]["weights_summary"],
|
||||||
num_sanity_val_steps=3,
|
num_sanity_val_steps=3,
|
||||||
|
default_root_dir="logs/"
|
||||||
# fast_dev_run=True,
|
# fast_dev_run=True,
|
||||||
# min_epochs=10,
|
# min_epochs=10,
|
||||||
# limit_train_batches=0.01
|
# limit_train_batches=0.1
|
||||||
# limit_val_batches=0.01
|
# limit_val_batches=0.01
|
||||||
# limit_test_batches=0.01
|
# limit_test_batches=0.01
|
||||||
# auto_scale_batch_size="power",
|
# auto_scale_batch_size="power",
|
||||||
|
|||||||
Reference in new issue
Block a user