This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 544
/
wordsim.py
242 lines (205 loc) · 8.11 KB
/
wordsim.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
241
242
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
from logging import getLogger
import numpy as np
import torch
from scipy.stats import spearmanr
MONOLINGUAL_EVAL_PATH = 'data/monolingual'
SEMEVAL17_EVAL_PATH = 'data/crosslingual/wordsim'
logger = getLogger()
def get_word_pairs(path, lower=True):
"""
Return a list of (word1, word2, score) tuples from a word similarity file.
"""
assert os.path.isfile(path) and type(lower) is bool
word_pairs = []
with open(path) as f:
for line in f:
line = line.rstrip()
line = line.lower() if lower else line
line = line.split()
# ignore phrases, only consider words
if len(line) != 3:
assert len(line) > 3
assert 'SEMEVAL17' in os.path.basename(path) or 'EN-IT_MWS353' in path
continue
word_pairs.append((line[0], line[1], float(line[2])))
return word_pairs
def get_word_id(word, word2id, lower):
"""
Get a word ID.
If the model does not use lowercase and the evaluation file is lowercased,
we might be able to find an associated word.
"""
assert type(lower) is bool
word_id = word2id.get(word)
if word_id is None and not lower:
word_id = word2id.get(word.capitalize())
if word_id is None and not lower:
word_id = word2id.get(word.title())
return word_id
def get_spearman_rho(word2id1, embeddings1, path, lower,
word2id2=None, embeddings2=None):
"""
Compute monolingual or cross-lingual word similarity score.
"""
assert not ((word2id2 is None) ^ (embeddings2 is None))
word2id2 = word2id1 if word2id2 is None else word2id2
embeddings2 = embeddings1 if embeddings2 is None else embeddings2
assert len(word2id1) == embeddings1.shape[0]
assert len(word2id2) == embeddings2.shape[0]
assert type(lower) is bool
word_pairs = get_word_pairs(path)
not_found = 0
pred = []
gold = []
for word1, word2, similarity in word_pairs:
id1 = get_word_id(word1, word2id1, lower)
id2 = get_word_id(word2, word2id2, lower)
if id1 is None or id2 is None:
not_found += 1
continue
u = embeddings1[id1]
v = embeddings2[id2]
score = u.dot(v) / (np.linalg.norm(u) * np.linalg.norm(v))
gold.append(similarity)
pred.append(score)
return spearmanr(gold, pred).correlation, len(gold), not_found
def get_wordsim_scores(language, word2id, embeddings, lower=True):
"""
Return monolingual word similarity scores.
"""
dirpath = os.path.join(MONOLINGUAL_EVAL_PATH, language)
if not os.path.isdir(dirpath):
return None
scores = {}
separator = "=" * (30 + 1 + 10 + 1 + 13 + 1 + 12)
pattern = "%30s %10s %13s %12s"
logger.info(separator)
logger.info(pattern % ("Dataset", "Found", "Not found", "Rho"))
logger.info(separator)
for filename in list(os.listdir(dirpath)):
if filename.startswith('%s_' % (language.upper())):
filepath = os.path.join(dirpath, filename)
coeff, found, not_found = get_spearman_rho(word2id, embeddings, filepath, lower)
logger.info(pattern % (filename[:-4], str(found), str(not_found), "%.4f" % coeff))
scores[filename[:-4]] = coeff
logger.info(separator)
return scores
def get_wordanalogy_scores(language, word2id, embeddings, lower):
"""
Return (english) word analogy score
"""
dirpath = os.path.join(MONOLINGUAL_EVAL_PATH, language)
assert os.path.isdir(dirpath) and type(lower) is bool
# normalize word embeddings
embeddings = embeddings / np.sqrt((embeddings ** 2).sum(1))[:, None]
# scores by category
scores = {}
word_ids = {}
queries = {}
for line in open(os.path.join(dirpath, 'questions-words.txt'), 'r'):
# new line
line = line.rstrip()
if lower:
line = line.lower()
# new category
if ":" in line:
assert line[1] == ' '
category = line[2:]
assert category not in scores
scores[category] = {'n_found': 0, 'n_not_found': 0, 'n_correct': 0}
word_ids[category] = []
queries[category] = []
continue
# get word IDs
assert len(line.split()) == 4, line
word1, word2, word3, word4 = line.split()
word_id1 = get_word_id(word1, word2id, lower)
word_id2 = get_word_id(word2, word2id, lower)
word_id3 = get_word_id(word3, word2id, lower)
word_id4 = get_word_id(word4, word2id, lower)
# if at least one word is not found
if any(x is None for x in [word_id1, word_id2, word_id3, word_id4]):
scores[category]['n_not_found'] += 1
continue
else:
scores[category]['n_found'] += 1
word_ids[category].append([word_id1, word_id2, word_id3, word_id4])
# generate query vector and get nearest neighbors
query = embeddings[word_id1] - embeddings[word_id2] + embeddings[word_id4]
query = query / np.linalg.norm(query)
queries[category].append(query)
# Compute score for each category
for cat in queries:
qs = torch.from_numpy(np.vstack(queries[cat]))
keys = torch.from_numpy(embeddings.T)
values = qs.mm(keys).cpu().numpy()
# be sure we do not select input words
for i, ws in enumerate(word_ids[cat]):
for wid in [ws[0], ws[1], ws[3]]:
values[i, wid] = -1e9
scores[cat]['n_correct'] = np.sum(values.argmax(axis=1) == [ws[2] for ws in word_ids[cat]])
# pretty print
separator = "=" * (30 + 1 + 10 + 1 + 13 + 1 + 12)
pattern = "%30s %10s %13s %12s"
logger.info(separator)
logger.info(pattern % ("Category", "Found", "Not found", "Accuracy"))
logger.info(separator)
# compute and log accuracies
accuracies = {}
for k in sorted(scores.keys()):
v = scores[k]
accuracies[k] = float(v['n_correct']) / max(v['n_found'], 1)
logger.info(pattern % (k, str(v['n_found']), str(v['n_not_found']), "%.4f" % accuracies[k]))
logger.info(separator)
return accuracies
def get_crosslingual_wordsim_scores(lang1, word2id1, embeddings1,
lang2, word2id2, embeddings2, lower=True):
"""
Return cross-lingual word similarity scores.
"""
if lang1 > lang2:
return get_crosslingual_wordsim_scores(lang2, word2id2, embeddings2,
lang1, word2id1, embeddings1, lower)
dirpath = os.path.join(SEMEVAL17_EVAL_PATH, '%s-%s' % (lang1, lang2))
if not os.path.isdir(dirpath):
return None
scores = {}
separator = "=" * (30 + 1 + 10 + 1 + 13 + 1 + 12)
pattern = "%30s %10s %13s %12s"
logger.info(separator)
logger.info(pattern % ("Dataset", "Found", "Not found", "Rho"))
logger.info(separator)
for filename in list(os.listdir(dirpath)):
if 'SEMEVAL17' not in filename:
continue
filepath = os.path.join(dirpath, filename)
# language order
assert len(filename.split('_')) >= 2
split = filename.split('_')[0].split('-')
assert len(split) == 2
if split[0] == lang1.upper() and split[1] == lang2.upper():
coeff, found, not_found = get_spearman_rho(
word2id1, embeddings1, filepath,
lower, word2id2, embeddings2
)
elif split[0] == lang2.upper() and split[1] == lang1.upper():
coeff, found, not_found = get_spearman_rho(
word2id2, embeddings2, filepath,
lower, word2id1, embeddings1
)
else:
raise Exception('Unexpected parse: %s' % filename)
logger.info(pattern % (filename[:-4], str(found),
str(not_found), "%.4f" % coeff))
scores[filename[:-4]] = coeff
if not scores:
return None
logger.info(separator)
return scores