-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
54 lines (43 loc) · 1.35 KB
/
train.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
import matplotlib.pyplot as plt
import torch
import torchvision
from downsample import downsample
from model import Loss
from utils import Timer
def train(net, lr, num_epochs, device, img):
net = net.to(device)
optimizer = torch.optim.AdamW(net.parameters(), lr=lr)
loss = Loss()
timer = Timer()
img = img.to(device)
down1, down2 = downsample(img)
down1.to(device)
down2.to(device)
loss_list = []
epoch_list = []
for epoch in range(num_epochs):
timer.start()
optimizer.zero_grad()
down1_dst = net(down1)
down2_dst = net(down2)
dst = net(img)
l = loss(down1, down2, dst, down1_dst, down2_dst)
l.backward()
optimizer.step()
loss_list.append(l.detach().to(torch.device('cpu')))
epoch_list.append(epoch + 1)
timer.stop()
with open('train_datas.log', 'a+') as f:
f.write(f'loss {loss_list[-1]:.3f}\n')
f.write(f'{num_epochs / timer.sum():.1f} examples/sec 'f'on {str(device)}\n')
plt.plot(epoch_list, loss_list, label=u"loss")
plt.show()
def predict(net, img, device):
img = img.to(device)
res = net(img)
trans = torchvision.transforms.ToPILImage()
image = trans(res)
if image.mode == 'RGBA':
image = image.convert('RGB')
image.save('pictures/result.jpg')
image.show()