-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmakemodel.py
105 lines (81 loc) · 2.8 KB
/
makemodel.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
import os
from models import *
class GlomNet():
def __init__(self, isTrain, isContinue, savedir, loadpath = "", modelname = "UNet"):
self.gpuid = 0
self.isTrain = isTrain
self.isContinue = isContinue
self.save_dir = savedir
self.model_name = modelname
self.lr = 1e-3
if(torch.cuda.is_available()):
print(torch.cuda.get_device_properties(self.gpuid))
torch.cuda.set_device(self.gpuid)
self.device = torch.device(f'cuda:{self.gpuid}')
else:
self.device = torch.device(f'cpu')
self.model = self.define_net(modelname)
if (not self.isTrain) or (self.isContinue) :
self.load_networks(loadpath)
if not self.isTrain:
self.model.eval() #deactive bn/drop
if self.isTrain:
self.criterion = nn.CrossEntropyLoss(reduction='none')
self.optim = torch.optim.Adam(self.model.parameters(),lr = self.lr)
def get_device(self):
return self.device
#define which network to use
def define_net(self,modelname):
net = None
print('[CREATE] MODEL')
if(modelname=="UNet"):
net = UNet(pretrained=False)
if(modelname=="Deeplab"):
net = Deeplab(pretrained=False).get_model()
print(modelname)
print(net)
return net.to(self.device)
#load models from the disk
def load_networks(self, load_filename):
load_path = os.path.join(self.save_dir, load_filename)
checkpoint = torch.load(load_path, map_location=str(self.device))
self.model.load_state_dict(checkpoint["model_dict"])
print("[LOADED] MODEL")
def save_networks(self,model_dir,epoch):
save_path = os.path.join(self.save_dir, model_dir)
state = {'epoch': epoch + 1,
'modelname': self.model_name,
'model_dict': self.model.state_dict(),
'optim_dict': self.optim.state_dict(),
}
torch.save(state, save_path)
def set_input(self, X, Y):
self.X = X.to(self.device) # [Nbatch, 3, H, W]
self.Y = Y.type('torch.LongTensor').to(self.device) # [Nbatch, H, W] with class indices (0, 1)
def update_lr(self):
self.model.train()
self.lr = self.lr/10
self.optim = torch.optim.Adam(self.model.parameters(),lr = self.lr)
print("update lr to {}".format(self.lr))
def set_train(self):
self.model.train()
def set_eval(self):
self.model.eval()
def forward(self):
self.pred = self.model(self.X) # [N, Nclass, H, W]
def backward(self):
self.optim.zero_grad()
self.loss = self.criterion(self.pred,self.Y).mean() # for one batch
self.loss.backward()
self.optim.step()
def get_loss(self):
return self.loss
def get_pred(self):
return self.pred
def validate(self):
with torch.no_grad():
self.forward()
self.loss = self.criterion(self.pred,self.Y).mean()
def test(self):
with torch.no_grad():
self.forward()