-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
182 lines (162 loc) · 6.71 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import numpy as np
import os
import matplotlib.pyplot as plt
import torchvision
import torch
from datasets import *
from vae import VAE
from liu_vae import VAE_LIU
import time
import re
import argparse
import matplotlib
matplotlib.use('Agg')
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--params_id", default=100)
parser.add_argument("--img_size", default=512, type=int)
parser.add_argument("--batch_size", default=16, type=int)
parser.add_argument("--batch_size_test", default=8, type=int)
parser.add_argument("--num_epochs", default=2000, type=int)
parser.add_argument("--latent_img_size", default=32, type=int)
parser.add_argument("--z_dim", default=32, type=int)
parser.add_argument("--lr", default=1e-4, type=float)
parser.add_argument("--beta", default=0.1, type=float)
parser.add_argument("--delta", default=1.0, type=float) # new_param
parser.add_argument("--exp", default=time.strftime("%Y%m%d-%H%M%S"))
parser.add_argument("--dataset", default="panoptics")
parser.add_argument("--category", default='all')
parser.add_argument("--defect", default=None)
parser.add_argument(
"--defect_list",
type=lambda s: [item for item in s.split(',')]
)
parser.add_argument("--nb_channels", default=3, type=int)
parser.add_argument("--force_train", dest='force_train', action='store_true')
parser.set_defaults(force_train=False)
parser.add_argument("--force_cpu", dest='force_cpu', action='store_true')
parser.add_argument("--dst_dir", type=str, default=os.getcwd())
parser.add_argument("--data_dir", type=str, default="/home/getch/DATA/VAE/data",required=False)
parser.add_argument("--ndvi", dest="ndvi", action='store_true', default=False)
parser.set_defaults(ndvi=False)
parser.add_argument("--anomaly", help='anomaly score map approach, could be either of "ssim" or "ssim_mad" ', type=str, default='ssim')
parser.add_argument("--blur", dest='blur', help='Whether to blur an image', default=False, action='store_true')
parser.set_defaults(blur=False)
parser.add_argument("--scale", help='Scale factor to downscale the image to coarser resolution', type=int, default=16)
parser.add_argument("--liu_vae", help='Whether to use Liu VAE implementation approach', dest='liu_vae', action='store_true')
parser.set_defaults(liu_vae=False) # conv_layers
parser.add_argument("--disc_module", help='Whether to use disc_module for liu_vae', dest='disc_module', action='store_true')
parser.set_defaults(disc_module=False) # conv_layers
parser.add_argument('--conv_layers', type=lambda s: re.split(',', s), help='list of convlayers for liu_vae implementation attanetion map generation', required=False, default="conv_1,conv_2,conv_3,conv4")
return parser.parse_args()
def load_vae(args):
if not args.liu_vae:
model = VAE(
latent_img_size=args.latent_img_size,
z_dim=args.z_dim,
img_size=args.img_size,
nb_channels=args.nb_channels,
beta=args.beta,)
else:
model = VAE_LIU(
latent_img_size=args.latent_img_size,
z_dim=args.z_dim,
img_size=args.img_size,
nb_channels=args.nb_channels,
beta=args.beta,
delta=args.delta,
liu_vae=args.liu_vae,
disc_module=args.disc_module)
print('Liu et al anomaly attention based VAE model initiated')
return model
def load_model_parameters(model, file_name, dir1, dir2, device):
print(f"Trying to load: {file_name}")
try:
state_dict = torch.load(
os.path.join(dir1, file_name),
map_location=device
)
except FileNotFoundError:
state_dict = torch.load(
os.path.join(dir2, file_name),
map_location=device
)
model.load_state_dict(state_dict, strict=False)
print(f"{file_name} loaded !")
return model
def get_train_dataloader(args):
if args.dataset == "panoptics":
train_dataset = PanopticsTrainDataset(
args.category,
args.img_size,
)
else:
raise RuntimeError("No / Wrong dataset provided")
train_dataloader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=False if args.dataset == "ssl_vqvae" else True,
num_workers=12
)
return train_dataloader, train_dataset
def get_test_dataloader(args, with_loc=False, categ='all',
fake_dataset_size=None): # categ=None is added
if args.dataset == "panoptics":
test_dataset = PanopticsTestDataset(
args.img_size,
category=categ,
fake_dataset_size=fake_dataset_size
)
else:
raise RuntimeError("No / Wrong dataset provided")
test_dataloader = DataLoader(
test_dataset,
batch_size=args.batch_size_test,
num_workers=12
)
return test_dataloader, test_dataset
def tensor_img_to_01(t, share_B=False):
''' t is a BxCxHxW tensor, put its values in [0, 1] for each batch element
if share_B is False otherwise normalization include all batch elements
'''
t = torch.nan_to_num(t)
if share_B:
t = ((t - torch.amin(t, dim=(0, 1, 2, 3), keepdim=True)) /
(torch.amax(t, dim=(0, 1, 2, 3), keepdim=True) - torch.amin(t,
dim=(0, 1, 2,3),
keepdim=True)))
if not share_B:
t = ((t - torch.amin(t, dim=(1, 2, 3), keepdim=True)) /
(torch.amax(t, dim=(1, 2, 3), keepdim=True) - torch.amin(t, dim=(1, 2,3),
keepdim=True)))
return t
def update_loss_dict(ld_old, ld_new):
for k, v in ld_new.items():
if k in ld_old:
ld_old[k] += v
else:
ld_old[k] = v
return ld_old
def print_loss_logs(f_name, out_dir, loss_dict, epoch, exp_name):
if epoch == 0:
with open(f_name, "w") as f:
print("epoch,", end="", file=f)
for k, v in loss_dict.items():
print(f"{k},", end="", file=f)
print("\n", end="", file=f)
# then, at every epoch
with open(f_name, "a") as f:
print(f"{epoch + 1},", end="", file=f)
for k, v in loss_dict.items():
print(f"{v},", end="", file=f)
print("\n", end="", file=f)
if (epoch + 1) % 50 == 0 or epoch in [4, 9, 24]:
# with this delimiter one spare column will be detected
arr = np.genfromtxt(f_name, names=True, delimiter=",")
fig, axis = plt.subplots(1)
for i, col in enumerate(arr.dtype.names[1:-1]):
axis.plot(arr[arr.dtype.names[0]], arr[col], label=col)
axis.legend()
fig.savefig(os.path.join(out_dir,
f"{exp_name}_loss_{epoch + 1}.png"))
plt.close(fig)