-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhelpers.py
More file actions
63 lines (44 loc) · 1.67 KB
/
Copy pathhelpers.py
File metadata and controls
63 lines (44 loc) · 1.67 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
import string
import torch as th
class Helpers:
# default constructor
def __init__(self):
self.char2index = {}
self.index2char = {}
for i,char in enumerate(' ' + string.ascii_lowercase + '0123456789' + string.punctuation):
self.char2index[char] = i
self.index2char[i] = char
def string2values(self, str_input, max_len=8):
str_input = str_input[:max_len].lower()
# pad strings shorter than max len
if(len(str_input) < max_len):
str_input = str_input + "." * (max_len - len(str_input))
values = list()
for char in str_input:
values.append(self.char2index[char])
return th.tensor(values).long()
def values2string(self, input_values):
s = ""
for value in input_values:
s += self.index2char[int(value)]
return s
def strings_equal(self ,str_a, str_b):
vect = (str_a * str_b).sum(1)
x = vect[0]
for i in range(vect.shape[0] - 1):
x = x * vect[i + 1]
return x
def one_hot(self, index, length):
vect = th.zeros(length).long()
vect[index] = 1
return vect
def string2one_hot_matrix(self ,str_input, max_len=8):
str_input = str_input[:max_len].lower()
# pad strings shorter than max len
if(len(str_input) < max_len):
str_input = str_input + "." * (max_len - len(str_input))
char_vectors = list()
for char in str_input:
char_v = self.one_hot(self.char2index[char], len(self.char2index)).unsqueeze(0)
char_vectors.append(char_v)
return th.cat(char_vectors, dim=0)