-
Notifications
You must be signed in to change notification settings - Fork 1
/
unet.py
154 lines (116 loc) · 4.67 KB
/
unet.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
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
import albumentations
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torchvision
import torchvision.models
import pytorch_lightning as pl
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
from src.dataset import DroneDeployDataset
def swish(input):
return input * torch.sigmoid(input)
class Swish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
return swish(input)
def dconv(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size = 3, padding = 1),
nn.ReLU(inplace =True),
#Swish(),
nn.Conv2d(out_channels, out_channels, kernel_size = 3, padding = 1),
nn.ReLU(inplace = True)
#Swish(),
)
class LightningUNet(pl.LightningModule):
def __init__(self, n_class):
super().__init__()
self.n_class = n_class
self.dconv1 = dconv(3, 64)
self.dconv2 = dconv(64, 128)
self.dconv3 = dconv(128, 256)
self.dconv4 = dconv(256, 512)
self.maxpool = nn.MaxPool2d(2)
self.upsample = nn.Upsample(scale_factor = 2, mode = 'bilinear', align_corners=True)
self.uconv3 = dconv(256 + 512, 256)
self.uconv2 = dconv(128 + 256, 128)
self.uconv1 = dconv(64 + 128, 64)
self.lconv = nn.Conv2d(64, self.n_class, kernel_size = 1)
def forward(self, x):
conv1 = self.dconv1(x)
x = self.maxpool(conv1)
conv2 = self.dconv2(x)
x = self.maxpool(conv2)
conv3 = self.dconv3(x)
x = self.maxpool(conv3)
x = self.dconv4(x)
x = self.upsample(x)
x = torch.cat([x, conv3], dim = 1)
x = self.uconv3(x)
x = self.upsample(x)
x = torch.cat([x, conv2], dim =1)
x = self.uconv2(x)
x = self.upsample(x)
x = torch.cat([x, conv1], dim =1)
x = self.uconv1(x)
out = self.lconv(x)
return out
def loss(self, logits, y):
return nn.CrossEntropyLoss()(logits, y)
def training_step(self, train_batch, batch_idx):
x = train_batch['features'].to(device='cuda', dtype = torch.float32)
y = train_batch['masks'].to(device='cuda', dtype = torch.long)
logits = self.forward(x)
tr_loss = self.loss(logits, y[:, :, :, 0])
return {'loss' : tr_loss}
def validation_step(self, val_batch, val_idx):
x_val = val_batch['features'].to(device='cuda', dtype = torch.float32)
y_val = val_batch['masks'].to(device='cuda', dtype = torch.long)
val_logits = self.forward(x_val)
val_loss = self.loss(val_logits, y_val[:, :, :, 0])
return {'val_loss' : val_loss}
def validation_epoch_end(self, outputs):
val_los_mean = torch.stack([x['val_loss'] for x in outputs]).mean()
return {'val_loss' : val_loss_mean}
def validation_end(self, outputs):
val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean()
return {'val_loss' : val_loss_mean}
def get_samples(self):
label_chips = os.listdir('dataset-medium/label-chips/')
image_chips = os.listdir('dataset-medium/image-chips/')
samples = [(os.path.join('dataset-medium/image-chips',x), os.path.join('dataset-medium/label-chips/', y) ) for (x, y) in zip(label_chips, image_chips)]
return samples
def prepare_data(self):
samples = self.get_samples()
dataset = DroneDeployDataset(samples = samples, transform = albumentations.Compose([ albumentations.LongestMaxSize(max_size = 768, p=1)], p=1))
self.train_data, self.val_data = torch.utils.data.random_split(dataset, [len(dataset) -50, 50])
def train_dataloader(self):
return DataLoader(self.train_data, batch_size = 1)
def val_dataloader(self):
return DataLoader(self.val_data, shuffle = False, batch_size = 1)
#def test_dataloader(self):
# return DataLoader(self.test_data, batch_size = 32)
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr = 1e-4)
return optimizer
def main():
model = LightningUNet(n_class = 6)
os.makedirs('results', exist_ok=True)
checkpoint_callback = ModelCheckpoint(
filepath = "results",
verbose = True,
monitor = "val_loss",
mode = "min",
prefix = "",
)
trainer = pl.Trainer(gpus=1, default_save_path='results',
max_epochs = 100,
checkpoint_callback=checkpoint_callback,
show_progress_bar=True,
)
trainer.fit(model)
if __name__ == "__main__":
main()