redesign project structure
This commit is contained in:
1 parent
104688be1b
commit
0ae8995eb3
19 files changed
+287
-188
No files matched your search
@@ -0,0 +1,21 @@
|
||||
hparams:
|
||||
max_epochs: 3
|
||||
batch_size: 64
|
||||
lr: 0.001
|
||||
weight_decay: 0.000001
|
||||
gradient_clip_val: 0.5
|
||||
accumulate_grad_batches: 1
|
||||
input_size: 784 # img size is 28*28*1
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
lin2_size: 256
|
||||
lin3_size: 128
|
||||
|
||||
|
||||
resume_training:
|
||||
lightning_ckpt:
|
||||
resume_from_ckpt: False
|
||||
ckpt_path: "checkpoints/epoch=2.ckpt"
|
||||
wandb:
|
||||
resume_wandb_run: False
|
||||
wandb_run_id: "8uuomodb"
|
||||
@@ -0,0 +1,70 @@
|
||||
from sklearn.metrics import accuracy_score
|
||||
import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
|
||||
# custom models
|
||||
from models.simple_mnist_classifier.models import *
|
||||
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
|
||||
def __init__(self, hparams=None):
|
||||
super().__init__()
|
||||
|
||||
if hparams:
|
||||
self.save_hyperparameters(hparams)
|
||||
|
||||
self.model = SimpleMNISTClassifier(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"])
|
||||
@@ -0,0 +1,32 @@
|
||||
from torch import nn
|
||||
|
||||
|
||||
class SimpleMNISTClassifier(nn.Module):
|
||||
|
||||
def __init__(self, config):
|
||||
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.ReLU(),
|
||||
nn.Dropout(p=0.3),
|
||||
nn.Linear(config["lin1_size"], config["lin2_size"]),
|
||||
nn.BatchNorm1d(config["lin2_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=0.25),
|
||||
nn.Linear(config["lin2_size"], config["lin3_size"]),
|
||||
nn.BatchNorm1d(config["lin3_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=0.2),
|
||||
nn.Linear(config["lin3_size"], config["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)
|
||||
@@ -0,0 +1,35 @@
|
||||
from models.simple_mnist_classifier.lightning_module import LitModel
|
||||
from models.simple_mnist_classifier import transforms
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def predict():
|
||||
"""
|
||||
Loads model from checkpoint.
|
||||
Model used in lightning_module.py and declaration of that model in models.py
|
||||
should be the same as during training.
|
||||
"""
|
||||
|
||||
CKPT_PATH = "epoch=0.ckpt"
|
||||
|
||||
# load model from checkpoint
|
||||
pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||
|
||||
# switch to evaluation mode
|
||||
pretrained_model.eval()
|
||||
pretrained_model.freeze()
|
||||
|
||||
# load data
|
||||
img = Image.open("../../example_img.png").convert("L")
|
||||
|
||||
# preprocess
|
||||
img = transforms.test_preprocess(img)
|
||||
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||
|
||||
# inference
|
||||
output = pretrained_model(img)
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
predict()
|
||||
@@ -0,0 +1,17 @@
|
||||
from torchvision import transforms
|
||||
|
||||
|
||||
img_augmentation_transformations = [
|
||||
transforms.RandomAffine((-4, 4), translate=(0.2, 0.2)),
|
||||
transforms.RandomHorizontalFlip(p=0.65),
|
||||
transforms.RandomRotation((-20, 20)),
|
||||
]
|
||||
|
||||
train_preprocess = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.RandomApply(img_augmentation_transformations, 0.5)
|
||||
])
|
||||
|
||||
test_preprocess = transforms.Compose([
|
||||
transforms.ToTensor()
|
||||
])
|
||||
@@ -0,0 +1,19 @@
|
||||
hparams:
|
||||
max_epochs: 3
|
||||
batch_size: 64
|
||||
lr: 0.001
|
||||
weight_decay: 0.000001
|
||||
gradient_clip_val: 0.5
|
||||
accumulate_grad_batches: 1
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
lin2_size: 256
|
||||
|
||||
|
||||
resume_training:
|
||||
lightning_ckpt:
|
||||
resume_from_ckpt: False
|
||||
ckpt_path: "checkpoints/epoch=2.ckpt"
|
||||
wandb:
|
||||
resume_wandb_run: False
|
||||
wandb_run_id: "8uuomodb"
|
||||
@@ -0,0 +1,115 @@
|
||||
from pl_bolts.models.self_supervised import CPCV2
|
||||
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-b1')
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# this model doesn't work yet, we wait for lightning-bolts patch
|
||||
# class ResnetPretrainedUnsupervised(nn.Module):
|
||||
# """
|
||||
# Trained without labels on Imagenet.
|
||||
# Perhaps the features when trained without labels are much better for classification or other tasks.
|
||||
# """
|
||||
# def __init__(self, config):
|
||||
# super().__init__()
|
||||
#
|
||||
# self.model = CPCV2(encoder='resnet18', pretrained='imagenet128').encoder
|
||||
# # self.model = CPCV2(encoder='resnet18', pretrained='stl10').encoder
|
||||
#
|
||||
# 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)
|
||||
@@ -0,0 +1,35 @@
|
||||
from models.transfer_learning_cifar10_classifier.lightning_module import LitModel
|
||||
from models.transfer_learning_cifar10_classifier import transforms
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def predict():
|
||||
"""
|
||||
Loads model from checkpoint.
|
||||
Model used in lightning_module.py and declaration of that model in models.py
|
||||
should be the same as during training.
|
||||
"""
|
||||
|
||||
CKPT_PATH = "epoch=0.ckpt"
|
||||
|
||||
# load model from checkpoint
|
||||
pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||
|
||||
# switch to evaluation mode
|
||||
pretrained_model.eval()
|
||||
pretrained_model.freeze()
|
||||
|
||||
# load data
|
||||
img = Image.open("../../example_img.png").convert("RGB")
|
||||
|
||||
# preprocess
|
||||
img = transforms.test_preprocess(img)
|
||||
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||
|
||||
# inference
|
||||
output = pretrained_model(img)
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
predict()
|
||||
@@ -0,0 +1,18 @@
|
||||
from torchvision import transforms
|
||||
|
||||
|
||||
img_augmentation_transformations = [
|
||||
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
|
||||
transforms.RandomHorizontalFlip(p=0.65),
|
||||
transforms.RandomRotation((-15, 15)),
|
||||
transforms.ColorJitter(hue=.05, saturation=.05),
|
||||
]
|
||||
|
||||
train_preprocess = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.RandomApply(img_augmentation_transformations, 0.5)
|
||||
])
|
||||
|
||||
test_preprocess = transforms.Compose([
|
||||
transforms.ToTensor()
|
||||
])
|
||||
Reference in new issue
Block a user