-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdummyindexer.py
78 lines (66 loc) · 1.72 KB
/
dummyindexer.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import abc
import pickle
import numpy as np
class Indexer(abc.ABC):
@abc.abstractmethod
def add(self, vs):
pass
@abc.abstractmethod
def train(self, train_vectors):
pass
@abc.abstractmethod
def find(self, query, topn):
pass
@abc.abstractmethod
def save(self,index):
pass
@abc.abstractmethod
def load(self, file):
pass
class DummyIndexer(Indexer):
def __init__(self):
"""
Creates an empty index object
"""
self.index = None
def add(self, embs: np.ndarray):
"""
Adds new embeddings embs in empty or existing index
:param embs:
:return:
"""
if self.index is None:
self.index = embs
else:
self.index = np.append(self.index, embs, axis=0)
def train(self):
"""
Not sure if this one is necessary here, left for compatibility with abstract class Indexer
:return:
"""
pass
def find(self, query: np.ndarray, topn: int) -> (np.ndarray, np.ndarray):
"""
Returns topn entries closest to the query vector
:param query:
:param topn:
:return:
"""
similarities = (self.index @ query.squeeze())
best_photo_idx = (-similarities).argsort()
D, I = similarities[best_photo_idx[:topn]], best_photo_idx[:topn]
return D, I
def save(self, file: str):
"""
Saves data to npy file
:param file:
:return:
"""
np.save(file, self.index)
def load(self, file: str):
"""
Loads data from npy file
:param file:
:return:
"""
self.index = np.load(file)