-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrainval.py
157 lines (142 loc) · 5.95 KB
/
trainval.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
import numpy as np
import torch
from torch import nn
import time
import os
from collections import OrderedDict
from torch.autograd import Variable
from matplotlib import pyplot as plt
import logging
class Trainer():
def __init__(self, model, loss, train_loader, val_loader, optimizer, args, scheme, save_dir):
self.model = model
self.loss = loss
self.valloss = {'L1': nn.L1Loss(), 'L2': nn.MSELoss()}
self.valloss = OrderedDict(sorted(self.valloss.items()))
self.train_loader = train_loader
self.val_loader = val_loader
self.optimizer = optimizer
self.args = args
self.scheme = scheme
self.save_dir = save_dir
self.logfile = os.path.join(self.save_dir,'log')
with open(self.logfile,'a') as f:
f.write('\n -------------------------')
f.write(str(args))
def get_lr(self, epoch):
if self.args.lr is None:
nodes = np.sort(np.array([n for n in self.scheme.keys()]))
id = np.sum(nodes<=epoch)-1
return self.scheme[nodes[id]]
else:
return self.args.lr
def train(self, epoch):
logging.info("train")
start_time = time.time()
lr = self.get_lr(epoch)
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr
self.model.train()
loss_hist = []
loss_sep_hist = []
for iter, batch in enumerate(self.train_loader):
logging.debug("iter:" + str(iter))
logging.debug("batch:" + str(batch))
batch = Variable(batch).cuda()
rec = self.model(batch)
l_sep, l = self.loss(rec, batch)
self.optimizer.zero_grad()
l.backward()
torch.nn.utils.clip_grad_norm(self.model.parameters(), 1.0)
self.optimizer.step()
loss_hist.append(l.data.cpu().numpy())
#print(loss_hist[-1])
l_sep = [li.data.cpu().numpy() for li in l_sep]
loss_sep_hist.append(l_sep)
logging.debug("for end")
if self.args.debug and iter ==4:
break
mean_loss = np.mean(loss_hist)
mean_loss_sep = np.mean(loss_sep_hist, 0)
dt = time.time()-start_time
info = 'Train Epoch %d, time %.1f, loss %.5f' %(epoch, dt, mean_loss)
for id, li in enumerate(mean_loss_sep):
info = info + ', lossid %d: %.5f' %(id, li)
info = info+' lr %.8f'%lr
print(info)
with open(self.logfile, 'a') as f:
f.write(info+'\n')
return mean_loss
def val(self, epoch):
start_time = time.time()
self.model.eval()
loss_hist = []
loss_sep_hist = []
self.valloss_hist = {k:[] for k in self.valloss.keys()}
for iter, batch in enumerate(self.val_loader):
batch = Variable(batch).cuda()
rec = self.model(batch)
l_sep, l = self.loss( rec, batch)
loss_hist.append(l.data.cpu().numpy())
l_sep = [li.data.cpu().numpy() for li in l_sep]
loss_sep_hist.append(l_sep)
rec = torch.clamp(rec,-1,1)
for key, lossfun in self.valloss.items():
l = lossfun(rec, batch)
self.valloss_hist[key].append(l.data.cpu().numpy())
if self.args.debug and iter ==4:
break
mean_loss = np.mean(loss_hist)
mean_loss_sep = np.mean(loss_sep_hist, 0)
dt = time.time()-start_time
info = 'Val Epoch %d, time %.1f, loss %.5f' %(epoch, dt, mean_loss)
for id, li in enumerate(mean_loss_sep):
info = info + ', lossid %d: %.5f' %(id, li)
for key, hist in self.valloss_hist.items():
info = info + ', Eval %s: %.5f' %(key, np.mean(hist))
print(info)
with open(self.logfile, 'a') as f:
f.writelines(info+'\n')
self.arithematic_coding(batch[0].data.cpu().numpy(), rec[0].data.cpu().numpy())
# im1 = batch[0].data.cpu().numpy()/2 +0.5
# im2 = rec[0].data.cpu().numpy()/2 + 0.5
# im2 = np.clip(im2,0,1)
# im3 = np.concatenate([im1, im2], 1).transpose([1,2,0])
# plt.imsave(os.path.join(self.save_dir, '%03d.png' % epoch), im3)
return mean_loss
def save_model(self, epoch):
try:
state_dict = self.model.module.state_dict()
except:
state_dict = self.model.state_dict()
for key in state_dict.keys():
state_dict[key] = state_dict[key].cpu()
torch.save({'state_dict': state_dict, 'args':self.args, 'scheme':self.scheme},
os.path.join(self.save_dir, '%03d.ckpt' % epoch))
def arithematic_coding(self, real, predict, minimun_error = 2 ** (-40)):
channel, height, width = real.shape
left_border = 0
right_border = 1
leftList = []
rightList = []
for h in range(height):
for w in range(width):
for c in range(channel):
if real[c, h, w] == 1:
right_border = (right_border - left_border) * predict[c, h, w] + left_border
elif real[c, h, w] == 0:
left_border = (right_border - left_border) * predict[c, h, w] + left_border
else:
print("error input not 0 or 1")
if right_border - left_border < minimun_error:
leftList.append(left_border)
rightList.append(right_border)
left_border = 0
right_border = 1
bitPerNum = - np.log(minimun_error) / np.log(2) + 2
total_size = len(leftList) * bitPerNum / 8
ratio = total_size / (channel * height * width / 8)
info = "total size: " + str(total_size) + '\n' + "ratio: " + str(ratio)
print(info)
with open(self.logfile, 'a') as f:
f.writelines(info+'\n')