-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
82 lines (62 loc) · 2.44 KB
/
models.py
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
import torch
import pytorch_lightning as pl
import torchvision
class Normalize(object):
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
self.mean = mean
self.std = std
def __call__(self, tensor):
"""
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
Returns:
Tensor: Normalized image.
"""
tensor = tensor.clone()
if len(tensor.shape) == 4:
for b in tensor:
for t, m, s in zip(b, self.mean, self.std):
t.sub_(m).div_(s)
elif len(tensor.shape) == 3:
for t, m, s in zip(tensor, self.mean, self.std):
t.sub_(m).div_(s)
# The normalize code -> t.sub_(m).div_(s)
return tensor
class ResNetGaussian(pl.LightningModule):
def __init__(self, lr = 0.01, output_dim=None, hidden_dim=None):
super().__init__()
self.encoder = torchvision.models.resnet18(pretrained=True)
self.encoder.fc = torch.nn.Linear(512, 256)
self.lin_out = torch.nn.Linear(256, output_dim)
self.normalize = Normalize()
self.lr = lr
def forward(self, x):
embedding = self.encoder(self.normalize(x)).relu()
y = self.lin_out(embedding)
return y
def training_step(self, batch, batch_idx):
image = batch['image']
label = batch['label']
output = self(image)
loss = torch.nn.functional.binary_cross_entropy_with_logits(output, label)
self.log("train_loss", loss)
return {'loss': loss}
def validation_step(self, batch, batch_idx):
image = batch['image']
label = batch['label']
output = self(image)
loss = torch.nn.functional.binary_cross_entropy_with_logits(output, label)
self.log("val_loss", loss)
return {"val_loss": loss}
def validation_end(self, outputs):
avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
self.log('avg_val_loss', avg_loss)
return {'avg_val_loss': avg_loss}
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)
return {"optimizer": optimizer,
"lr_scheduler": {
"scheduler": torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=2),
"monitor": "val_loss",
"frequency": 1
}}