change folder structure

This commit is contained in:
hobogalaxy committed 2021-01-12 18:33:04 +01:00
1 parent fbe2464426
commit 9a5a4eb192
23 files changed
+148 -120

No files matched your search

+1
View File
@@ -0,0 +1 @@
# package file
+32
View File
@@ -0,0 +1,32 @@
from torch import nn
class SimpleMNISTClassifier(nn.Module):
def __init__(self, hparams):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential(
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
nn.BatchNorm1d(hparams["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.3),
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
nn.BatchNorm1d(hparams["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
nn.BatchNorm1d(hparams["lin3_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
batch_size, channels, width, height = x.size()
# (b, 1, 28, 28) -> (b, 1*28*28)
x = x.view(batch_size, -1)
return self.model(x)
+28
View File
@@ -0,0 +1,28 @@
from pytorch_lightning import Callback
class ExampleCallback(Callback):
def __init__(self):
pass
def on_init_start(self, trainer):
print('Starting to initialize trainer!')
def on_init_end(self, trainer):
print('Trainer is initialized now.')
def on_train_end(self, trainer, pl_module):
print('Do something when training ends.')
class UnfreezeModelCallback(Callback):
"""
Unfreeze model after a few epochs.
"""
def __init__(self, wait_epochs=5):
self.wait_epochs = wait_epochs
def on_epoch_end(self, trainer, pl_module):
if trainer.current_epoch == self.wait_epochs:
for param in pl_module.model.model.parameters():
param.requires_grad = True
+190
View File
@@ -0,0 +1,190 @@
from sklearn.metrics import precision_score, recall_score, f1_score
from pytorch_lightning.loggers import WandbLogger
from wandb.sdk.wandb_run import Run as wandb_run
from pytorch_lightning import Callback
import torch
import wandb
import glob
import os
class SaveCodeToWandb(Callback):
"""
Upload all *.py files to wandb at the beginning of the run.
"""
def __init__(self, code_dir: str):
self.code_dir = code_dir
def on_sanity_check_end(self, trainer, pl_module):
"""Upload files when all validation sanity checks end."""
code = wandb.Artifact('project-source', type='code')
for path in glob.glob(os.path.join(self.code_dir, '**/*.py'), recursive=True):
code.add_file(path)
wandb.run.use_artifact(code)
class UploadAllCheckpointsToWandb(Callback):
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
self.ckpt_dir = ckpt_dir
self.upload_best_only = upload_best_only
def on_train_end(self, trainer, pl_module):
"""Upload ckpts when training ends."""
ckpts = wandb.Artifact('experiment-ckpts', type='checkpoints')
if self.upload_best_only:
ckpts.add_file(trainer.checkpoint_callback.best_model_path)
else:
for path in glob.glob(os.path.join(self.ckpt_dir, '**/*.ckpt'), recursive=True):
ckpts.add_file(path)
wandb.run.use_artifact(ckpts)
class SaveMetricsHeatmapToWandb(Callback):
"""
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, class_names=None):
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["batch_val_preds"], outputs["batch_val_y"]
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).cpu()
self.targets = torch.cat(self.targets).cpu()
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)
logger = None
for some_logger in trainer.logger.experiment:
if isinstance(some_logger, wandb_run):
logger = some_logger
logger.log({
f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": wandb.plots.HeatMap(
x_labels=self.class_names,
y_labels=["f1", "precision", "recall"],
matrix_values=[f1, p, r],
show_text=True,
)}, commit=False)
self.preds = []
self.targets = []
class SaveConfusionMatrixToWandb(Callback):
"""
Generate Confusion Matrix.
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
def __init__(self, class_names=None):
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["batch_val_preds"], outputs["batch_val_y"]
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()
for logger in trainer.logger.experiment:
if isinstance(logger, wandb_run):
logger.log({
f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix(
preds=self.preds,
y_true=self.targets,
class_names=self.class_names)
}, commit=False)
self.preds = []
self.targets = []
class SaveBestMetricScoresToWandb(Callback):
def __init__(self):
self.train_loss_best = None
self.train_acc_best = None
self.val_loss_best = None
self.val_acc_best = None
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_epoch_end(self, trainer, pl_module):
if self.ready:
for logger in trainer.logger.experiment:
metrics = trainer.callback_metrics
if isinstance(logger, wandb_run):
if self.train_loss_best is None or metrics["train_loss"] < self.train_loss_best:
self.train_loss_best = metrics["train_loss"]
if self.train_acc_best is None or metrics["train_acc"] > self.train_acc_best:
self.train_acc_best = metrics["train_acc"]
if self.val_loss_best is None or metrics["val_loss"] < self.val_loss_best:
self.val_loss_best = metrics["val_loss"]
if self.val_acc_best is None or metrics["val_acc"] > self.val_acc_best:
self.val_acc_best = metrics["val_acc"]
logger.log({"train_loss_best": self.train_loss_best}, commit=False)
logger.log({"train_acc_best": self.train_acc_best}, commit=False)
logger.log({"val_loss_best": self.val_loss_best}, commit=False)
logger.log({"val_acc_best": self.val_acc_best}, commit=False)
# class SaveImagePredictionsToWandb(Callback):
# """
# 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):
# 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)
@@ -0,0 +1,53 @@
from torch.utils.data import DataLoader, ConcatDataset, random_split
from pytorch_lightning import LightningDataModule
from torchvision.transforms import transforms
from torchvision.datasets import MNIST
class MNISTDataModule(LightningDataModule):
"""
This is example of datamodule for MNIST dataset.
To learn how to create datamodules visit:
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
"""
def __init__(self, data_dir, **args):
super().__init__()
self.data_dir = data_dir # data_dir is specified in config.yaml
self.batch_size = args["batch_size"]
self.train_val_test_split = args["train_val_test_split"]
self.num_workers = args["num_workers"]
self.pin_memory = args["pin_memory"]
self.transforms = transforms.ToTensor()
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
dataset = ConcatDataset(datasets=[trainset, testset])
self.data_train, self.data_val, self.data_test = random_split(dataset, self.train_val_test_split)
def train_dataloader(self):
return DataLoader(dataset=self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory, shuffle=True)
def val_dataloader(self):
return DataLoader(dataset=self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self):
return DataLoader(dataset=self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
+27
View File
@@ -0,0 +1,27 @@
from torch.utils.data import Dataset
from PIL import Image
import os
class TestDataset(Dataset):
"""
Example dataset class for loading images from folder and converting them to monochromatic.
Can be used to perform inference with trained MNIST model.
'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by datamodules.
"""
def __init__(self, img_dir, transform):
self.transform = transform
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
def __getitem__(self, idx):
image = Image.open(self.images[idx]).convert("L") # convert to black and white
# image = Image.open(self.images[idx]).convert("RGB")
if self.transform is not None:
image = self.transform(image)
return image
def __len__(self):
return len(self.images)
@@ -0,0 +1,78 @@
from pytorch_lightning.metrics.classification import Accuracy
from template_utils.initializers import load_class
import pytorch_lightning as pl
import torch.nn.functional as F
import torch
# import custom architectures
from src.architectures.simple_mnist import SimpleMNISTClassifier
class LitModel(pl.LightningModule):
"""
This is example of lightning model for MNIST classification.
This class enables you to specify what happens during training, validation and test step.
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
To learn how to create lightning models visit:
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
"""
def __init__(self, model_config, optimizer_config):
super().__init__()
hparams = {**model_config["args"], **optimizer_config["args"]}
self.save_hyperparameters(hparams)
self.optimizer_config = optimizer_config
self.model = SimpleMNISTClassifier(hparams=self.hparams)
self.accuracy = Accuracy()
def forward(self, x):
return self.model(x)
# logic for a single training step
def training_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# training metrics
preds = torch.argmax(logits, dim=1)
acc = self.accuracy(preds, y)
self.log('train_loss', loss, on_step=False, on_epoch=True)
self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
return loss
# logic for a single validation step
def validation_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# validation metrics
preds = torch.argmax(logits, dim=1)
acc = self.accuracy(preds, y)
self.log('val_loss', loss, on_step=False, on_epoch=True)
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
# we can return here anything and then read it in some callback
return {"batch_val_loss": loss, "batch_val_acc": acc, "batch_val_preds": preds, "batch_val_y": y}
# logic for a single testing step
def test_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# test metrics
preds = torch.argmax(logits, dim=1)
acc = self.accuracy(preds, y)
self.log('test_loss', loss, on_step=False, on_epoch=True)
self.log('test_acc', acc, on_step=False, on_epoch=True)
return loss
def configure_optimizers(self):
Optimizer = load_class(self.optimizer_config["class"])
return Optimizer(self.parameters(), **self.optimizer_config["args"])
@@ -0,0 +1,13 @@
"""
Example file containing data transformations, which can be used by datamodule.
"""
from torchvision import transforms
mnist_train_transforms = transforms.Compose([
transforms.ToTensor(),
])
mnist_test_transforms = transforms.Compose([
transforms.ToTensor(),
])