forked from vyraun/Half-Size
-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_embeddings.py
60 lines (47 loc) · 1.36 KB
/
new_embeddings.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
import numpy as np
import _pickle as pickle
from sklearn.decomposition import PCA
import subprocess
Glove = {}
f = open('glove.6B.200d.txt')
print("Loading Glove vectors.")
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
Glove[word] = coefs
f.close()
print("Done.")
X_train = []
X_train_names = []
for x in Glove:
X_train.append(Glove[x])
X_train_names.append(x)
X_train = np.asarray(X_train)
pca_embeddings = {}
embedding_file = open('pca_embedding_30.txt', 'w')
# First PCA to get Top Components
pca = PCA(n_components = 200)
X_train = X_train - np.mean(X_train)
X_fit = pca.fit_transform(X_train)
U1 = pca.components_
pca_embeddings = {}
z = []
# Removing Projections on Top Components
for i, x in enumerate(X_train):
for u in U1[0:7]:
x = x - np.dot(u.transpose(),x) * u
z.append(x)
z = np.asarray(z).astype(np.float32)
# PCA for Dim Reduction
pca = PCA(n_components = 100)
X_train = z - np.mean(z)
X_new = pca.fit_transform(X_train)
final_pca_embeddings = {}
embedding_file = open('pca_embedding_30.txt', 'w')
for i, x in enumerate(X_train_names):
final_pca_embeddings[x] = X_new[i]
embedding_file.write("%s\t" % x)
for t in final_pca_embeddings[x]:
embedding_file.write("%f\t" % t)
embedding_file.write("\n")