-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathutils.py
More file actions
65 lines (45 loc) · 1.55 KB
/
utils.py
File metadata and controls
65 lines (45 loc) · 1.55 KB
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
import math
import time
import numpy as np
import torch
def cos_np(data1, data2):
"""numpy implementation of cosine similarity for matrix"""
dotted = np.dot(data1, np.transpose(data2))
norm1 = np.linalg.norm(data1, axis=1)
norm2 = np.linalg.norm(data2, axis=1)
matrix_vector_norms = np.multiply(norm1, norm2)
neighbors = np.divide(dotted, matrix_vector_norms)
return neighbors
def normalize(data):
"""normalize matrix by rows"""
normalized_data = data / np.linalg.norm(data, axis=1).reshape((data.shape[0], 1))
return normalized_data
def dot_np(data1, data2):
"""cosine similarity for normalized vectors"""
return np.dot(data1, np.transpose(data2))
#######################################################################
def asMinutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%d:%d' % (m, s)
def timeSince(since, percent):
now = time.time()
s = now - since
es = s / (percent)
rs = es - s
return '%s<%s' % (asMinutes(s), asMinutes(rs))
#######################################################################
def sent2indexes(sentence, vocab):
'''sentence: a string
return: a numpy array of word indices
'''
return np.array([vocab[word] for word in sentence.strip().split(' ')])
########################################################################
use_cuda = torch.cuda.is_available()
def gVar(data):
tensor = data
if isinstance(data, np.ndarray):
tensor = torch.from_numpy(data)
if use_cuda:
tensor = tensor.cuda()
return tensor