File size: 6,790 Bytes
3631068 acab651 3631068 5c43f60 3631068 69c8e55 5c43f60 3631068 69c8e55 3631068 69c8e55 3631068 5c43f60 3631068 6ff7b63 d358c49 3631068 69c8e55 3631068 5c43f60 3631068 6ff7b63 69c8e55 3631068 5c43f60 3631068 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
import torchmetrics
from . import config
from typing import Tuple, Dict, List, Any
import numpy as np
import torch
import torchvision
import torch.nn as nn
import pytorch_lightning as ptl
class ResNet18Regressor(nn.Module):
def __init__(self):
super().__init__()
self.model = torchvision.models.resnet18(weights=False)
self.model.fc = nn.Linear(512, config.FONT_COUNT + 12)
def forward(self, X):
X = self.model(X)
# [0, 1]
X[..., config.FONT_COUNT + 2 :] = X[..., config.FONT_COUNT + 2 :].sigmoid()
return X
class FontDetectorLoss(nn.Module):
def __init__(self, lambda_font, lambda_direction, lambda_regression):
super().__init__()
self.category_loss = nn.CrossEntropyLoss()
self.regression_loss = nn.MSELoss()
self.lambda_font = lambda_font
self.lambda_direction = lambda_direction
self.lambda_regression = lambda_regression
def forward(self, y_hat, y):
font_cat = self.category_loss(y_hat[..., : config.FONT_COUNT], y[..., 0].long())
direction_cat = self.category_loss(
y_hat[..., config.FONT_COUNT : config.FONT_COUNT + 2], y[..., 1].long()
)
regression = self.regression_loss(
y_hat[..., config.FONT_COUNT + 2 :], y[..., 2:]
)
return (
self.lambda_font * font_cat
+ self.lambda_direction * direction_cat
+ self.lambda_regression * regression
)
class CosineWarmupScheduler(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer, warmup, max_iters):
self.warmup = warmup
self.max_num_iters = max_iters
super().__init__(optimizer)
def get_lr(self):
lr_factor = self.get_lr_factor(epoch=self.last_epoch)
return [base_lr * lr_factor for base_lr in self.base_lrs]
def get_lr_factor(self, epoch):
lr_factor = 0.5 * (1 + np.cos(np.pi * epoch / self.max_num_iters))
if epoch <= self.warmup:
lr_factor *= epoch * 1.0 / self.warmup
return lr_factor
class FontDetector(ptl.LightningModule):
def __init__(
self,
model: nn.Module,
lambda_font: float,
lambda_direction: float,
lambda_regression: float,
lr: float,
betas: Tuple[float, float],
num_warmup_iters: int,
num_iters: int,
):
super().__init__()
self.model = model
self.loss = FontDetectorLoss(lambda_font, lambda_direction, lambda_regression)
self.font_accur_train = torchmetrics.Accuracy(
task="multiclass", num_classes=config.FONT_COUNT
)
self.direction_accur_train = torchmetrics.Accuracy(
task="multiclass", num_classes=2
)
self.font_accur_val = torchmetrics.Accuracy(
task="multiclass", num_classes=config.FONT_COUNT
)
self.direction_accur_val = torchmetrics.Accuracy(
task="multiclass", num_classes=2
)
self.font_accur_test = torchmetrics.Accuracy(
task="multiclass", num_classes=config.FONT_COUNT
)
self.direction_accur_test = torchmetrics.Accuracy(
task="multiclass", num_classes=2
)
self.lr = lr
self.betas = betas
self.num_warmup_iters = num_warmup_iters
self.num_iters = num_iters
def forward(self, x):
return self.model(x)
def training_step(
self, batch: Tuple[torch.Tensor, torch.Tensor], batch_idx: int
) -> Dict[str, Any]:
X, y = batch
y_hat = self.forward(X)
loss = self.loss(y_hat, y)
self.log("train_loss", loss, prog_bar=True, sync_dist=True)
# accur
self.log(
"train_font_accur",
self.font_accur_train(y_hat[..., : config.FONT_COUNT], y[..., 0]),
sync_dist=True,
)
self.log(
"train_direction_accur",
self.direction_accur_train(
y_hat[..., config.FONT_COUNT : config.FONT_COUNT + 2], y[..., 1]
),
sync_dist=True,
)
return {"loss": loss}
def on_train_epoch_end(self) -> None:
self.log("train_font_accur", self.font_accur_train.compute(), sync_dist=True)
self.log(
"train_direction_accur", self.direction_accur_train.compute(), sync_dist=True
)
self.font_accur_train.reset()
self.direction_accur_train.reset()
def validation_step(
self, batch: Tuple[torch.Tensor, torch.Tensor], batch_idx: int
) -> Dict[str, Any]:
X, y = batch
y_hat = self.forward(X)
loss = self.loss(y_hat, y)
self.log("val_loss", loss, prog_bar=True, sync_dist=True)
self.font_accur_val.update(y_hat[..., : config.FONT_COUNT], y[..., 0])
self.direction_accur_val.update(
y_hat[..., config.FONT_COUNT : config.FONT_COUNT + 2], y[..., 1]
)
return {"loss": loss}
def on_validation_epoch_end(self):
self.log("val_font_accur", self.font_accur_val.compute(), sync_dist=True)
self.log(
"val_direction_accur", self.direction_accur_val.compute(), sync_dist=True
)
self.font_accur_val.reset()
self.direction_accur_val.reset()
def test_step(self, batch: Tuple[torch.Tensor, torch.Tensor], batch_idx: int):
X, y = batch
y_hat = self.forward(X)
loss = self.loss(y_hat, y)
self.log("test_loss", loss, prog_bar=True, sync_dist=True)
self.font_accur_test.update(y_hat[..., : config.FONT_COUNT], y[..., 0])
self.direction_accur_test.update(
y_hat[..., config.FONT_COUNT : config.FONT_COUNT + 2], y[..., 1]
)
return {"loss": loss}
def on_test_epoch_end(self) -> None:
self.log("test_font_accur", self.font_accur_test.compute(), sync_dist=True)
self.log(
"test_direction_accur", self.direction_accur_test.compute(), sync_dist=True
)
self.font_accur_test.reset()
self.direction_accur_test.reset()
def configure_optimizers(self):
optimizer = torch.optim.Adam(
self.model.parameters(), lr=self.lr, betas=self.betas
)
self.scheduler = CosineWarmupScheduler(
optimizer, self.num_warmup_iters, self.num_iters
)
return optimizer
def optimizer_step(
self,
epoch: int,
batch_idx: int,
optimizer,
optimizer_idx: int = 0,
*args,
**kwargs
):
super().optimizer_step(
epoch, batch_idx, optimizer, optimizer_idx, *args, **kwargs
)
self.log("lr", self.scheduler.get_last_lr()[0])
self.scheduler.step()
|