-
Notifications
You must be signed in to change notification settings - Fork 1
/
glove_solution.py
executable file
·40 lines (31 loc) · 1.01 KB
/
glove_solution.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
#!/usr/bin/env python3
from scipy.sparse import *
import numpy as np
import pickle
import random
def main():
print("loading cooccurrence matrix")
with open('cooc.pkl', 'rb') as f:
cooc = pickle.load(f)
print("{} nonzero entries".format(cooc.nnz))
nmax = 100
print("using nmax =", nmax, ", cooc.max() =", cooc.max())
print("initializing embeddings")
embedding_dim = 20
xs = np.random.normal(size=(cooc.shape[0], embedding_dim))
ys = np.random.normal(size=(cooc.shape[1], embedding_dim))
eta = 0.001
alpha = 3 / 4
epochs = 10
for epoch in range(epochs):
print("epoch {}".format(epoch))
for ix, jy, n in zip(cooc.row, cooc.col, cooc.data):
logn = np.log(n)
fn = min(1.0, (n / nmax) ** alpha)
x, y = xs[ix, :], ys[jy, :]
scale = 2 * eta * fn * (logn - np.dot(x, y))
xs[ix, :] += scale * y
ys[jy, :] += scale * x
np.save('embeddings', xs)
if __name__ == '__main__':
main()