-
Notifications
You must be signed in to change notification settings - Fork 59
/
models.py
77 lines (71 loc) · 2.46 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
import segmentation_models_pytorch as smp
import torch
class Segmentor:
def __init__(self, args):
# create segmentation model with pretrained encoder
if args.decoder == "fpn":
self.model = smp.FPN(
encoder_name=args.encoder,
encoder_weights=args.encoder_weights,
classes=len(args.classes),
activation=args.activation,
)
elif args.decoder == "unet":
self.model = smp.Unet(
encoder_name=args.encoder,
encoder_weights=args.encoder_weights,
classes=len(args.classes),
activation=args.activation,
)
elif args.decoder == "deeplabv3":
self.model = smp.DeepLabV3(
encoder_name=args.encoder,
encoder_weights=args.encoder_weights,
classes=len(args.classes),
activation=args.activation,
)
else:
self.model = smp.PSPNet(
encoder_name=args.encoder,
encoder_weights=args.encoder_weights,
classes=len(args.classes),
activation=args.activation,
)
self.preprocessing_fn = smp.encoders.get_preprocessing_fn(args.encoder, args.encoder_weights)
self.loss = smp.utils.losses.DiceLoss()
self.metrics = [
smp.utils.metrics.IoU(threshold=0.5),
smp.utils.metrics.Accuracy(threshold=0.5),
smp.utils.metrics.Precision(),
smp.utils.metrics.Recall(),
]
self.optimizer = torch.optim.Adam(
[
dict(params=self.model.parameters(), lr=0.0001),
]
)
self.train_epoch = smp.utils.train.TrainEpoch(
self.model,
loss=self.loss,
metrics=self.metrics,
optimizer=self.optimizer,
device=args.device,
verbose=True,
)
# return train_epoch
self.valid_epoch = smp.utils.train.ValidEpoch(
self.model,
loss=self.loss,
metrics=self.metrics,
device=args.device,
verbose=True,
)
def test_model(self, path):
self.test_model = smp.utils.train.ValidEpoch(
torch.load(path),
loss=self.loss,
metrics=self.metrics,
device="cuda",
verbose=True,
)
self.model = torch.load(path)