File size: 9,810 Bytes
d908fd7 754b856 12319ae 91867af 12319ae ba9c868 12319ae 754b856 d908fd7 754b856 d908fd7 91867af d908fd7 ba9c868 90cf80d d908fd7 754b856 d908fd7 754b856 d908fd7 754b856 d908fd7 754b856 d908fd7 754b856 d908fd7 754b856 d908fd7 754b856 d908fd7 754b856 d908fd7 a58327a d908fd7 754b856 d908fd7 |
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
from typing import Any, List
import torch
from torch import nn
from pytorch_lightning import LightningModule
from torchmetrics import MaxMetric, MeanAbsoluteError, MinMetric
from torchmetrics.classification.accuracy import Accuracy
class SimpleDenseNet(nn.Module):
def __init__(self, hparams: dict):
super().__init__()
self.model = nn.Sequential(
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
nn.BatchNorm1d(hparams["lin1_size"]),
nn.ReLU(),
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
nn.BatchNorm1d(hparams["lin2_size"]),
nn.ReLU(),
nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
nn.BatchNorm1d(hparams["lin3_size"]),
nn.ReLU(),
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
)
def forward(self, x):
batch_size, channels, width, height = x.size()
# (batch, 1, width, height) -> (batch, 1*width*height)
x = x.view(batch_size, -1)
return self.model(x)
class FocusLitModule(LightningModule):
"""
Example of LightningModule for MNIST classification.
A LightningModule organizes your PyTorch code into 5 sections:
- Computations (init).
- Train loop (training_step)
- Validation loop (validation_step)
- Test loop (test_step)
- Optimizers (configure_optimizers)
Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html
"""
def __init__(
self,
input_size: int = 75 * 75 * 3,
lin1_size: int = 256,
lin2_size: int = 256,
lin3_size: int = 256,
output_size: int = 1,
lr: float = 0.001,
weight_decay: float = 0.0005,
):
super().__init__()
# this line allows to access init params with 'self.hparams' attribute
# it also ensures init params will be stored in ckpt
self.save_hyperparameters(logger=False)
self.model = SimpleDenseNet(hparams=self.hparams)
# loss function
self.criterion = torch.nn.L1Loss()
# use separate metric instance for train, val and test step
# to ensure a proper reduction over the epoch
self.train_mae = MeanAbsoluteError()
self.val_mae = MeanAbsoluteError()
self.test_mae = MeanAbsoluteError()
# for logging best so far validation accuracy
self.val_mae_best = MinMetric()
def forward(self, x: torch.Tensor):
return self.model(x)
def step(self, batch: Any):
x = batch["image"]
y = batch["focus_height"]
logits = self.forward(x)
loss = self.criterion(logits, y.unsqueeze(1))
preds = torch.squeeze(logits)
return loss, preds, y
def training_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log train metrics
mae = self.train_mae(preds, targets)
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
self.log("train/mae", mae, on_step=False, on_epoch=True, prog_bar=True)
# we can return here dict with any tensors
# and then read it in some callback or in `training_epoch_end()`` below
# remember to always return loss from `training_step()` or else backpropagation will fail!
return {"loss": loss, "preds": preds, "targets": targets}
def training_epoch_end(self, outputs: List[Any]):
# `outputs` is a list of dicts returned from `training_step()`
pass
def validation_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log val metrics
mae = self.val_mae(preds, targets)
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
self.log("val/mae", mae, on_step=False, on_epoch=True, prog_bar=True)
return {"loss": loss, "preds": preds, "targets": targets}
def validation_epoch_end(self, outputs: List[Any]):
mae = self.val_mae.compute() # get val accuracy from current epoch
self.val_mae_best.update(mae)
self.log(
"val/mae_best", self.val_mae_best.compute(), on_epoch=True, prog_bar=True
)
def test_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log test metrics
mae = self.test_mae(preds, targets)
self.log("test/loss", loss, on_step=False, on_epoch=True)
self.log("test/mae", mae, on_step=False, on_epoch=True)
return {"loss": loss, "preds": preds, "targets": targets}
def test_epoch_end(self, outputs: List[Any]):
print(outputs)
pass
def on_epoch_end(self):
# reset metrics at the end of every epoch
self.train_mae.reset()
self.test_mae.reset()
self.val_mae.reset()
def configure_optimizers(self):
"""Choose what optimizers and learning-rate schedulers.
Normally you'd need one. But in the case of GANs or similar you might have multiple.
See examples here:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
"""
return torch.optim.Adam(
params=self.parameters(),
lr=self.hparams.lr,
weight_decay=self.hparams.weight_decay,
)
class FocusMSELitModule(LightningModule):
"""
Example of LightningModule for MNIST classification.
A LightningModule organizes your PyTorch code into 5 sections:
- Computations (init).
- Train loop (training_step)
- Validation loop (validation_step)
- Test loop (test_step)
- Optimizers (configure_optimizers)
Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html
"""
def __init__(
self,
input_size: int = 75 * 75 * 3,
lin1_size: int = 256,
lin2_size: int = 256,
lin3_size: int = 256,
output_size: int = 1,
lr: float = 0.001,
weight_decay: float = 0.0005,
):
super().__init__()
# this line allows to access init params with 'self.hparams' attribute
# it also ensures init params will be stored in ckpt
self.save_hyperparameters(logger=False)
self.model = SimpleDenseNet(hparams=self.hparams)
# loss function
self.criterion = torch.nn.MSELoss()
# use separate metric instance for train, val and test step
# to ensure a proper reduction over the epoch
self.train_mae = MeanAbsoluteError()
self.val_mae = MeanAbsoluteError()
self.test_mae = MeanAbsoluteError()
# for logging best so far validation accuracy
self.val_mae_best = MinMetric()
def forward(self, x: torch.Tensor):
return self.model(x)
def step(self, batch: Any):
x = batch["image"]
y = batch["focus_height"]
logits = self.forward(x)
loss = self.criterion(logits, y.unsqueeze(1))
preds = torch.squeeze(logits)
return loss, preds, y
def training_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log train metrics
mae = self.train_mae(preds, targets)
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
self.log("train/mae", mae, on_step=False, on_epoch=True, prog_bar=True)
# we can return here dict with any tensors
# and then read it in some callback or in `training_epoch_end()`` below
# remember to always return loss from `training_step()` or else backpropagation will fail!
return {"loss": loss, "preds": preds, "targets": targets}
def training_epoch_end(self, outputs: List[Any]):
# `outputs` is a list of dicts returned from `training_step()`
pass
def validation_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log val metrics
mae = self.val_mae(preds, targets)
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
self.log("val/mae", mae, on_step=False, on_epoch=True, prog_bar=True)
return {"loss": loss, "preds": preds, "targets": targets}
def validation_epoch_end(self, outputs: List[Any]):
mae = self.val_mae.compute() # get val accuracy from current epoch
self.val_mae_best.update(mae)
self.log(
"val/mae_best", self.val_mae_best.compute(), on_epoch=True, prog_bar=True
)
def test_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log test metrics
mae = self.test_mae(preds, targets)
self.log("test/loss", loss, on_step=False, on_epoch=True)
self.log("test/mae", mae, on_step=False, on_epoch=True)
return {"loss": loss, "preds": preds, "targets": targets}
def test_epoch_end(self, outputs: List[Any]):
print(outputs)
pass
def on_epoch_end(self):
# reset metrics at the end of every epoch
self.train_mae.reset()
self.test_mae.reset()
self.val_mae.reset()
def configure_optimizers(self):
"""Choose what optimizers and learning-rate schedulers.
Normally you'd need one. But in the case of GANs or similar you might have multiple.
See examples here:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
"""
return torch.optim.Adam(
params=self.parameters(),
lr=self.hparams.lr,
weight_decay=self.hparams.weight_decay,
)
|