-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathutils.py
79 lines (58 loc) · 2.52 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
import os
import codecs
import torch
import numpy as np
from functools import reduce
import operator
def describe(t): # t could be numpy or torch tensor.
t = t.data if isinstance(t, torch.autograd.Variable) else t
s = '{:17s} {:8s} [{:.4f} , {:.4f}] m+-s = {:.4f} +- {:.4f}'
ttype = 'np.{}'.format(t.dtype) if type(t) == np.ndarray else str(t.type()).replace('ensor', '')
si = 'x'.join(map(str, t.shape if isinstance(t, np.ndarray) else t.size()))
return s.format(ttype, si, t.min(), t.max(), t.mean(), t.std())
def write_gen_samples(samples, fn, c_lab=None):
""" samples: list of strings. c_lab (optional): tensor of same size. """
fn_dir = os.path.dirname(fn)
if not os.path.exists(fn_dir):
os.makedirs(fn_dir)
size = len(samples)
with open(fn, 'w+') as f:
if c_lab is not None:
print("Saving %d samples with labels" % size)
assert c_lab.nelement() == size, 'sizes dont match'
f.writelines(['label: {}\n{}\n'.format(y, s) for y, s in zip(c_lab, samples)])
else:
print("Saving %d samples without labels" % size)
f.write('\n'.join(samples) + '\n')
def write_interpsamples(samples, fn, c_lab=False):
raise Exception('Reimplement this function like write_gen_samples(), use minibatch')
def write_samezsamples(samples, samples2, fn, fn2, lab=False):
raise Exception('Reimplement this function like write_gen_samples(), use minibatch')
def save_vocab(vocab, fn):
check_dir_exists(fn)
with codecs.open(fn, "w", "utf-8") as f:
for word, ix in vocab.stoi.items():
f.write(word + " " + str(ix) + "\n")
print('Saved vocab to ' + fn)
# Linearly interpolate between start and end val depending on current iteration
def interpolate(start_val, end_val, start_iter, end_iter, current_iter):
if current_iter < start_iter:
return start_val
elif current_iter >= end_iter:
return end_val
else:
return start_val + (end_val - start_val) * (current_iter - start_iter) / (end_iter - start_iter)
def anneal(cfgan, it):
return interpolate(cfgan.start.val, cfgan.end.val, cfgan.start.iter, cfgan.end.iter, it)
def check_dir_exists(fn):
fn_dir = os.path.dirname(fn)
if not os.path.exists(fn_dir):
os.makedirs(fn_dir)
def prod(iterable):
return reduce(operator.mul, iterable, 1)
def scale_and_clamp(dist, w, clamp_val=None):
rescaled = dist * w # w = 1/scale
if clamp_val and rescaled > clamp_val:
return clamp_val
else:
return rescaled