|
| 1 | +from spacy import Language |
| 2 | +from spacy.tokens import Doc |
| 3 | +from spacy.pipeline import Pipe |
| 4 | +from spacy.vocab import Vocab |
| 5 | + |
| 6 | +from thinc.types import Floats1d, Floats2d |
| 7 | +from thinc.api import Model, CosineDistance, get_ops |
| 8 | + |
| 9 | +from dataclasses import dataclass |
| 10 | + |
| 11 | +Doc.set_extension("poles", default={}, force=True) |
| 12 | + |
| 13 | + |
| 14 | +@dataclass |
| 15 | +class Axis: |
| 16 | + """An invididual semantic axis.""" |
| 17 | + |
| 18 | + neg: str |
| 19 | + pos: str |
| 20 | + vector: Floats1d |
| 21 | + |
| 22 | + def get_key(self, sep="-"): |
| 23 | + return f"{self.neg}{sep}{self.pos}" |
| 24 | + |
| 25 | + |
| 26 | +@Language.factory( |
| 27 | + "polar", |
| 28 | + requires=["doc.vector"], |
| 29 | + default_config={}, |
| 30 | + default_score_weights={}, |
| 31 | +) |
| 32 | +def make_polar_embeddings( |
| 33 | + nlp: Language, |
| 34 | + name: str, |
| 35 | +): |
| 36 | + return PolarEmbeddings( |
| 37 | + nlp, |
| 38 | + name, |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +class PolarEmbeddings(Pipe): |
| 43 | + """PolarEmbeddings let you turn normal word embeddings into embeddings |
| 44 | + oriented along axes of meaning, preserving the overall distance of the |
| 45 | + original embeddings while giving dimensions semantic meaning. |
| 46 | + """ |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + nlp: Language, |
| 51 | + name: str = "polar", |
| 52 | + *, |
| 53 | + separator: str = "-", |
| 54 | + ) -> None: |
| 55 | + self.nlp = nlp |
| 56 | + self.name = name |
| 57 | + self.separator = separator |
| 58 | + |
| 59 | + self.ops = get_ops("numpy") |
| 60 | + self.cosine = CosineDistance() |
| 61 | + self._matrix = None |
| 62 | + self.axes = [] |
| 63 | + self.cfg = {} |
| 64 | + |
| 65 | + def get_average_neighbors(self, query, nn=150): |
| 66 | + """Given a query vector, return the average of the nearest vecs. |
| 67 | +
|
| 68 | + Used to calculate pole vectors.""" |
| 69 | + # Note that in spaCy pipelines for many languages vectors include case |
| 70 | + # variations, so nn should be larger than in the reference paper |
| 71 | + seed = self.nlp.vocab[query].vector |
| 72 | + vectors = self.nlp.vocab.vectors |
| 73 | + qarray = self.ops.asarray2f([seed]) |
| 74 | + keys, best_rows, scores = vectors.most_similar(qarray, n=nn) |
| 75 | + targets = vectors.data[best_rows].squeeze() |
| 76 | + |
| 77 | + return self.ops.xp.mean(targets, axis=0) |
| 78 | + |
| 79 | + def add_axis(self, neg: str, pos: str) -> None: |
| 80 | + """Add a new pole to the pipe. Pass the negative word first.""" |
| 81 | + |
| 82 | + notfound = "Anchor word '{}' not found in vocab." |
| 83 | + |
| 84 | + if not self.nlp.vocab.has_vector(neg): |
| 85 | + raise KeyError(notfound.format(neg)) |
| 86 | + if not self.nlp.vocab.has_vector(pos): |
| 87 | + raise KeyError(notfound.format(pos)) |
| 88 | + |
| 89 | + pv = self.get_average_neighbors(pos) |
| 90 | + nv = self.get_average_neighbors(neg) |
| 91 | + self.axes.append(Axis(neg, pos, pv - nv)) |
| 92 | + self._update_axes_matrix() |
| 93 | + |
| 94 | + def _update_axes_matrix(self) -> None: |
| 95 | + vecs = [aa.vector for aa in self.axes] |
| 96 | + self._matrix = self.ops.asarray2f(vecs).T |
| 97 | + |
| 98 | + def __call__(self, doc: Doc) -> Doc: |
| 99 | + docvec = self.ops.xp.expand_dims(doc.vector, axis=1) |
| 100 | + docvec = docvec.repeat(len(self.axes), axis=1) |
| 101 | + dists = self.cosine.get_similarity(docvec.T, self._matrix.T) |
| 102 | + |
| 103 | + for axis, dist in zip(self.axes, dists): |
| 104 | + key = axis.get_key(sep=self.separator) |
| 105 | + doc._.poles[key] = float(dist) |
| 106 | + return doc |
0 commit comments