7 files changed
+80
-40
No files matched your search
+4
-4
@@ -225,7 +225,7 @@ ipython_config.py
|
||||
# git rm -r .ipynb_checkpoints/
|
||||
|
||||
.idea/
|
||||
data/
|
||||
logs/
|
||||
lightning_logs/
|
||||
wandb/
|
||||
project/data/
|
||||
project/lightning_logs/
|
||||
project/wandb/
|
||||
project/logs/
|
||||
@@ -35,7 +35,7 @@ https://pytorch.org/get-started/locally/
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### PyCharm set up
|
||||
### PyCharm setup
|
||||
- open this repository as PyCharm project
|
||||
- set "hack_env" as project interpreter:<br>
|
||||
`Ctrl + Shift + A -> type "Project Interpreter"`
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
num_of_gpus: -1
|
||||
|
||||
hparams:
|
||||
max_epochs: 10
|
||||
max_epochs: 3
|
||||
batch_size: 64
|
||||
lr: 0.001
|
||||
accumulate_grad_batches: 1
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
||||
from pytorch_lightning.callbacks import Callback
|
||||
import seaborn
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
@@ -18,8 +20,10 @@ class ExampleCallback(Callback):
|
||||
print('Do something when training ends.')
|
||||
|
||||
|
||||
class SaveOnnxToWandbCallback(Callback):
|
||||
"""Save model in .onnx format."""
|
||||
class SaveModelOnnxCallback(Callback):
|
||||
"""
|
||||
Save model in .onnx format.
|
||||
"""
|
||||
def __init__(self, datamodule, save_dir):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
x, y = first_batch
|
||||
@@ -39,24 +43,36 @@ class SaveOnnxToWandbCallback(Callback):
|
||||
|
||||
|
||||
class ImagePredictionLoggerCallback(Callback):
|
||||
"""Each epoch upload to wandb a couple of the same images with predicted labels."""
|
||||
def __init__(self, val_samples, num_samples=32):
|
||||
super().__init__()
|
||||
self.val_imgs, self.val_labels = val_samples[:num_samples]
|
||||
"""
|
||||
Each epoch upload to wandb a couple of the same images with predicted labels.
|
||||
"""
|
||||
def __init__(self, datamodule, num_samples=8):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
self.imgs, self.labels = first_batch
|
||||
self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples]
|
||||
self.ready = True
|
||||
|
||||
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_epoch_end(self, trainer, pl_module):
|
||||
val_imgs = self.val_imgs.to(device=pl_module.device)
|
||||
|
||||
logits = pl_module(val_imgs)
|
||||
preds = torch.argmax(logits, -1)
|
||||
|
||||
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)
|
||||
]})
|
||||
if self.ready:
|
||||
imgs = self.imgs.to(device=pl_module.device)
|
||||
logits = pl_module(imgs)
|
||||
preds = torch.argmax(logits, -1)
|
||||
trainer.logger.experiment.log({f"img_examples": [
|
||||
wandb.Image(
|
||||
x,
|
||||
caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}"
|
||||
) for x, pred, y in zip(imgs, preds, self.labels)
|
||||
]}, commit=False)
|
||||
|
||||
|
||||
class UnFreezeModelCallback(Callback):
|
||||
"""Unfreeze model after a few epochs."""
|
||||
class UnfreezeModelCallback(Callback):
|
||||
"""
|
||||
Unfreeze model after a few epochs.
|
||||
"""
|
||||
def __init__(self, wait_epochs=5):
|
||||
self.wait_epochs = wait_epochs
|
||||
|
||||
@@ -66,10 +82,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 +99,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_{trainer.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 pl_bolts.models.regression import LogisticRegression
|
||||
from pl_bolts.models.regression import LinearRegression
|
||||
from torch.nn.functional import one_hot
|
||||
import torch.nn.functional as F
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
@@ -31,10 +32,10 @@ class LitModel(pl.LightningModule):
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
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_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
|
||||
|
||||
@@ -48,10 +49,10 @@ class LitModel(pl.LightningModule):
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
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_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
|
||||
|
||||
@@ -65,10 +66,10 @@ class LitModel(pl.LightningModule):
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
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_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
|
||||
|
||||
|
||||
+6
-5
@@ -38,10 +38,10 @@ def train(config):
|
||||
mode=config["callbacks"]["checkpoint"]["mode"],
|
||||
save_last=config["callbacks"]["checkpoint"]["save_last"],
|
||||
),
|
||||
# ExampleCallback(),
|
||||
# ConfusionMatrixLoggerCallback(),
|
||||
# UnFreezeModelCallback(wait_epochs=5),
|
||||
# SaveOnnxToWandbCallback(datamodule=datamodule, save_dir=wandb_logger.save_dir)
|
||||
# MetricsHeatmapLoggerCallback(),
|
||||
# UnfreezeModelCallback(wait_epochs=5),
|
||||
# ImagePredictionLoggerCallback(datamodule=datamodule),
|
||||
# SaveModelOnnxCallback(datamodule=datamodule, save_dir=wandb_logger.save_dir)
|
||||
]
|
||||
|
||||
# Init trainer
|
||||
@@ -57,9 +57,10 @@ def train(config):
|
||||
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
||||
weights_summary=config["printing"]["weights_summary"],
|
||||
num_sanity_val_steps=3,
|
||||
default_root_dir="logs/"
|
||||
# fast_dev_run=True,
|
||||
# min_epochs=10,
|
||||
# limit_train_batches=0.01
|
||||
# limit_train_batches=0.1
|
||||
# limit_val_batches=0.01
|
||||
# limit_test_batches=0.01
|
||||
# auto_scale_batch_size="power",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
scikit-learn>=0.23.2
|
||||
torchvision>=0.8.1
|
||||
pytorch-lightning>=1.0.6
|
||||
pytorch-lightning-bolts>=0.2.5
|
||||
wandb>=0.10.10
|
||||
PyYAML>=5.3.1
|
||||
efficientnet-pytorch>=0.7.0
|
||||
seaborn>=0.11.0
|
||||
Reference in new issue
Block a user