|
| 1 | +import numpy as np |
| 2 | +from collections import OrderedDict |
| 3 | +from sklearn import preprocessing |
| 4 | + |
| 5 | + |
| 6 | +# This file contains the WordVectors class used to load and handle word embeddings |
| 7 | +def intersection(*args): |
| 8 | + """ |
| 9 | + This function returns the intersection between WordVectors objects |
| 10 | + I.e.: all words that occur in both objects simultaneously as well as their |
| 11 | + respective word vectors |
| 12 | + Returns: list(WordVectors) objects with intersecting words |
| 13 | + """ |
| 14 | + if len(args) < 2: |
| 15 | + print("! Error: intersection requires at least 2 WordVector objects") |
| 16 | + return None |
| 17 | + # Get intersecting words |
| 18 | + # WARNING: using set intersection will affect the order of words |
| 19 | + # in the original word vectors, to keep results consistent |
| 20 | + # it is better to iterate over the list of words |
| 21 | + # the resulting order will follow the first WordVectors's order |
| 22 | + # Get intersecting words |
| 23 | + common_words = set.intersection(*[set(wv.words) for wv in args]) |
| 24 | + # Get intersecting words following the order of first WordVector |
| 25 | + words = [w for w in args[0].words if w in common_words] |
| 26 | + |
| 27 | + # Retrieve vectors from a and b for intersecting words |
| 28 | + wv_out = list() # list of output WordVectors |
| 29 | + for wv in args: |
| 30 | + wv_out.append(WordVectors(words=words, vectors=[wv[w]for w in words])) |
| 31 | + |
| 32 | + return wv_out |
| 33 | + |
| 34 | + |
| 35 | +def union(*args, f="average"): |
| 36 | + """ |
| 37 | + Performs union of two or more word vectors, returning a new WordVectors |
| 38 | + containing union of words and combination of vectors according to given |
| 39 | + function. |
| 40 | + Arguments: |
| 41 | + *args - list of WordVectors objects |
| 42 | + f - (str) function to use when combining word vectors (default to average) |
| 43 | + Returns: |
| 44 | + wv - WordVectors as the union the input args |
| 45 | + """ |
| 46 | + |
| 47 | + if f == 'average': |
| 48 | + f = lambda x: sum(x)/len(x) |
| 49 | + |
| 50 | + union_words = set.union(*[set(wv.words) for wv in args]) |
| 51 | + |
| 52 | + words = list(union_words) |
| 53 | + vectors = np.zeros((len(words), args[0].dimension), dtype=float) |
| 54 | + for i, w in enumerate(words): |
| 55 | + # Get list of existing vectors for w |
| 56 | + vecs = np.array([wv[w] for wv in args if w in wv]) |
| 57 | + vectors[i] = f(vecs) # Combine vectors |
| 58 | + |
| 59 | + wv_out = WordVectors(words=words, vectors=vectors) |
| 60 | + |
| 61 | + return wv_out |
| 62 | + |
| 63 | + |
| 64 | +# Implements a WordVector class that performs mapping of word tokens to vectors |
| 65 | +# Stores words as |
| 66 | +class WordVectors: |
| 67 | + """ |
| 68 | + WordVectors class containing methods for handling the mapping of words |
| 69 | + to vectors. |
| 70 | + Attributes |
| 71 | + - word_id -- OrderedDict mapping word to id in list of vectors |
| 72 | + - words -- list of words mapping id (index) to word string |
| 73 | + - vectors -- n x dim matrix of word vectors, follows id order |
| 74 | + - counts -- not used at the moment, designed to store word count |
| 75 | + - dimension -- dimension of wordvectors |
| 76 | + - zipped -- a zipped list of (word, vec) used to construct the object |
| 77 | + - min_freq -- filter out words whose frequency is less than min_freq |
| 78 | + """ |
| 79 | + def __init__(self, words=None, vectors=None, counts=None, zipped=None, |
| 80 | + input_file=None, centered=True, normalized=False, |
| 81 | + min_freq=0, word_frequency=None): |
| 82 | + |
| 83 | + if words is not None and vectors is not None: |
| 84 | + self.word_id = OrderedDict() |
| 85 | + self.words = list() |
| 86 | + for i, w in enumerate(words): |
| 87 | + self.word_id[w] = i |
| 88 | + self.words = list(words) |
| 89 | + self.vectors = np.array(vectors) |
| 90 | + self.counts = counts |
| 91 | + self.dimension = len(vectors[0]) |
| 92 | + elif zipped: |
| 93 | + pass |
| 94 | + elif input_file: |
| 95 | + self.dimension = 0 |
| 96 | + self.word_id = dict() |
| 97 | + self.words = list() |
| 98 | + self.counts = dict() |
| 99 | + self.vectors = None |
| 100 | + self.read_file(input_file) |
| 101 | + |
| 102 | + if centered: |
| 103 | + self.center() |
| 104 | + if normalized: |
| 105 | + self.normalize() |
| 106 | + |
| 107 | + if word_frequency: |
| 108 | + self.filter_frequency(min_freq, word_frequency) |
| 109 | + |
| 110 | + def center(self): |
| 111 | + self.vectors = self.vectors - self.vectors.mean(axis=0, keepdims=True) |
| 112 | + |
| 113 | + def normalize(self): |
| 114 | + self.vectors = preprocessing.normalize(self.vectors, norm="l2") |
| 115 | + |
| 116 | + def get_words(self): |
| 117 | + return self.word_id.keys() |
| 118 | + |
| 119 | + # Returns a numpy (m, dim) array for a given list of words |
| 120 | + # I.e.: select vectors whose word are in argument words |
| 121 | + def get_vectors_from_words(self, words): |
| 122 | + vectors = np.zeros((len(words), self.dimension)) |
| 123 | + for i, w in enumerate(words): |
| 124 | + vectors[i] = self[w] |
| 125 | + return vectors |
| 126 | + |
| 127 | + # Return (word,vec) for given word |
| 128 | + # In future versions may only return self.vectors |
| 129 | + def loc(self, word, return_word=False): |
| 130 | + if return_word: |
| 131 | + return word, self.vectors[self.word_id[word]] |
| 132 | + else: |
| 133 | + return self.vectors[self.word_id[word]] |
| 134 | + |
| 135 | + def get_count(self, word): |
| 136 | + return self.freq[self.word_id[word]] |
| 137 | + |
| 138 | + # Get word, vector pair from id |
| 139 | + def iloc(self, id_query, return_word=False): |
| 140 | + if return_word: |
| 141 | + return self.words[id_query], self.vectors[id_query] |
| 142 | + else: |
| 143 | + return self.vectors[id_query] |
| 144 | + |
| 145 | + # Overload [], given word w returns its vector |
| 146 | + def __getitem__(self, key): |
| 147 | + if isinstance(key, int) or isinstance(key, np.int64): |
| 148 | + return self.iloc(key) |
| 149 | + elif isinstance(key, slice): # slice |
| 150 | + return ([w for w in self.words[key.start: key.stop]], |
| 151 | + [v for v in self.vectors[key.start: key.stop]]) |
| 152 | + return self.loc(key) |
| 153 | + |
| 154 | + def __len__(self): |
| 155 | + return len(self.words) |
| 156 | + |
| 157 | + def __contains__(self, word): |
| 158 | + return word in self.word_id |
| 159 | + |
| 160 | + def filter_frequency(self, min_freq, word_frequency): |
| 161 | + print("Filtering %d" % min_freq) |
| 162 | + words_kept = list() |
| 163 | + vectors_kept = list() |
| 164 | + for word, vec in zip(self.words, self.vectors): |
| 165 | + if word in word_frequency and word_frequency[word] > min_freq: |
| 166 | + words_kept.append(word) |
| 167 | + vectors_kept.append(vec) |
| 168 | + |
| 169 | + self.words = words_kept |
| 170 | + self.vectors = np.array(vectors_kept) |
| 171 | + self.word_id = OrderedDict() |
| 172 | + for i, w in enumerate(self.words): |
| 173 | + self.word_id[w] = i |
| 174 | + |
| 175 | + print(" - Found %d words" % len(self.words)) |
| 176 | + |
| 177 | + # Read file in following format: |
| 178 | + # n_items dim |
| 179 | + def read_file(self, path): |
| 180 | + with open(path) as fin: |
| 181 | + n_words, dim = map(int, fin.readline().rstrip().split(" ", 1)) |
| 182 | + self.dimension = dim |
| 183 | + # print("Reading WordVectors (%d,%d)" % (n_words, dim)) |
| 184 | + |
| 185 | + # Use this function to process line reading in map |
| 186 | + def process_line(s): |
| 187 | + s = s.rstrip().split(" ", 1) |
| 188 | + w = s[0] |
| 189 | + v = np.array(s[1].split(" "), dtype=float) |
| 190 | + return w, v |
| 191 | + |
| 192 | + data = map(process_line, fin.readlines()) |
| 193 | + self.words, self.vectors = zip(*data) |
| 194 | + self.words = list(self.words) |
| 195 | + self.word_id = {w: i for i, w in enumerate(self.words)} |
| 196 | + self.vectors = np.array(self.vectors, dtype=float) |
| 197 | + |
| 198 | + def save_txt(self, path): |
| 199 | + with open(path, "w") as fout: |
| 200 | + fout.write("%d %d\n" % (len(self.word_id), self.dimension)) |
| 201 | + for word, vec in zip(self.words, self.vectors): |
| 202 | + v_string = " ".join(map(str, vec)) |
| 203 | + fout.write("%s %s\n" % (word, v_string)) |
0 commit comments