forked from hellozhuo/pidinet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
159 lines (123 loc) · 4.35 KB
/
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
"""
Utility functions for training
Author: Zhuo Su, Wenzhe Liu
Date: Aug 22, 2020
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import os
import shutil
import math
import time
import random
import skimage
import numpy as np
from skimage import io
from skimage.transform import resize
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
######################################
# measurement functions #
######################################
def get_model_parm_nums(model):
total = sum([param.numel() for param in model.parameters()])
total = float(total) / 1e6
return total
######################################
# basic functions #
######################################
def load_checkpoint(args, running_file):
model_dir = os.path.join(args.savedir, 'save_models')
latest_filename = os.path.join(model_dir, 'latest.txt')
model_filename = ''
if args.evaluate is not None:
model_filename = args.evaluate
else:
if os.path.exists(latest_filename):
with open(latest_filename, 'r') as fin:
model_filename = fin.readlines()[0].strip()
loadinfo = "=> loading checkpoint from '{}'".format(model_filename)
print(loadinfo)
state = None
if os.path.exists(model_filename):
state = torch.load(model_filename, map_location='cpu')
loadinfo2 = "=> loaded checkpoint '{}' successfully".format(model_filename)
else:
loadinfo2 = "no checkpoint loaded"
print(loadinfo2)
running_file.write('%s\n%s\n' % (loadinfo, loadinfo2))
running_file.flush()
return state
def save_checkpoint(state, epoch, root, saveID, keep_freq=10):
filename = 'checkpoint_%03d.pth' % epoch
model_dir = os.path.join(root, 'save_models')
model_filename = os.path.join(model_dir, filename)
latest_filename = os.path.join(model_dir, 'latest.txt')
if not os.path.exists(model_dir):
os.makedirs(model_dir)
# write new checkpoint
torch.save(state, model_filename)
with open(latest_filename, 'w') as fout:
fout.write(model_filename)
print("=> saved checkpoint '{}'".format(model_filename))
# remove old model
if saveID is not None and (saveID + 1) % keep_freq != 0:
filename = 'checkpoint_%03d.pth' % saveID
model_filename = os.path.join(model_dir, filename)
if os.path.exists(model_filename):
os.remove(model_filename)
print('=> removed checkpoint %s' % model_filename)
print('##########Time##########', time.strftime('%Y-%m-%d %H:%M:%S'))
return epoch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
#self.sum += val * n
self.sum += val
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch, args):
method = args.lr_type
if method == 'cosine':
T_total = float(args.epochs)
T_cur = float(epoch)
lr = 0.5 * args.lr * (1 + math.cos(math.pi * T_cur / T_total))
elif method == 'multistep':
lr = args.lr
for epoch_step in args.lr_steps:
if epoch >= epoch_step:
lr = lr * 0.1
for param_group in optimizer.param_groups:
param_group['lr'] = lr
str_lr = '%.6f' % lr
return str_lr
######################################
# edge specific functions #
######################################
def cross_entropy_loss_RCF(prediction, labelf, beta):
label = labelf.long()
mask = labelf.clone()
num_positive = torch.sum(label==1).float()
num_negative = torch.sum(label==0).float()
mask[label == 1] = 1.0 * num_negative / (num_positive + num_negative)
mask[label == 0] = beta * num_positive / (num_positive + num_negative)
mask[label == 2] = 0
cost = F.binary_cross_entropy(
prediction, labelf, weight=mask, reduction='sum')
return cost
######################################
# debug functions #
######################################
# no function currently