-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelper.py
36 lines (28 loc) · 996 Bytes
/
helper.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
import numpy as np
import os
import torch
def ensure_dir(file_path):
'''
Used to ensure to create the a directory when needed
:param file_path: path to the file that we want to create
'''
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
return file_path
def safemean(xs):
return np.nan if len(xs) == 0 else np.mean(xs)
def explained_variance(ypred, y):
"""
Computes fraction of variance that ypred explains about y.
Returns 1 - Var[y-ypred] / Var[y]
interpretation:
ev=0 => might as well have predicted zero
ev=1 => perfect prediction
ev<0 => worse than just predicting zero
"""
assert y.ndim == 1 and ypred.ndim == 1
vary = np.var(y)
return np.nan if vary==0 else 1 - np.var(y-ypred)/vary
def save_checkpoint(state, path, filename='checkpoint.pth.tar', version=0):
torch.save(state, ensure_dir(os.path.join(path, version, filename)))