-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
63 lines (55 loc) · 2.05 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
class Indexer(object):
"""
Bijection between objects and integers starting at 0. Useful for mapping
labels, features, etc. into coordinates of a vector space.
Attributes:
objs_to_ints
ints_to_objs
"""
def __init__(self):
self.objs_to_ints = {}
self.ints_to_objs = {}
def __repr__(self):
return str([str(self.get_object(i)) for i in range(0, len(self))])
def __str__(self):
return self.__repr__()
def __len__(self):
return len(self.objs_to_ints)
def get_object(self, index):
"""
:param index: integer index to look up
:return: Returns the object corresponding to the particular index or None if not found
"""
if (index not in self.ints_to_objs):
return None
else:
return self.ints_to_objs[index]
def contains(self, object):
"""
:param object: object to look up
:return: Returns True if it is in the Indexer, False otherwise
"""
return self.index_of(object) != -1
def index_of(self, object):
"""
:param object: object to look up
:return: Returns -1 if the object isn't present, index otherwise
"""
if (object not in self.objs_to_ints):
return -1
else:
return self.objs_to_ints[object]
def add_and_get_index(self, object, add=True):
"""
Adds the object to the index if it isn't present, always returns a nonnegative index
:param object: object to look up or add
:param add: True by default, False if we shouldn't add the object. If False, equivalent to index_of.
:return: The index of the object
"""
if not add:
return self.index_of(object)
if (object not in self.objs_to_ints):
new_idx = len(self.objs_to_ints)
self.objs_to_ints[object] = new_idx
self.ints_to_objs[new_idx] = object
return self.objs_to_ints[object]