-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlsb_utils.py
202 lines (167 loc) · 5.64 KB
/
lsb_utils.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
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
import albumentations
import os
import yaml
import cirrus
import torch
import torch.nn as nn
from cirrus.data import (
CirrusDataset,
LSBDataset,
LSBInstanceDataset,
)
from quicktorch.modules.loss import (
PlainConsensusLossMC,
ConsensusLossMC,
SuperMajorityConsensusLossMC,
)
from quicktorch.metrics import (
SegmentationTracker,
MCMLSegmentationTracker
)
from quicktorch.modules.attention.loss import (
DAFConsensusLoss,
FocalWithLogitsLoss,
GuidedAuxLoss,
)
from quicktorch.modules.attention.models import AttModel
from quicktorch.modules.attention.metrics import DAFMetric
datasets = {
'cirrus': {
'class': CirrusDataset,
'images': "E:/MATLAS Data/FITS/matlas",
'annotations': "E:/MATLAS Data/cirrus_annotations",
},
'lsb': {
'class': LSBDataset,
'images': "E:/MATLAS Data/np_surveys/cirrus",
'annotations': "E:/MATLAS Data/annotations/consensus",
},
'instance': {
'class': LSBInstanceDataset,
'images': "../im_tr",
'annotations': "../lab_tr",
},
}
def construct_dataset(dataset='instance', transform=None, idxs=None, bands=['g', 'r'], class_map='basicshells', aug_mult=1, padding=0):
Dataset = datasets[dataset]['class']
if transform is not None:
transform = get_transform(transform)
return Dataset(
datasets[dataset]['images'],
datasets[dataset]['annotations'],
bands=bands,
class_map=class_map,
indices=idxs,
aug_mult=aug_mult,
transform=transform,
padding=padding,
)
def get_transform(transforms):
def parse_args(args):
pos_args = []
kwargs = {}
if type(args) is list:
pos_args += args
if type(args) is dict:
kwargs.update(args)
return pos_args, kwargs
transforms = [TRANSFORMS[t](*parse_args(args)[0], **parse_args(args)[1]) for t, args in transforms.items()]
return albumentations.Compose(transforms)
# Some gross patching to prevent albumentations clipping image
def apply(self, img, gauss=None, **params):
img = img.astype("float32")
return img + gauss
albumentations.GaussNoise.apply = apply
TRANSFORMS = {
'crop': albumentations.RandomCrop,
'resize': albumentations.Resize,
'pad': albumentations.PadIfNeeded,
'flip': albumentations.Flip,
'rotate': albumentations.RandomRotate90,
'noise': albumentations.GaussNoise,
'affine': albumentations.Affine,
'contrast': albumentations.RandomContrast
}
def lsb_datasets(class_map, dataset='instance'):
# split the dataset in train and test set
dataset = construct_dataset(dataset=dataset, class_map=class_map)
N = len(dataset)
test_p = .85
val_p = .7
indices = torch.randperm(int(N * test_p)).tolist()
test_indices = torch.arange(int(N * test_p), N).tolist()
# define transform
transform = get_transform(['flip', 'rotate', 'noise'])
print(transform)
# get datasets
dataset_train = construct_dataset(idxs=indices[:int(N * val_p)], class_map=class_map, transform=transform, aug_mult=4)
dataset_val = construct_dataset(idxs=indices[int(N * val_p):int(N * test_p)], class_map=class_map, transform=transform)
dataset_test = construct_dataset(idxs=test_indices, class_map=class_map)
return dataset_train, dataset_val, dataset_test
def load_config(config_path, default_config_path=None, default=False):
if default_config_path is not None:
config = load_config(default_config_path, default=True)
else:
config = {}
with open(config_path, "r") as stream:
try:
config.update(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
if not default:
if 'name' not in config:
config['name'] = os.path.split(config_path)[-1][:-5]
return config
def remove_dims(a):
if a.ndim > 0:
if a.size(0) == 1:
return remove_dims(a.squeeze(0))
return a
def get_loss(seg_loss, consensus_loss, aux_loss=None, pos_weight=torch.tensor(1)):
pos_weight = remove_dims(pos_weight)
print(f'{pos_weight=}')
seg_loss = seg_losses[seg_loss](reduction='none', pos_weight=pos_weight)
consensus_loss = consensus_losses[consensus_loss](seg_criterion=seg_loss)
if aux_loss is None:
return consensus_loss
aux_loss = aux_losses[aux_loss]()
return DAFConsensusLoss(consensus_criterion=consensus_loss, aux_loss=aux_loss)
seg_losses = {
'bce': nn.BCEWithLogitsLoss,
'focal': FocalWithLogitsLoss,
}
consensus_losses = {
'plain': PlainConsensusLossMC,
'rcf': ConsensusLossMC,
'super': SuperMajorityConsensusLossMC,
}
aux_losses = {
'guided': GuidedAuxLoss
}
def get_metrics(n_classes, model_variant=""):
if 'Attention' in model_variant:
metrics_class = DAFMetric(full_metrics=True, n_classes=n_classes)
else:
if n_classes > 1:
metrics_class = MCMLSegmentationTracker(full_metrics=True, n_classes=n_classes)
else:
metrics_class = SegmentationTracker(full_metrics=True)
return metrics_class
def get_scale(scale_key, n_channels):
if scale_key is not None:
scale = cirrus.scale.get_scale(scale_key)(n_channels)
n_scaling = scale.n_scaling
else:
scale = None
n_scaling = 1
return scale, n_scaling
def create_attention_model(n_channels, n_classes, model_config, pad_to_remove=0):
scale, n_scaling = get_scale(model_config['scale_key'], n_channels)
model = AttModel(
n_channels=n_channels * n_scaling,
n_classes=n_classes,
scale=scale,
pad_to_remove=pad_to_remove,
**model_config
)
return model