-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_vec.py
51 lines (43 loc) · 1.57 KB
/
get_vec.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
import os
import numpy as np
import pickle
import subprocess
from sklearn.metrics.pairwise import cosine_similarity
from shutil import move
def load_matrices():
"""
Function for loading in matrices from pickle files
"""
outs = []
for filename in ['embed_ix', 'embed_matrix', 'categories']:
with open(f'data/{filename}.pkl', 'rb') as f:
temp = pickle.load(f)
outs.append(temp)
return outs
def get_closest(inputs, stochastic=False):
"""
Function for finding the closest vector among the categories
Arguments:
inputs (str): Input string to be embedded
stochastic (boolean): If True, randomly samples from top 5 closest vectors else use the closest vector
"""
inputs = inputs.lower().split(" ")
feat_vec = np.tile(embed_matrix.mean(axis=0), (len(inputs), 1))
for ix, word in enumerate(inputs):
try: feat_vec[ix] = embed_ix[word]
except KeyError: pass
feat_vec = feat_vec.mean(axis=0).reshape(1, -1)
sims = cosine_similarity(feat_vec, embed_matrix)
if stochastic:
return cats[np.random.choice(sims.argsort()[0, -5:][::-1].tolist())]
else:
return cats[np.argmax(sims)]
if __name__ == "__main__":
with open('data/files.pkl', 'rb') as f:
files = pickle.load(f)
embed_ix, embed_matrix, cats = load_matrices()
input_str = input("Enter your text: ")
chosen_class = get_closest(str(input_str))
f = [i for i in files if chosen_class in i]
print("Downloading closest class...")
subprocess.run(["gsutil", "cp", f[0], 'data/'])