-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.py
executable file
·51 lines (40 loc) · 1.27 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
import os
import csv
import random
import numpy as np
import torch
def to_cuda(sample):
sampleout = {}
for key, val in sample.items():
if isinstance(val, torch.Tensor):
sampleout[key] = val.cuda()
elif isinstance(val, list):
new_val = []
for e in val:
if isinstance(e, torch.Tensor):
new_val.append(e.cuda())
else:
new_val.append(val)
sampleout[key] = new_val
else:
sampleout[key] = val
return sampleout
def seed_all(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def new_log(folder_path, args=None):
os.makedirs(folder_path, exist_ok=True)
n_exp = len(os.listdir(folder_path))
experiment_folder = os.path.join(folder_path, f'experiment_{n_exp}')
os.mkdir(experiment_folder)
if args is not None:
args_dict = args.__dict__
write_params(args_dict, os.path.join(experiment_folder, 'args' + '.csv'))
return experiment_folder
def write_params(params, path):
with open(path, 'w') as fh:
writer = csv.writer(fh)
writer.writerow(['key', 'value'])
for data in params.items():
writer.writerow([el for el in data])