diff options
author | Yigit Sever | 2019-09-19 00:22:25 +0300 |
---|---|---|
committer | Yigit Sever | 2019-09-19 00:22:25 +0300 |
commit | 1890976ed1eee59eda92ceabdcb1c966d6707269 (patch) | |
tree | f7bb7de36d158ee970aaf4f0f5a6b682ac359825 | |
parent | 68b6c55d0e3217362d6e17ea8458dfa7e5242e17 (diff) | |
download | Evaluating-Dictionary-Alignment-1890976ed1eee59eda92ceabdcb1c966d6707269.tar.gz Evaluating-Dictionary-Alignment-1890976ed1eee59eda92ceabdcb1c966d6707269.tar.bz2 Evaluating-Dictionary-Alignment-1890976ed1eee59eda92ceabdcb1c966d6707269.zip |
Add experiment scripts
-rw-r--r-- | WMD_matching.py | 265 | ||||
-rw-r--r-- | WMD_retrieval.py | 259 | ||||
-rw-r--r-- | Wass_Matcher.py | 76 | ||||
-rw-r--r-- | Wass_Retriever.py | 73 | ||||
-rw-r--r-- | sentence_emb_matching.py | 153 | ||||
-rw-r--r-- | sentence_emb_retrieval.py | 151 |
6 files changed, 977 insertions, 0 deletions
diff --git a/WMD_matching.py b/WMD_matching.py new file mode 100644 index 0000000..c65e6e5 --- /dev/null +++ b/WMD_matching.py | |||
@@ -0,0 +1,265 @@ | |||
1 | ########################### | ||
2 | # Wasserstein Retrieval # | ||
3 | ########################### | ||
4 | import argparse | ||
5 | |||
6 | parser = argparse.ArgumentParser(description='run matching using wmd and wasserstein distances') | ||
7 | parser.add_argument('source_lang', help='source language short name') | ||
8 | parser.add_argument('target_lang', help='target language short name') | ||
9 | parser.add_argument('source_vector', help='path of the source vector') | ||
10 | parser.add_argument('target_vector', help='path of the target vector') | ||
11 | parser.add_argument('source_defs', help='path of the source definitions') | ||
12 | parser.add_argument('target_defs', help='path of the target definitions') | ||
13 | parser.add_argument('-n', '--instances', help='number of instances in each language to retrieve', default=2000, type=int) | ||
14 | |||
15 | args = parser.parse_args() | ||
16 | |||
17 | source_lang = args.source_lang | ||
18 | target_lang = args.target_lang | ||
19 | |||
20 | def load_embeddings(path, dimension=300): | ||
21 | """ | ||
22 | Loads the embeddings from a word2vec formatted file. | ||
23 | word2vec format is one line per word and it's associated embedding | ||
24 | (dimension x floating numbers) separated by spaces | ||
25 | The first line may or may not include the word count and dimension | ||
26 | """ | ||
27 | vectors = {} | ||
28 | with open(path, mode='r', encoding='utf8') as fp: | ||
29 | first_line = fp.readline().rstrip('\n') | ||
30 | if first_line.count(' ') == 1: | ||
31 | # includes the "word_count dimension" information | ||
32 | (word_count, dimension) = map(int, first_line.split()) | ||
33 | else: | ||
34 | # assume the file only contains vectors | ||
35 | fp.seek(0) | ||
36 | for line in fp: | ||
37 | elems = line.split() | ||
38 | vectors[" ".join(elems[:-dimension])] = " ".join(elems[-dimension:]) | ||
39 | return vectors | ||
40 | |||
41 | ####################################################################### | ||
42 | # Vectors Load Here # | ||
43 | ####################################################################### | ||
44 | |||
45 | source_vectors_filename = args.source_vector | ||
46 | target_vectors_filename = args.target_vector | ||
47 | vectors_source = load_embeddings(source_vectors_filename) | ||
48 | vectors_target = load_embeddings(target_vectors_filename) | ||
49 | |||
50 | ####################################################################### | ||
51 | # Corpora Load Here # | ||
52 | ####################################################################### | ||
53 | |||
54 | source_defs_filename = args.source_defs | ||
55 | target_defs_filename = args.target_defs | ||
56 | defs_source = [line.rstrip('\n') for line in open(source_defs_filename, encoding='utf8')] | ||
57 | defs_target = [line.rstrip('\n') for line in open(target_defs_filename, encoding='utf8')] | ||
58 | |||
59 | import numpy as np | ||
60 | from mosestokenizer import * | ||
61 | |||
62 | def clean_corpus_using_embeddings_vocabulary( | ||
63 | embeddings_dictionary, | ||
64 | corpus, | ||
65 | vectors, | ||
66 | language, | ||
67 | ): | ||
68 | ''' | ||
69 | Cleans corpus using the dictionary of embeddings. | ||
70 | Any word without an associated embedding in the dictionary is ignored. | ||
71 | Adds '__target-language' and '__source-language' at the end of the words according to their language. | ||
72 | ''' | ||
73 | clean_corpus, clean_vectors, keys = [], {}, [] | ||
74 | words_we_want = set(embeddings_dictionary) | ||
75 | tokenize = MosesTokenizer(language) | ||
76 | for key, doc in enumerate(corpus): | ||
77 | clean_doc = [] | ||
78 | words = tokenize(doc) | ||
79 | for word in words: | ||
80 | if word in words_we_want: | ||
81 | clean_doc.append(word + '__%s' % language) | ||
82 | clean_vectors[word + '__%s' % language] = np.array(vectors[word].split()).astype(np.float) | ||
83 | if len(clean_doc) > 3 and len(clean_doc) < 25: | ||
84 | keys.append(key) | ||
85 | clean_corpus.append(' '.join(clean_doc)) | ||
86 | tokenize.close() | ||
87 | return np.array(clean_corpus), clean_vectors, keys | ||
88 | |||
89 | import nltk | ||
90 | clean_src_corpus, clean_src_vectors, src_keys = clean_corpus_using_embeddings_vocabulary( | ||
91 | set(vectors_source.keys()), | ||
92 | defs_source, | ||
93 | vectors_source, | ||
94 | source_lang, | ||
95 | ) | ||
96 | |||
97 | clean_target_corpus, clean_target_vectors, target_keys = clean_corpus_using_embeddings_vocabulary( | ||
98 | set(vectors_target.keys()), | ||
99 | defs_target, | ||
100 | vectors_target, | ||
101 | target_lang, | ||
102 | ) | ||
103 | |||
104 | import random | ||
105 | take = args.instances | ||
106 | |||
107 | common_keys = set(src_keys).intersection(set(target_keys)) | ||
108 | take = min(len(common_keys), take) # you can't sample more than length | ||
109 | experiment_keys = random.sample(common_keys, take) | ||
110 | |||
111 | instances = len(experiment_keys) | ||
112 | |||
113 | clean_src_corpus = list(clean_src_corpus[experiment_keys]) | ||
114 | clean_target_corpus = list(clean_target_corpus[experiment_keys]) | ||
115 | |||
116 | print(f'{source_lang} - {target_lang} : document sizes: {len(clean_src_corpus)}, {len(clean_target_corpus)}') | ||
117 | |||
118 | del vectors_source, vectors_target, defs_source, defs_target | ||
119 | |||
120 | from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer | ||
121 | |||
122 | vec = CountVectorizer().fit(clean_src_corpus + clean_target_corpus) | ||
123 | common = [word for word in vec.get_feature_names() if word in clean_src_vectors or word in clean_target_vectors] | ||
124 | W_common = [] | ||
125 | for w in common: | ||
126 | if w in clean_src_vectors: | ||
127 | W_common.append(np.array(clean_src_vectors[w])) | ||
128 | else: | ||
129 | W_common.append(np.array(clean_target_vectors[w])) | ||
130 | |||
131 | print(f'{source_lang} - {target_lang}: the vocabulary size is {len(W_common)}') | ||
132 | |||
133 | from sklearn.preprocessing import normalize | ||
134 | W_common = np.array(W_common) | ||
135 | W_common = normalize(W_common) | ||
136 | vect = TfidfVectorizer(vocabulary=common, dtype=np.double, norm=None) | ||
137 | vect.fit(clean_src_corpus + clean_target_corpus) | ||
138 | X_train_idf = vect.transform(clean_src_corpus) | ||
139 | X_test_idf = vect.transform(clean_target_corpus) | ||
140 | |||
141 | vect_tf = CountVectorizer(vocabulary=common, dtype=np.double) | ||
142 | vect_tf.fit(clean_src_corpus + clean_target_corpus) | ||
143 | X_train_tf = vect_tf.transform(clean_src_corpus) | ||
144 | X_test_tf = vect_tf.transform(clean_target_corpus) | ||
145 | |||
146 | import ot | ||
147 | from lapjv import lapjv | ||
148 | from sklearn.neighbors import KNeighborsClassifier | ||
149 | from sklearn.metrics import euclidean_distances | ||
150 | from sklearn.externals.joblib import Parallel, delayed | ||
151 | from sklearn.utils import check_array | ||
152 | from sklearn.metrics.scorer import check_scoring | ||
153 | from pathos.multiprocessing import ProcessingPool as Pool | ||
154 | from sklearn.metrics import euclidean_distances | ||
155 | |||
156 | class WassersteinDistances(KNeighborsClassifier): | ||
157 | """ | ||
158 | Implements a nearest neighbors classifier for input distributions using the Wasserstein distance as metric. | ||
159 | Source and target distributions are l_1 normalized before computing the Wasserstein distance. | ||
160 | Wasserstein is parametrized by the distances between the individual points of the distributions. | ||
161 | In this work, we propose to use cross-lingual embeddings for calculating these distances. | ||
162 | |||
163 | """ | ||
164 | def __init__(self, W_embed, n_neighbors=1, n_jobs=1, verbose=False, sinkhorn= False, sinkhorn_reg=0.1): | ||
165 | """ | ||
166 | Initialization of the class. | ||
167 | Arguments | ||
168 | --------- | ||
169 | W_embed: embeddings of the words, np.array | ||
170 | verbose: True/False | ||
171 | """ | ||
172 | self.sinkhorn = sinkhorn | ||
173 | self.sinkhorn_reg = sinkhorn_reg | ||
174 | self.W_embed = W_embed | ||
175 | self.verbose = verbose | ||
176 | super(WassersteinDistances, self).__init__(n_neighbors=n_neighbors, n_jobs=n_jobs, metric='precomputed', algorithm='brute') | ||
177 | |||
178 | def _wmd(self, i, row, X_train): | ||
179 | union_idx = np.union1d(X_train[i].indices, row.indices) | ||
180 | W_minimal = self.W_embed[union_idx] | ||
181 | W_dist = euclidean_distances(W_minimal) | ||
182 | bow_i = X_train[i, union_idx].A.ravel() | ||
183 | bow_j = row[:, union_idx].A.ravel() | ||
184 | if self.sinkhorn: | ||
185 | return ot.sinkhorn2(bow_i, bow_j, W_dist, self.sinkhorn_reg, numItermax=50, method='sinkhorn_stabilized',)[0] | ||
186 | else: | ||
187 | return ot.emd2(bow_i, bow_j, W_dist) | ||
188 | |||
189 | def _wmd_row(self, row): | ||
190 | X_train = self._fit_X | ||
191 | n_samples_train = X_train.shape[0] | ||
192 | return [self._wmd(i, row, X_train) for i in range(n_samples_train)] | ||
193 | |||
194 | def _pairwise_wmd(self, X_test, X_train=None): | ||
195 | n_samples_test = X_test.shape[0] | ||
196 | |||
197 | if X_train is None: | ||
198 | X_train = self._fit_X | ||
199 | pool = Pool(nodes=self.n_jobs) # Parallelization of the calculation of the distances | ||
200 | dist = pool.map(self._wmd_row, X_test) | ||
201 | return np.array(dist) | ||
202 | |||
203 | def fit(self, X, y): # X_train_idf | ||
204 | X = check_array(X, accept_sparse='csr', copy=True) # check if array is sparse | ||
205 | X = normalize(X, norm='l1', copy=False) | ||
206 | return super(WassersteinDistances, self).fit(X, y) # X_train_idf, np_ones(document collection size) | ||
207 | |||
208 | def predict(self, X): | ||
209 | X = check_array(X, accept_sparse='csr', copy=True) | ||
210 | X = normalize(X, norm='l1', copy=False) | ||
211 | dist = self._pairwise_wmd(X) | ||
212 | dist = dist * 1000 # for lapjv, small floating point numbers are evil | ||
213 | return super(WassersteinDistances, self).predict(dist) | ||
214 | |||
215 | def kneighbors(self, X, n_neighbors=1): # X : X_train_idf | ||
216 | X = check_array(X, accept_sparse='csr', copy=True) | ||
217 | X = normalize(X, norm='l1', copy=False) | ||
218 | dist = self._pairwise_wmd(X) | ||
219 | dist = dist * 1000 # for lapjv, small floating point numbers are evil | ||
220 | return lapjv(dist) # and here is the matching part | ||
221 | |||
222 | def mrr_precision_at_k(golden, preds, k_list=[1,]): | ||
223 | """ | ||
224 | Calculates Mean Reciprocal Error and Hits@1 == Precision@1 | ||
225 | """ | ||
226 | my_score = 0 | ||
227 | precision_at = np.zeros(len(k_list)) | ||
228 | for key, elem in enumerate(golden): | ||
229 | if elem in preds[key]: | ||
230 | location = np.where(preds[key]==elem)[0][0] | ||
231 | my_score += 1/(1+ location) | ||
232 | for k_index, k_value in enumerate(k_list): | ||
233 | if location < k_value: | ||
234 | precision_at[k_index] += 1 | ||
235 | return my_score/len(golden), (precision_at/len(golden))[0] | ||
236 | |||
237 | print(f'WMD - tfidf: {source_lang} - {target_lang}') | ||
238 | clf = WassersteinDistances(W_embed=W_common, n_neighbors=5, n_jobs=14) | ||
239 | clf.fit(X_train_idf[:instances], np.ones(instances)) | ||
240 | row_ind, col_ind, a = clf.kneighbors(X_test_idf[:instances], n_neighbors=instances) | ||
241 | result = zip(row_ind, col_ind) | ||
242 | hit_one = len([x for x,y in result if x == y]) | ||
243 | print(f'{hit_one} definitions have been mapped correctly') | ||
244 | |||
245 | import csv | ||
246 | percentage = hit_one / instances * 100 | ||
247 | fields = [f'{source_lang}', f'{target_lang}', f'{instances}', f'{hit_one}', f'{percentage}'] | ||
248 | with open('/home/syigit/multilang_results/wmd_matching_result.csv', 'a') as f: | ||
249 | writer = csv.writer(f) | ||
250 | writer.writerow(fields) | ||
251 | |||
252 | print(f'Sinkhorn - tfidf: {source_lang} - {target_lang}') | ||
253 | clf = WassersteinDistances(W_embed=W_common, n_neighbors=5, n_jobs=14, sinkhorn=True) | ||
254 | clf.fit(X_train_idf[:instances], np.ones(instances)) | ||
255 | row_ind, col_ind, a = clf.kneighbors(X_test_idf[:instances], n_neighbors=instances) | ||
256 | |||
257 | result = zip(row_ind, col_ind) | ||
258 | hit_one = len([x for x,y in result if x == y]) | ||
259 | print(f'{hit_one} definitions have been mapped correctly') | ||
260 | |||
261 | percentage = hit_one / instances * 100 | ||
262 | fields = [f'{source_lang}', f'{target_lang}', f'{instances}', f'{hit_one}', f'{percentage}'] | ||
263 | with open('/home/syigit/multilang_results/sinkhorn_matching_result.csv', 'a') as f: | ||
264 | writer = csv.writer(f) | ||
265 | writer.writerow(fields) | ||
diff --git a/WMD_retrieval.py b/WMD_retrieval.py new file mode 100644 index 0000000..f99eaa1 --- /dev/null +++ b/WMD_retrieval.py | |||
@@ -0,0 +1,259 @@ | |||
1 | ########################### | ||
2 | # Wasserstein Retrieval # | ||
3 | ########################### | ||
4 | import argparse | ||
5 | |||
6 | parser = argparse.ArgumentParser(description='run retrieval using wmd and wasserstein distances') | ||
7 | parser.add_argument('source_lang', help='source language short name') | ||
8 | parser.add_argument('target_lang', help='target language short name') | ||
9 | parser.add_argument('source_vector', help='path of the source vector') | ||
10 | parser.add_argument('target_vector', help='path of the target vector') | ||
11 | parser.add_argument('source_defs', help='path of the source definitions') | ||
12 | parser.add_argument('target_defs', help='path of the target definitions') | ||
13 | parser.add_argument('-n', '--instances', help='number of instances in each language to retrieve', default=2000, type=int) | ||
14 | |||
15 | args = parser.parse_args() | ||
16 | |||
17 | source_lang = args.source_lang | ||
18 | target_lang = args.target_lang | ||
19 | |||
20 | def load_embeddings(path, dimension=300): | ||
21 | """ | ||
22 | Loads the embeddings from a word2vec formatted file. | ||
23 | word2vec format is one line per word and it's associated embedding | ||
24 | (dimension x floating numbers) separated by spaces | ||
25 | The first line may or may not include the word count and dimension | ||
26 | """ | ||
27 | vectors = {} | ||
28 | with open(path, mode='r', encoding='utf8') as fp: | ||
29 | first_line = fp.readline().rstrip('\n') | ||
30 | if first_line.count(' ') == 1: | ||
31 | # includes the "word_count dimension" information | ||
32 | (word_count, dimension) = map(int, first_line.split()) | ||
33 | else: # assume the file only contains vectors | ||
34 | fp.seek(0) | ||
35 | for line in fp: | ||
36 | elems = line.split() | ||
37 | vectors[" ".join(elems[:-dimension])] = " ".join(elems[-dimension:]) | ||
38 | return vectors | ||
39 | |||
40 | ####################################################################### | ||
41 | # Vectors Load Here # | ||
42 | ####################################################################### | ||
43 | |||
44 | source_vectors_filename = args.source_vector | ||
45 | target_vectors_filename = args.target_vector | ||
46 | vectors_source = load_embeddings(source_vectors_filename) | ||
47 | vectors_target = load_embeddings(target_vectors_filename) | ||
48 | |||
49 | ####################################################################### | ||
50 | # Corpora Load Here # | ||
51 | ####################################################################### | ||
52 | source_defs_filename = args.source_defs | ||
53 | target_defs_filename = args.target_defs | ||
54 | defs_source = [line.rstrip('\n') for line in open(source_defs_filename, encoding='utf8')] | ||
55 | defs_target = [line.rstrip('\n') for line in open(target_defs_filename, encoding='utf8')] | ||
56 | |||
57 | import numpy as np | ||
58 | from mosestokenizer import * | ||
59 | |||
60 | def clean_corpus_using_embeddings_vocabulary( | ||
61 | embeddings_dictionary, | ||
62 | corpus, | ||
63 | vectors, | ||
64 | language, | ||
65 | ): | ||
66 | ''' | ||
67 | Cleans corpus using the dictionary of embeddings. | ||
68 | Any word without an associated embedding in the dictionary is ignored. | ||
69 | Adds '__target-language' and '__source-language' at the end of the words according to their language. | ||
70 | ''' | ||
71 | clean_corpus, clean_vectors, keys = [], {}, [] | ||
72 | words_we_want = set(embeddings_dictionary) | ||
73 | tokenize = MosesTokenizer(language) | ||
74 | for key, doc in enumerate(corpus): | ||
75 | clean_doc = [] | ||
76 | words = tokenize(doc) | ||
77 | for word in words: | ||
78 | if word in words_we_want: | ||
79 | clean_doc.append(word + '__%s' % language) | ||
80 | clean_vectors[word + '__%s' % language] = np.array(vectors[word].split()).astype(np.float) | ||
81 | if len(clean_doc) > 3 and len(clean_doc) < 25: | ||
82 | keys.append(key) | ||
83 | clean_corpus.append(' '.join(clean_doc)) | ||
84 | tokenize.close() | ||
85 | return np.array(clean_corpus), clean_vectors, keys | ||
86 | |||
87 | clean_src_corpus, clean_src_vectors, src_keys = clean_corpus_using_embeddings_vocabulary( | ||
88 | set(vectors_source.keys()), | ||
89 | defs_source, | ||
90 | vectors_source, | ||
91 | source_lang, | ||
92 | ) | ||
93 | |||
94 | clean_target_corpus, clean_target_vectors, target_keys = clean_corpus_using_embeddings_vocabulary( | ||
95 | set(vectors_target.keys()), | ||
96 | defs_target, | ||
97 | vectors_target, | ||
98 | target_lang, | ||
99 | ) | ||
100 | |||
101 | # Here is the part Wasserstein prunes two corporas to 500 articles each | ||
102 | # Our dataset does not have that luxury (turns out it's not a luxury but a necessity) | ||
103 | |||
104 | import random | ||
105 | take = args.instances | ||
106 | |||
107 | common_keys = set(src_keys).intersection(set(target_keys)) | ||
108 | take = min(len(common_keys), take) # you can't sample more than length | ||
109 | experiment_keys = random.sample(common_keys, take) | ||
110 | |||
111 | instances = len(experiment_keys) | ||
112 | |||
113 | clean_src_corpus = list(clean_src_corpus[experiment_keys]) | ||
114 | clean_target_corpus = list(clean_target_corpus[experiment_keys]) | ||
115 | |||
116 | print(f'{source_lang} - {target_lang} : document sizes: {len(clean_src_corpus)}, {len(clean_target_corpus)}') | ||
117 | |||
118 | del vectors_source, vectors_target, defs_source, defs_target | ||
119 | |||
120 | from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer | ||
121 | |||
122 | vec = CountVectorizer().fit(clean_src_corpus + clean_target_corpus) | ||
123 | common = [word for word in vec.get_feature_names() if word in clean_src_vectors or word in clean_target_vectors] | ||
124 | W_common = [] | ||
125 | for w in common: | ||
126 | if w in clean_src_vectors: | ||
127 | W_common.append(np.array(clean_src_vectors[w])) | ||
128 | else: | ||
129 | W_common.append(np.array(clean_target_vectors[w])) | ||
130 | |||
131 | print(f'{source_lang} - {target_lang}: the vocabulary size is {len(W_common)}') | ||
132 | |||
133 | from sklearn.preprocessing import normalize | ||
134 | W_common = np.array(W_common) | ||
135 | W_common = normalize(W_common) | ||
136 | vect = TfidfVectorizer(vocabulary=common, dtype=np.double, norm=None) | ||
137 | vect.fit(clean_src_corpus + clean_target_corpus) | ||
138 | X_train_idf = vect.transform(clean_src_corpus) | ||
139 | X_test_idf = vect.transform(clean_target_corpus) | ||
140 | |||
141 | vect_tf = CountVectorizer(vocabulary=common, dtype=np.double) | ||
142 | vect_tf.fit(clean_src_corpus + clean_target_corpus) | ||
143 | X_train_tf = vect_tf.transform(clean_src_corpus) | ||
144 | X_test_tf = vect_tf.transform(clean_target_corpus) | ||
145 | |||
146 | import ot | ||
147 | from sklearn.neighbors import KNeighborsClassifier | ||
148 | from sklearn.metrics import euclidean_distances | ||
149 | from sklearn.externals.joblib import Parallel, delayed | ||
150 | from sklearn.utils import check_array | ||
151 | from sklearn.metrics.scorer import check_scoring | ||
152 | from pathos.multiprocessing import ProcessingPool as Pool | ||
153 | from sklearn.metrics import euclidean_distances | ||
154 | |||
155 | class WassersteinDistances(KNeighborsClassifier): | ||
156 | """ | ||
157 | Implements a nearest neighbors classifier for input distributions using the Wasserstein distance as metric. | ||
158 | Source and target distributions are l_1 normalized before computing the Wasserstein distance. | ||
159 | Wasserstein is parametrized by the distances between the individual points of the distributions. | ||
160 | In this work, we propose to use cross-lingual embeddings for calculating these distances. | ||
161 | |||
162 | """ | ||
163 | def __init__(self, W_embed, n_neighbors=1, n_jobs=1, verbose=False, sinkhorn= False, sinkhorn_reg=0.1): | ||
164 | """ | ||
165 | Initialization of the class. | ||
166 | Arguments | ||
167 | --------- | ||
168 | W_embed: embeddings of the words, np.array | ||
169 | verbose: True/False | ||
170 | """ | ||
171 | self.sinkhorn = sinkhorn | ||
172 | self.sinkhorn_reg = sinkhorn_reg | ||
173 | self.W_embed = W_embed | ||
174 | self.verbose = verbose | ||
175 | super(WassersteinDistances, self).__init__(n_neighbors=n_neighbors, n_jobs=n_jobs, metric='precomputed', algorithm='brute') | ||
176 | |||
177 | def _wmd(self, i, row, X_train): | ||
178 | union_idx = np.union1d(X_train[i].indices, row.indices) | ||
179 | W_minimal = self.W_embed[union_idx] | ||
180 | W_dist = euclidean_distances(W_minimal) | ||
181 | bow_i = X_train[i, union_idx].A.ravel() | ||
182 | bow_j = row[:, union_idx].A.ravel() | ||
183 | if self.sinkhorn: | ||
184 | return ot.sinkhorn2(bow_i, bow_j, W_dist, self.sinkhorn_reg, numItermax=50, method='sinkhorn_stabilized',)[0] | ||
185 | else: | ||
186 | return ot.emd2(bow_i, bow_j, W_dist) | ||
187 | |||
188 | def _wmd_row(self, row): | ||
189 | X_train = self._fit_X | ||
190 | n_samples_train = X_train.shape[0] | ||
191 | return [self._wmd(i, row, X_train) for i in range(n_samples_train)] | ||
192 | |||
193 | def _pairwise_wmd(self, X_test, X_train=None): | ||
194 | n_samples_test = X_test.shape[0] | ||
195 | |||
196 | if X_train is None: | ||
197 | X_train = self._fit_X | ||
198 | pool = Pool(nodes=self.n_jobs) # Parallelization of the calculation of the distances | ||
199 | dist = pool.map(self._wmd_row, X_test) | ||
200 | return np.array(dist) | ||
201 | |||
202 | def fit(self, X, y): | ||
203 | X = check_array(X, accept_sparse='csr', copy=True) | ||
204 | X = normalize(X, norm='l1', copy=False) | ||
205 | return super(WassersteinDistances, self).fit(X, y) | ||
206 | |||
207 | def predict(self, X): | ||
208 | X = check_array(X, accept_sparse='csr', copy=True) | ||
209 | X = normalize(X, norm='l1', copy=False) | ||
210 | dist = self._pairwise_wmd(X) | ||
211 | return super(WassersteinDistances, self).predict(dist) | ||
212 | |||
213 | def kneighbors(self, X, n_neighbors=1): | ||
214 | X = check_array(X, accept_sparse='csr', copy=True) | ||
215 | X = normalize(X, norm='l1', copy=False) | ||
216 | dist = self._pairwise_wmd(X) | ||
217 | return super(WassersteinDistances, self).kneighbors(dist, n_neighbors) | ||
218 | |||
219 | def mrr_precision_at_k(golden, preds, k_list=[1,]): | ||
220 | """ | ||
221 | Calculates Mean Reciprocal Error and Hits@1 == Precision@1 | ||
222 | """ | ||
223 | my_score = 0 | ||
224 | precision_at = np.zeros(len(k_list)) | ||
225 | for key, elem in enumerate(golden): | ||
226 | if elem in preds[key]: | ||
227 | location = np.where(preds[key]==elem)[0][0] | ||
228 | my_score += 1/(1+ location) | ||
229 | for k_index, k_value in enumerate(k_list): | ||
230 | if location < k_value: | ||
231 | precision_at[k_index] += 1 | ||
232 | return my_score/len(golden), (precision_at/len(golden))[0] | ||
233 | |||
234 | print(f'WMD - tfidf: {source_lang} - {target_lang}') | ||
235 | clf = WassersteinDistances(W_embed=W_common, n_neighbors=5, n_jobs=14) | ||
236 | clf.fit(X_train_idf[:instances], np.ones(instances)) | ||
237 | dist, preds = clf.kneighbors(X_test_idf[:instances], n_neighbors=instances) | ||
238 | mrr, p_at_1 = mrr_precision_at_k(list(range(len(preds))), preds) | ||
239 | print(f'MRR: {mrr} | Precision @ 1: {p_at_1}') | ||
240 | |||
241 | import csv | ||
242 | percentage = p_at_1 * 100 | ||
243 | fields = [f'{source_lang}', f'{target_lang}', f'{instances}', f'{mrr}', f'{p_at_1}', f'{percentage}'] | ||
244 | with open('/home/syigit/multilang_results/wmd_retrieval_result.csv', 'a') as f: | ||
245 | writer = csv.writer(f) | ||
246 | writer.writerow(fields) | ||
247 | |||
248 | print(f'Sinkhorn - tfidf: {source_lang} - {target_lang}') | ||
249 | clf = WassersteinDistances(W_embed=W_common, n_neighbors=5, n_jobs=14, sinkhorn=True) | ||
250 | clf.fit(X_train_idf[:instances], np.ones(instances)) | ||
251 | dist, preds = clf.kneighbors(X_test_idf[:instances], n_neighbors=instances) | ||
252 | mrr, p_at_1 = mrr_precision_at_k(list(range(len(preds))), preds) | ||
253 | print(f'MRR: {mrr} | Precision @ 1: {p_at_1}') | ||
254 | |||
255 | percentage = p_at_1 * 100 | ||
256 | fields = [f'{source_lang}', f'{target_lang}', f'{instances}', f'{mrr}', f'{p_at_1}', f'{percentage}'] | ||
257 | with open('/home/syigit/multilang_results/sinkhorn_retrieval_result.csv', 'a') as f: | ||
258 | writer = csv.writer(f) | ||
259 | writer.writerow(fields) | ||
diff --git a/Wass_Matcher.py b/Wass_Matcher.py new file mode 100644 index 0000000..44b29eb --- /dev/null +++ b/Wass_Matcher.py | |||
@@ -0,0 +1,76 @@ | |||
1 | import ot | ||
2 | from sklearn.preprocessing import normalize | ||
3 | from lapjv import lapjv | ||
4 | from sklearn.neighbors import KNeighborsClassifier | ||
5 | from sklearn.metrics import euclidean_distances | ||
6 | from sklearn.externals.joblib import Parallel, delayed | ||
7 | from sklearn.utils import check_array | ||
8 | from sklearn.metrics.scorer import check_scoring | ||
9 | from pathos.multiprocessing import ProcessingPool as Pool | ||
10 | from sklearn.metrics import euclidean_distances | ||
11 | import numpy as np | ||
12 | |||
13 | class Wasserstein_Matcher(KNeighborsClassifier): | ||
14 | """ | ||
15 | Implements a nearest neighbors classifier for input distributions using the Wasserstein distance as metric. | ||
16 | Source and target distributions are l_1 normalized before computing the Wasserstein distance. | ||
17 | Wasserstein is parametrized by the distances between the individual points of the distributions. | ||
18 | """ | ||
19 | def __init__(self, W_embed, n_neighbors=1, n_jobs=1, verbose=False, sinkhorn= False, sinkhorn_reg=0.1): | ||
20 | """ | ||
21 | Initialization of the class. | ||
22 | Arguments | ||
23 | --------- | ||
24 | W_embed: embeddings of the words, np.array | ||
25 | verbose: True/False | ||
26 | """ | ||
27 | self.sinkhorn = sinkhorn | ||
28 | self.sinkhorn_reg = sinkhorn_reg | ||
29 | self.W_embed = W_embed | ||
30 | self.verbose = verbose | ||
31 | super(Wasserstein_Matcher, self).__init__(n_neighbors=n_neighbors, n_jobs=n_jobs, metric='precomputed', algorithm='brute') | ||
32 | |||
33 | def _wmd(self, i, row, X_train): | ||
34 | union_idx = np.union1d(X_train[i].indices, row.indices) | ||
35 | W_minimal = self.W_embed[union_idx] | ||
36 | W_dist = euclidean_distances(W_minimal) | ||
37 | bow_i = X_train[i, union_idx].A.ravel() | ||
38 | bow_j = row[:, union_idx].A.ravel() | ||
39 | if self.sinkhorn: | ||
40 | return ot.sinkhorn2(bow_i, bow_j, W_dist, self.sinkhorn_reg, numItermax=50, method='sinkhorn_stabilized',)[0] | ||
41 | else: | ||
42 | return ot.emd2(bow_i, bow_j, W_dist) | ||
43 | |||
44 | def _wmd_row(self, row): | ||
45 | X_train = self._fit_X | ||
46 | n_samples_train = X_train.shape[0] | ||
47 | return [self._wmd(i, row, X_train) for i in range(n_samples_train)] | ||
48 | |||
49 | def _pairwise_wmd(self, X_test, X_train=None): | ||
50 | n_samples_test = X_test.shape[0] | ||
51 | |||
52 | if X_train is None: | ||
53 | X_train = self._fit_X | ||
54 | pool = Pool(nodes=self.n_jobs) # Parallelization of the calculation of the distances | ||
55 | dist = pool.map(self._wmd_row, X_test) | ||
56 | return np.array(dist) | ||
57 | |||
58 | def fit(self, X, y): # X_train_idf | ||
59 | X = check_array(X, accept_sparse='csr', copy=True) # check if array is sparse | ||
60 | X = normalize(X, norm='l1', copy=False) | ||
61 | return super(Wasserstein_Matcher, self).fit(X, y) # X_train_idf, np_ones(document collection size) | ||
62 | |||
63 | def predict(self, X): | ||
64 | X = check_array(X, accept_sparse='csr', copy=True) | ||
65 | X = normalize(X, norm='l1', copy=False) | ||
66 | dist = self._pairwise_wmd(X) | ||
67 | dist = dist * 1000 # for lapjv, small floating point numbers are evil | ||
68 | return super(Wasserstein_Matcher, self).predict(dist) | ||
69 | |||
70 | def kneighbors(self, X, n_neighbors=1): # X : X_train_idf | ||
71 | X = check_array(X, accept_sparse='csr', copy=True) | ||
72 | X = normalize(X, norm='l1', copy=False) | ||
73 | dist = self._pairwise_wmd(X) | ||
74 | dist = dist * 1000 # for lapjv, small floating point numbers are evil | ||
75 | return lapjv(dist) # and here is the matching part | ||
76 | |||
diff --git a/Wass_Retriever.py b/Wass_Retriever.py new file mode 100644 index 0000000..036cf93 --- /dev/null +++ b/Wass_Retriever.py | |||
@@ -0,0 +1,73 @@ | |||
1 | import ot | ||
2 | from sklearn.preprocessing import normalize | ||
3 | from sklearn.neighbors import KNeighborsClassifier | ||
4 | from sklearn.metrics import euclidean_distances | ||
5 | from sklearn.externals.joblib import Parallel, delayed | ||
6 | from sklearn.utils import check_array | ||
7 | from sklearn.metrics.scorer import check_scoring | ||
8 | from pathos.multiprocessing import ProcessingPool as Pool | ||
9 | from sklearn.metrics import euclidean_distances | ||
10 | import numpy as np | ||
11 | |||
12 | class Wasserstein_Retriever(KNeighborsClassifier): | ||
13 | """ | ||
14 | Implements a nearest neighbors classifier for input distributions using the Wasserstein distance as metric. | ||
15 | Source and target distributions are l_1 normalized before computing the Wasserstein distance. | ||
16 | Wasserstein is parametrized by the distances between the individual points of the distributions. | ||
17 | """ | ||
18 | def __init__(self, W_embed, n_neighbors=1, n_jobs=1, verbose=False, sinkhorn= False, sinkhorn_reg=0.1): | ||
19 | """ | ||
20 | Initialization of the class. | ||
21 | Arguments | ||
22 | --------- | ||
23 | W_embed: embeddings of the words, np.array | ||
24 | verbose: True/False | ||
25 | """ | ||
26 | self.sinkhorn = sinkhorn | ||
27 | self.sinkhorn_reg = sinkhorn_reg | ||
28 | self.W_embed = W_embed | ||
29 | self.verbose = verbose | ||
30 | super(Wasserstein_Retriever, self).__init__(n_neighbors=n_neighbors, n_jobs=n_jobs, metric='precomputed', algorithm='brute') | ||
31 | |||
32 | def _wmd(self, i, row, X_train): | ||
33 | union_idx = np.union1d(X_train[i].indices, row.indices) | ||
34 | W_minimal = self.W_embed[union_idx] | ||
35 | W_dist = euclidean_distances(W_minimal) | ||
36 | bow_i = X_train[i, union_idx].A.ravel() | ||
37 | bow_j = row[:, union_idx].A.ravel() | ||
38 | if self.sinkhorn: | ||
39 | return ot.sinkhorn2(bow_i, bow_j, W_dist, self.sinkhorn_reg, numItermax=50, method='sinkhorn_stabilized',)[0] | ||
40 | else: | ||
41 | return ot.emd2(bow_i, bow_j, W_dist) | ||
42 | |||
43 | def _wmd_row(self, row): | ||
44 | X_train = self._fit_X | ||
45 | n_samples_train = X_train.shape[0] | ||
46 | return [self._wmd(i, row, X_train) for i in range(n_samples_train)] | ||
47 | |||
48 | def _pairwise_wmd(self, X_test, X_train=None): | ||
49 | n_samples_test = X_test.shape[0] | ||
50 | |||
51 | if X_train is None: | ||
52 | X_train = self._fit_X | ||
53 | pool = Pool(nodes=self.n_jobs) # Parallelization of the calculation of the distances | ||
54 | dist = pool.map(self._wmd_row, X_test) | ||
55 | return np.array(dist) | ||
56 | |||
57 | def fit(self, X, y): | ||
58 | X = check_array(X, accept_sparse='csr', copy=True) | ||
59 | X = normalize(X, norm='l1', copy=False) | ||
60 | return super(Wasserstein_Retriever, self).fit(X, y) | ||
61 | |||
62 | def predict(self, X): | ||
63 | X = check_array(X, accept_sparse='csr', copy=True) | ||
64 | X = normalize(X, norm='l1', copy=False) | ||
65 | dist = self._pairwise_wmd(X) | ||
66 | return super(Wasserstein_Retriever, self).predict(dist) | ||
67 | |||
68 | def kneighbors(self, X, n_neighbors=1): | ||
69 | X = check_array(X, accept_sparse='csr', copy=True) | ||
70 | X = normalize(X, norm='l1', copy=False) | ||
71 | dist = self._pairwise_wmd(X) | ||
72 | return super(Wasserstein_Retriever, self).kneighbors(dist, n_neighbors) | ||
73 | |||
diff --git a/sentence_emb_matching.py b/sentence_emb_matching.py new file mode 100644 index 0000000..38812d7 --- /dev/null +++ b/sentence_emb_matching.py | |||
@@ -0,0 +1,153 @@ | |||
1 | import argparse | ||
2 | |||
3 | parser = argparse.ArgumentParser(description='run matching using sentence embeddings and cosine similarity') | ||
4 | parser.add_argument('source_lang', help='source language short name') | ||
5 | parser.add_argument('target_lang', help='target language short name') | ||
6 | parser.add_argument('source_vector', help='path of the source vector') | ||
7 | parser.add_argument('target_vector', help='path of the target vector') | ||
8 | parser.add_argument('source_defs', help='path of the source definitions') | ||
9 | parser.add_argument('target_defs', help='path of the target definitions') | ||
10 | parser.add_argument('-n', '--instances', help='number of instances in each language to retrieve', default=2000, type=int) | ||
11 | |||
12 | args = parser.parse_args() | ||
13 | |||
14 | source_lang = args.source_lang | ||
15 | target_lang = args.target_lang | ||
16 | |||
17 | def load_embeddings(path, dimension = 300): | ||
18 | """ | ||
19 | Loads the embeddings from a word2vec formatted file. | ||
20 | The first line may or may not include the word count and dimension | ||
21 | """ | ||
22 | vectors = {} | ||
23 | with open(path, mode='r', encoding='utf8') as fp: | ||
24 | first_line = fp.readline().rstrip('\n') | ||
25 | if first_line.count(' ') == 1: # includes the "word_count dimension" information | ||
26 | (word_count, dimension) = map(int, first_line.split()) | ||
27 | else: # assume the file only contains vectors | ||
28 | fp.seek(0) | ||
29 | for line in fp: | ||
30 | elems = line.split() | ||
31 | vectors[" ".join(elems[:-dimension])] = " ".join(elems[-dimension:]) | ||
32 | return vectors | ||
33 | |||
34 | source_vectors_filename = args.source_vector | ||
35 | target_vectors_filename = args.target_vector | ||
36 | vectors_source = load_embeddings(source_vectors_filename) | ||
37 | vectors_target = load_embeddings(target_vectors_filename) | ||
38 | |||
39 | source_defs_filename = args.source_defs | ||
40 | target_defs_filename = args.target_defs | ||
41 | defs_source = [line.rstrip('\n') for line in open(source_defs_filename, encoding='utf8')] | ||
42 | defs_target = [line.rstrip('\n') for line in open(target_defs_filename, encoding='utf8')] | ||
43 | |||
44 | import numpy as np | ||
45 | from mosestokenizer import * | ||
46 | |||
47 | def clean_corpus_using_embeddings_vocabulary( | ||
48 | embeddings_dictionary, | ||
49 | corpus, | ||
50 | vectors, | ||
51 | language, | ||
52 | ): | ||
53 | ''' | ||
54 | Cleans corpus using the dictionary of embeddings. | ||
55 | Any word without an associated embedding in the dictionary is ignored. | ||
56 | ''' | ||
57 | clean_corpus, clean_vectors, keys = [], {}, [] | ||
58 | words_we_want = set(embeddings_dictionary) | ||
59 | tokenize = MosesTokenizer(language) | ||
60 | for key, doc in enumerate(corpus): | ||
61 | clean_doc = [] | ||
62 | words = tokenize(doc) | ||
63 | for word in words: | ||
64 | if word in words_we_want: | ||
65 | clean_doc.append(word) | ||
66 | clean_vectors[word] = np.array(vectors[word].split()).astype(np.float) | ||
67 | if len(clean_doc) > 3 and len(clean_doc) < 25: | ||
68 | keys.append(key) | ||
69 | clean_corpus.append(' '.join(clean_doc)) | ||
70 | tokenize.close() | ||
71 | return np.array(clean_corpus), clean_vectors, keys | ||
72 | |||
73 | clean_src_corpus, clean_src_vectors, src_keys = clean_corpus_using_embeddings_vocabulary( | ||
74 | set(vectors_source.keys()), | ||
75 | defs_source, | ||
76 | vectors_source, | ||
77 | source_lang, | ||
78 | ) | ||
79 | |||
80 | clean_target_corpus, clean_target_vectors, target_keys = clean_corpus_using_embeddings_vocabulary( | ||
81 | set(vectors_target.keys()), | ||
82 | defs_target, | ||
83 | vectors_target, | ||
84 | target_lang, | ||
85 | ) | ||
86 | |||
87 | import random | ||
88 | take = args.instances | ||
89 | |||
90 | common_keys = set(src_keys).intersection(set(target_keys)) | ||
91 | take = min(len(common_keys), take) # you can't sample more than length | ||
92 | experiment_keys = random.sample(common_keys, take) | ||
93 | |||
94 | instances = len(experiment_keys) | ||
95 | |||
96 | clean_src_corpus = list(clean_src_corpus[experiment_keys]) | ||
97 | clean_target_corpus = list(clean_target_corpus[experiment_keys]) | ||
98 | |||
99 | print(f'{source_lang} - {target_lang} : document sizes: {len(clean_src_corpus)}, {len(clean_target_corpus)}') | ||
100 | |||
101 | del vectors_source, vectors_target, defs_source, defs_target | ||
102 | |||
103 | from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer | ||
104 | |||
105 | vocab_counter = CountVectorizer().fit(clean_src_corpus + clean_target_corpus) | ||
106 | common = [w for w in vocab_counter.get_feature_names() if w in clean_src_vectors or w in clean_target_vectors] | ||
107 | W_common = [] | ||
108 | |||
109 | for w in common: | ||
110 | if w in clean_src_vectors: | ||
111 | W_common.append(np.array(clean_src_vectors[w])) | ||
112 | else: | ||
113 | W_common.append(np.array(clean_target_vectors[w])) | ||
114 | |||
115 | print(f'{source_lang} - {target_lang}: the vocabulary size is {len(W_common)}') | ||
116 | |||
117 | from sklearn.preprocessing import normalize | ||
118 | W_common = np.array(W_common) | ||
119 | W_common = normalize(W_common) # default is l2 | ||
120 | |||
121 | vect_tfidf = TfidfVectorizer(vocabulary=common, dtype=np.double, norm='l2') | ||
122 | vect_tfidf.fit(clean_src_corpus + clean_target_corpus) | ||
123 | X_idf_source = vect_tfidf.transform(clean_src_corpus) | ||
124 | X_idf_target = vect_tfidf.transform(clean_target_corpus) | ||
125 | |||
126 | print(f'Matrices are {X_idf_source.shape} and {W_common.shape}') | ||
127 | print(f'The dimensions are {X_idf_source.ndim} and {W_common.ndim}') | ||
128 | |||
129 | X_idf_source_array = X_idf_source.toarray() | ||
130 | X_idf_target_array = X_idf_target.toarray() | ||
131 | S_emb_source = np.matmul(X_idf_source_array, W_common) | ||
132 | S_emb_target = np.matmul(X_idf_target_array, W_common) | ||
133 | |||
134 | S_emb_target_transpose = np.transpose(S_emb_target) | ||
135 | |||
136 | cost_matrix = np.matmul(S_emb_source, S_emb_target_transpose) | ||
137 | |||
138 | from lapjv import lapjv | ||
139 | cost_matrix = cost_matrix * -1000 | ||
140 | row_ind, col_ind, a = lapjv(cost_matrix, verbose=False) | ||
141 | |||
142 | result = zip(row_ind, col_ind) | ||
143 | hit_one = len([x for x,y in result if x == y]) | ||
144 | print(f'{hit_one} definitions have been mapped correctly, shape of cost matrix: {str(cost_matrix.shape)}') | ||
145 | |||
146 | import csv | ||
147 | percentage = hit_one / instances * 100 | ||
148 | fields = [f'{source_lang}', f'{target_lang}', f'{instances}', f'{hit_one}', f'{percentage}'] | ||
149 | |||
150 | with open('semb_matcing.csv', 'a') as f: | ||
151 | writer = csv.writer(f) | ||
152 | writer.writerow(fields) | ||
153 | |||
diff --git a/sentence_emb_retrieval.py b/sentence_emb_retrieval.py new file mode 100644 index 0000000..63ebcdc --- /dev/null +++ b/sentence_emb_retrieval.py | |||
@@ -0,0 +1,151 @@ | |||
1 | import argparse | ||
2 | |||
3 | parser = argparse.ArgumentParser(description='Run Retrieval using Sentence Embedding + Cosine') | ||
4 | parser.add_argument('source_lang', help='source language short name') | ||
5 | parser.add_argument('target_lang', help='target language short name') | ||
6 | parser.add_argument('source_vector', help='path of the source vector') | ||
7 | parser.add_argument('target_vector', help='path of the target vector') | ||
8 | parser.add_argument('source_defs', help='path of the source definitions') | ||
9 | parser.add_argument('target_defs', help='path of the target definitions') | ||
10 | parser.add_argument('-n', '--instances', help='number of instances in each language to retrieve', default=1000, type=int) | ||
11 | args = parser.parse_args() | ||
12 | |||
13 | source_lang = args.source_lang | ||
14 | target_lang = args.target_lang | ||
15 | |||
16 | def load_embeddings(path, dimension = 300): | ||
17 | """ | ||
18 | Loads the embeddings from a word2vec formatted file. | ||
19 | The first line may or may not include the word count and dimension | ||
20 | """ | ||
21 | vectors = {} | ||
22 | with open(path, mode='r', encoding='utf8') as fp: | ||
23 | first_line = fp.readline().rstrip('\n') | ||
24 | if first_line.count(' ') == 1: # includes the "word_count dimension" information | ||
25 | (word_count, dimension) = map(int, first_line.split()) | ||
26 | else: # assume the file only contains vectors | ||
27 | fp.seek(0) | ||
28 | for line in fp: | ||
29 | elems = line.split() | ||
30 | vectors[" ".join(elems[:-dimension])] = " ".join(elems[-dimension:]) | ||
31 | return vectors | ||
32 | |||
33 | lang_source = args.source_lang | ||
34 | lang_target = args.target_lang | ||
35 | |||
36 | vectors_filename_source = args.source_vector | ||
37 | vectors_filename_target = args.target_vector | ||
38 | |||
39 | vectors_source = load_embeddings(vectors_filename_source) | ||
40 | vectors_target = load_embeddings(vectors_filename_target) | ||
41 | |||
42 | defs_filename_source = args.source_defs | ||
43 | defs_filename_target = args.target_defs | ||
44 | defs_source = [line.rstrip('\n') for line in open(defs_filename_source, encoding='utf8')] | ||
45 | defs_target = [line.rstrip('\n') for line in open(defs_filename_target, encoding='utf8')] | ||
46 | |||
47 | print('Read {} {} documents and {} {} documents'.format(len(defs_source), lang_source, len(defs_target), lang_target)) | ||
48 | |||
49 | import numpy as np | ||
50 | from mosestokenizer import * | ||
51 | |||
52 | def clean_corpus_using_embeddings_vocabulary( | ||
53 | embeddings_dictionary, | ||
54 | corpus, | ||
55 | vectors, | ||
56 | language, | ||
57 | ): | ||
58 | ''' | ||
59 | Cleans corpus using the dictionary of embeddings. | ||
60 | Any word without an associated embedding in the dictionary is ignored. | ||
61 | Adds '__target-language' and '__source-language' at the end of the words according to their language. | ||
62 | ''' | ||
63 | clean_corpus, clean_vectors, keys = [], {}, [] | ||
64 | words_we_want = set(embeddings_dictionary) | ||
65 | tokenize = MosesTokenizer(language) | ||
66 | for key, doc in enumerate(corpus): | ||
67 | clean_doc = [] | ||
68 | words = tokenize(doc) | ||
69 | for word in words: | ||
70 | if word in words_we_want: | ||
71 | clean_doc.append(word + '__%s' % language) | ||
72 | clean_vectors[word + '__%s' % language] = np.array(vectors[word].split()).astype(np.float) | ||
73 | if len(clean_doc) > 3 and len(clean_doc) < 25: | ||
74 | keys.append(key) | ||
75 | clean_corpus.append(' '.join(clean_doc)) | ||
76 | tokenize.close() | ||
77 | return np.array(clean_corpus), clean_vectors, keys | ||
78 | |||
79 | clean_corpus_source, clean_vectors_source, keys_source = clean_corpus_using_embeddings_vocabulary( | ||
80 | set(vectors_source.keys()), | ||
81 | defs_source, | ||
82 | vectors_source, | ||
83 | lang_source, | ||
84 | ) | ||
85 | |||
86 | clean_corpus_target, clean_vectors_target, keys_target = clean_corpus_using_embeddings_vocabulary( | ||
87 | set(vectors_target.keys()), | ||
88 | defs_target, | ||
89 | vectors_target, | ||
90 | lang_target, | ||
91 | ) | ||
92 | |||
93 | import random | ||
94 | take = args.instances | ||
95 | |||
96 | common_keys = set(keys_source).intersection(set(keys_target)) # definitions that fit the above requirements | ||
97 | take = min(len(common_keys), take) # you can't sample more than length | ||
98 | experiment_keys = random.sample(common_keys, take) | ||
99 | |||
100 | instances = len(experiment_keys) | ||
101 | |||
102 | clean_corpus_source = list(clean_corpus_source[experiment_keys]) | ||
103 | clean_corpus_target = list(clean_corpus_target[experiment_keys]) | ||
104 | print(f'{source_lang} - {target_lang} : document sizes: {len(clean_corpus_source)}, {len(clean_corpus_target)}') | ||
105 | |||
106 | del vectors_source, vectors_target, defs_source, defs_target | ||
107 | |||
108 | from sklearn.feature_extraction.text import CountVectorizer | ||
109 | from sklearn.feature_extraction.text import TfidfVectorizer | ||
110 | |||
111 | vocab_counter = CountVectorizer().fit(clean_corpus_source + clean_corpus_target) | ||
112 | common = [w for w in vocab_counter.get_feature_names() if w in clean_vectors_source or w in clean_vectors_target] | ||
113 | |||
114 | W_common = [] | ||
115 | for w in common: | ||
116 | if w in clean_vectors_source: | ||
117 | W_common.append(np.array(clean_vectors_source[w])) | ||
118 | else: | ||
119 | W_common.append(np.array(clean_vectors_target[w])) | ||
120 | |||
121 | print('The vocabulary size is %d' % (len(W_common))) | ||
122 | |||
123 | from sklearn.preprocessing import normalize | ||
124 | W_common = np.array(W_common) | ||
125 | W_common = normalize(W_common) # default is l2 | ||
126 | |||
127 | vect_tfidf = TfidfVectorizer(vocabulary=common, dtype=np.double, norm='l2') | ||
128 | vect_tfidf.fit(clean_corpus_source + clean_corpus_target) | ||
129 | X_idf_source = vect_tfidf.transform(clean_corpus_source) | ||
130 | X_idf_target = vect_tfidf.transform(clean_corpus_target) | ||
131 | |||
132 | print(f'Matrices are {X_idf_source.shape} and {W_common.shape}') | ||
133 | print(f'The dimensions are {X_idf_source.ndim} and {W_common.ndim}') | ||
134 | |||
135 | X_idf_source_array = X_idf_source.toarray() | ||
136 | X_idf_target_array = X_idf_target.toarray() | ||
137 | S_emb_source = np.matmul(X_idf_source_array, W_common) | ||
138 | S_emb_target = np.matmul(X_idf_target_array, W_common) | ||
139 | |||
140 | S_emb_target_transpose = np.transpose(S_emb_target) | ||
141 | |||
142 | cost_matrix = np.matmul(S_emb_source, S_emb_target_transpose) | ||
143 | |||
144 | hit_at_one = len([x for x,y in enumerate(cost_matrix.argmax(axis=1)) if x == y]) | ||
145 | |||
146 | import csv | ||
147 | percentage = hit_at_one / instances * 100 | ||
148 | fields = [f'{source_lang}', f'{target_lang}', f'{instances}', f'{hit_at_one}', f'{percentage}'] | ||
149 | with open('/home/syigit/multilang_results/sentence_emb_retrieval_axis_1.csv', 'a') as f: | ||
150 | writer = csv.writer(f) | ||
151 | writer.writerow(fields) | ||