(w1, w2, w3, we_file='word_embeddings.npy', w2i_file='wikipedia_word2idx.json')
| 148 | |
| 149 | |
| 150 | def find_analogies(w1, w2, w3, we_file='word_embeddings.npy', w2i_file='wikipedia_word2idx.json'): |
| 151 | We = np.load(we_file) |
| 152 | with open(w2i_file) as f: |
| 153 | word2idx = json.load(f) |
| 154 | |
| 155 | king = We[word2idx[w1]] |
| 156 | man = We[word2idx[w2]] |
| 157 | woman = We[word2idx[w3]] |
| 158 | v0 = king - man + woman |
| 159 | |
| 160 | def dist1(a, b): |
| 161 | return np.linalg.norm(a - b) |
| 162 | def dist2(a, b): |
| 163 | return 1 - a.dot(b) / (np.linalg.norm(a) * np.linalg.norm(b)) |
| 164 | |
| 165 | for dist, name in [(dist1, 'Euclidean'), (dist2, 'cosine')]: |
| 166 | min_dist = float('inf') |
| 167 | best_word = '' |
| 168 | for word, idx in iteritems(word2idx): |
| 169 | if word not in (w1, w2, w3): |
| 170 | v1 = We[idx] |
| 171 | d = dist(v0, v1) |
| 172 | if d < min_dist: |
| 173 | min_dist = d |
| 174 | best_word = word |
| 175 | print("closest match by", name, "distance:", best_word) |
| 176 | print(w1, "-", w2, "=", best_word, "-", w3) |
| 177 | |
| 178 | |
| 179 |
no test coverage detected