| 52 | |
| 53 | ## faster |
| 54 | def find_analogies(w1, w2, w3): |
| 55 | for w in (w1, w2, w3): |
| 56 | if w not in word2vec: |
| 57 | print("%s not in dictionary" % w) |
| 58 | return |
| 59 | |
| 60 | king = word2vec[w1] |
| 61 | man = word2vec[w2] |
| 62 | woman = word2vec[w3] |
| 63 | v0 = king - man + woman |
| 64 | |
| 65 | distances = pairwise_distances(v0.reshape(1, D), embedding, metric=metric).reshape(V) |
| 66 | idxs = distances.argsort()[:4] |
| 67 | for idx in idxs: |
| 68 | word = idx2word[idx] |
| 69 | if word not in (w1, w2, w3): |
| 70 | best_word = word |
| 71 | break |
| 72 | |
| 73 | print(w1, "-", w2, "=", best_word, "-", w3) |
| 74 | |
| 75 | |
| 76 | def nearest_neighbors(w, n=5): |