Skip to content

Instantly share code, notes, and snippets.

@kingjr
Last active March 31, 2021 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingjr/2f66c3b2f43653b80169df2e0e53a6c7 to your computer and use it in GitHub Desktop.
Save kingjr/2f66c3b2f43653b80169df2e0e53a6c7 to your computer and use it in GitHub Desktop.
2v2 gpu
class Time2v2():
def __init__(self, metric='cosine', scale=True, to=None):
self.metric = metric
self.to = to
self.scale = scale
def __call__(self, y_true, y_pred):
from torch.nn import CosineSimilarity
from numpy.random import permutation
# define permutations
assert len(y_true) == len(y_pred)
ns = len(y_true)
first = permutation(ns) # first group of TR
second = permutation(ns) # second group of TR
while (first == second).any(): # check that distinct TRs in pairs
first[first == second] = np.random.choice((first == second).sum())
# Prepare tensors
cos = CosineSimilarity(dim=1, eps=1e-08)
y_true = torch.tensor(y_true)
y_pred = torch.tensor(y_pred)
if torch.cuda.is_available() and self.to in (None, 'cuda'):
y_true = y_true.to('cuda')
y_pred = y_pred.to('cuda')
# scale
if self.scale:
y_true -= y_true.mean(0)
y_pred -= y_pred.mean(0)
y_true /= y_true.std(0)
y_pred /= y_pred.std(0)
# compute cosine distance across dim == 1
s1 = 1. - cos(y_true[first], y_pred[first])
s1 += 1. - cos(y_true[second], y_pred[second])
s2 = 1. - cos(y_true[first], y_pred[second])
s2 += 1. - cos(y_true[second], y_pred[first])
acc = (1.*(s1 < s2)).mean(0).cpu().numpy()
return acc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment