forked from machelreid/vcdm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembeddings.py
More file actions
37 lines (30 loc) · 978 Bytes
/
Copy pathembeddings.py
File metadata and controls
37 lines (30 loc) · 978 Bytes
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
import torch
import torch.nn as nn
import gensim
from gensim.models import KeyedVectors
import numpy as np
from tqdm import tqdm
print("Loading Word2Vec")
google_wv = KeyedVectors.load_word2vec_format(
"/path/to/GoogleNews-vectors-negative300.bin",
binary=True,
limit=500000, # faster loading
)
def Word2Vec(list_of_words):
model = google_wv
number = 0
embedding_matrix = np.zeros((len(list_of_words), 300))
for i, word in tqdm(enumerate(list_of_words)):
try:
if word == "<pad>":
embedding_matrix[i] = np.zeros(300)
else:
embedding_matrix[i] = model[word]
number += 1
except KeyError:
embedding_matrix[i] = np.random.uniform(-0.05, 0.05, 300)
embs = torch.FloatTensor(embedding_matrix)
print("Loaded Word2Vec")
print("Vocab Size:", embedding_matrix.shape)
print("Coverage:", 100 * number / len(list_of_words))
return embs