-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvectorize.py
240 lines (203 loc) · 8.03 KB
/
vectorize.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import sqlite3
from gensim.models.word2vec import Word2Vec
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.cluster import KMeans
from sklearn.metrics.cluster import adjusted_mutual_info_score, silhouette_score
from nltk.corpus import stopwords
import pandas as pd
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
import numpy as np
import os
import argparse
from sklearn.decomposition import PCA
import json
from pprint import pprint
def bert(vec_path):
vectors = []
with open(vec_path, 'r') as file:
for line in file.readlines():
vectors.append(json.loads(line))
return np.asarray(vectors)
def w2v(data, model_path='data/word2vec_sg0'):
if os.path.isfile(model_path):
model = Word2Vec.load(model_path)
else:
model = Word2Vec(data, size=100, window=5, min_count=5, workers=4, iter=15, sg=0)
model.save(model_path)
print('Model Saved:', model_path)
result = []
for text_id, text in enumerate(data):
word_vectors = []
for word in text:
if word in model.wv.vocab:
word_vectors.append(model.wv[word])
if len(word_vectors) > 0:
result.append(np.mean(word_vectors, axis=0))
else:
result.append([0] * 100)
return np.asarray(result)
def d2v(data, ids, dm, model_path):
tagged_data = [
TaggedDocument(words=text, tags=[text_id])
for text, text_id in zip(data, ids)
]
if os.path.isfile(model_path):
model = Doc2Vec.load(model_path)
else:
model = Doc2Vec(tagged_data, vector_size=100, window=5, min_count=5, workers=4, epochs=15, dm=dm)
model.save(model_path)
print("Model Saved:", model_path)
result = []
for doc in tagged_data:
result.append(*model[doc.tags])
return np.asarray(result)
def lsa(corpus):
tfidf = TfidfVectorizer().fit_transform(corpus)#.toarray()
return TruncatedSVD(n_components=100).fit_transform(tfidf)
def lda(corpus):
tf = CountVectorizer().fit_transform(corpus)#.toarray()
return LatentDirichletAllocation(
n_components=100,
random_state=42,
n_jobs=-1,
verbose=1).fit_transform(tf)
def rdf(corpus, model_path='data/dict.jsonld', verbose=0):
with open(model_path, encoding="utf8") as f:
data = json.load(f)
if verbose:
pprint(data)
w2i, i2w, ids = {}, {}, []
for d in data['@graph']:
if d['@type'] != 'skos:Concept':
continue
i = d['@id']
ids.append(i)
words = []
for key in ['skos:prefLabel', 'skos:altLabel', 'skos:hiddenLabel']:
pairs = d.get(key, {}).items()
for lang, labels in pairs:
if isinstance(labels, list):
words.extend(labels)
else:
words.append(labels)
# print(words)
for w in words:
w2i.setdefault(w, []).append(len(ids) - 1)
i2w.setdefault(len(ids) - 1, []).append(w)
vectors = np.zeros((len(corpus), len(ids)))
for index, row in enumerate(corpus):
tokens = row.split()
for k in range(1, 3):
for j in range(0, len(tokens), k):
t = ' '.join(tokens[j:j + k])
i = w2i.get(t, None)
if i is not None:
vectors[index, i] += 1
vectors /= vectors.sum(axis=1, keepdims=True)
vectors = np.nan_to_num(vectors, nan=0)
return vectors
def topic_net(files):
data_path = 'data/topic_net.csv'
df = pd.read_csv(data_path, usecols=['file_paths', 'vec'],
converters={'vec': lambda x: json.loads(x)})
dim = len(df['vec'][0])
print(f'vectors: {len(df)}, dim: {dim}')
fp2i = {x: i for i, x in enumerate(df['file_paths'])}
vectors = []
for i, row in files.iterrows():
fp = row['file_path']
i2 = fp2i.get(fp, None)
if i2 is not None:
vectors.append(df['vec'][i2])
else:
print(fp)
vectors.append([0 for _ in range(dim)])
vectors = np.array(vectors)
return vectors
def cluster(vec, n_clusters):
return KMeans(n_clusters, random_state=42).fit(vec).labels_
def lbl2color(l):
colors = [
"#cc4767", "#6f312a", "#d59081", "#d14530", "#d27f35",
"#887139", "#d2b64b", "#c7df48", "#c0d296", "#5c8f37",
"#364d26", "#70d757", "#60db9e", "#4c8f76", "#75d4d5",
"#6a93c1", "#616ed0", "#46316c", "#8842c4", "#bc87d0"
]
return colors[l % len(colors)]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--type', choices=[
'word2vec', 'pv_dm', 'pv_dbow', 'lsa', 'lda', 'rdf', 'topic_net', 'bert'])
parser.add_argument('--labels', choices=['db', 'cluster'])
parser.add_argument('--save', type=str, default=None)
parser.add_argument('--plot', action='store_true')
parser.add_argument('--dataset', choices=['mouse', 'trecgen', '20ng'])
args = parser.parse_args()
conn = sqlite3.connect(f'data/{args.dataset}.sqlite')
stops = set(stopwords.words('english'))
stops.add('http')
files = pd.read_sql('SELECT * FROM Files', conn)
texts = [list(filter(lambda w: w not in stops, text.split())) for text in files['text']]
text_ids = list(map(int, files['file_id']))
if args.type == 'word2vec':
vectors = w2v(texts, model_path=f'data/word2vec_sg0_{args.dataset}')
elif args.type == 'pv_dm':
vectors = d2v(texts, text_ids, dm=1, model_path=f'data/pvdm_{args.dataset}')
elif args.type == 'pv_dbow':
vectors = d2v(texts, text_ids, dm=0, model_path=f'data/pvdbow_{args.dataset}')
elif args.type == 'lsa':
vectors = lsa(files['text'])
elif args.type == 'lda':
vectors = lda(files['text'])
elif args.type == 'rdf':
vectors = rdf(files['text'])
elif args.type == 'topic_net':
vectors = topic_net(files)
elif args.type == 'bert':
vectors = bert(vec_path=f'data/bert_{args.dataset}_vecs.json')
else:
assert False, '{} is not implemented'.format(args.type)
#for i, v in enumerate(vectors):
# vectors[i] = v / np.linalg.norm(v)
cursor = conn.cursor()
cursor.execute(f'DROP TABLE IF EXISTS {args.type}')
cursor.execute(f'CREATE TABLE {args.type}(file_id INTEGER NOT NULL PRIMARY KEY, vec TEXT NOT NULL)')
for text_id, v in zip(text_ids, vectors):
vec = ','.join(map(str, v))
cursor.execute(f'INSERT INTO {args.type} VALUES ({text_id}, "{vec}")')
conn.commit()
if args.labels == 'db':
labels = [list(map(int, ids.split(','))) for ids in files['label_ids']]
elif args.labels == 'cluster':
labels = cluster(vectors, n_clusters=27)
else:
assert False, '{} is not implemented'.format(args.labels)
if args.save:
with open('{}.csv'.format(args.save), 'w') as out:
file_path = list(files['file_path'])
out.write('file_id\tfile_path\tlabel\n')
for i in np.argsort(labels):
out.write('{}\t{}\t{}\n'.format(text_ids[i], file_path[i], labels[i]))
if args.plot:
#vectors = PCA(n_components=30).fit_transform(vectors)
emb = TSNE(random_state=42).fit_transform(vectors)
print(emb.shape)
for i in range(len(emb)):
plt.plot(emb[i][0], emb[i][1], marker='')
if args.labels == 'db':
for lbl in labels[i]:
plt.text(emb[i][0], emb[i][1], str(lbl), color=lbl2color(lbl), fontsize=12)
elif args.labels == 'cluster':
plt.text(emb[i][0], emb[i][1], str(labels[i]), color=lbl2color(labels[i]), fontsize=12)
plt.axis('off')
plt.show()
exit(0)
print(vectors.shape)
labels = np.asarray(labels).ravel()
print(labels.shape)
score = silhouette_score(vectors, labels)
print('silhouette_score', score)