BIG clean up and refactoring

This commit is contained in:
hobogalaxy committed 2020-11-27 20:23:05 +01:00
1 parent a905c0b094
commit e7a579d720
24 files changed
+369 -597

No files matched your search

@@ -0,0 +1,58 @@
import pytorch_lightning as pl
import torch.nn.functional as F
import torch
# custom models
from models.example_model.models import *
class LitModel(pl.LightningModule):
"""
This is example of lightning model.
The folder name of LitModel used during trainig should be specified in run config and all parameters from
'model' section will be passed in 'hparams' dictionary.
It enables you to specify what happens during training, validation and test step.
You can just remove validatin_step() or test_step() if you don't want to use them during trainig and model
should still train correctly.
See 'simple_mnist_classifier' for more proper example.
"""
def __init__(self, hparams=None):
super().__init__()
if hparams:
self.save_hyperparameters(hparams)
self.model = ExampleModel(hparams=self.hparams)
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)
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)
return loss
# 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)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
+21
View File
@@ -0,0 +1,21 @@
from torch import nn
class ExampleModel(nn.Module):
def __init__(self, hparams):
super().__init__()
self.model = nn.Sequential(
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
nn.BatchNorm1d(hparams["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
batch_size, channels, width, height = x.size()
x = x.view(batch_size, -1)
return self.model(x)
@@ -15,7 +15,7 @@ class LitModel(pl.LightningModule):
if hparams:
self.save_hyperparameters(hparams)
self.model = SimpleMNISTClassifier(config=self.hparams)
self.model = SimpleMNISTClassifier(hparams=self.hparams)
def forward(self, x):
return self.model(x)
@@ -3,24 +3,24 @@ from torch import nn
class SimpleMNISTClassifier(nn.Module):
def __init__(self, config):
def __init__(self, hparams):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential(
nn.Linear(config["input_size"], config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
nn.BatchNorm1d(hparams["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.3),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
nn.BatchNorm1d(hparams["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin2_size"], config["lin3_size"]),
nn.BatchNorm1d(config["lin3_size"]),
nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
nn.BatchNorm1d(hparams["lin3_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin3_size"], config["output_size"]),
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
nn.LogSoftmax(dim=1)
)
@@ -1,70 +0,0 @@
from sklearn.metrics import accuracy_score
import pytorch_lightning as pl
import torch.nn.functional as F
import torch
# custom models
from models.transfer_learning_img_classifier.models import *
class LitModel(pl.LightningModule):
def __init__(self, hparams=None):
super().__init__()
if hparams:
self.save_hyperparameters(hparams)
self.model = EfficientNetPretrained(config=self.hparams)
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)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
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)
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)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
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)
# we can return here anything and then read it in some callback
return preds, 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)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
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)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
@@ -1,82 +0,0 @@
from efficientnet_pytorch import EfficientNet
from torchvision import models
from torch import nn
class EfficientNetPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = EfficientNet.from_pretrained('efficientnet-b0')
for param in self.model.parameters():
param.requires_grad = False
self.model._fc = nn.Sequential(
nn.Linear(self.model._fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
class ResnetPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = models.resnet18(pretrained=True)
for param in self.model.parameters():
param.requires_grad = False
self.model.fc = nn.Sequential(
nn.Linear(self.model.fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
class ResnextPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = models.resnext101_32x8d(pretrained=True)
for param in self.model.parameters():
param.requires_grad = False
self.model.fc = nn.Sequential(
nn.Linear(self.model.fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)