forked from spyysalo/wvlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wvlib.py
executable file
·1491 lines (1190 loc) · 48.2 KB
/
wvlib.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Word vector library.
Provides functionality for reading and writing word vectors in various
formats and support for basic operations using word vectors such as
cosine similarity.
The word2vec binary and text formats are supported for input, and tar,
tar.gz and directory-based variants of the wvlib format are supported
for input and output.
Variables:
formats -- list of formats recognized by load().
output_formats -- list of formats recognized by WVData.save()
vector_formats -- list of vector formats recognized by WVData.save()
Functions:
load() -- load word vectors from a file in a supported input format.
Classes:
WVData -- represents word vectors and related data.
Word2VecData -- WVData for word2vec vectors.
SdvData -- WVData for space-delimited values vectors.
Examples:
Load word2vec vectors from "vectors.bin", save in wvlib format in
"vectors.tar.gz":
>>> import wvlib
>>> wv = wvlib.load("vectors.bin")
>>> wv.save("vectors.tar.gz")
Load word vectors and compare similarity of two words:
>>> import wvlib
>>> wv = wvlib.load("text8.tar.gz")
>>> wv.similarity("dog", "cat")
Load word vectors, normalize, and find words nearest to given word:
>>> import wvlib
>>> wv = wvlib.load("text8.tar.gz").normalize()
>>> wv.nearest("dog")
(normalize() irreversibly alters the word vectors, but considerably
speeds up calculations using word vector similarity.)
Load word vectors, normalize, and find word that has the same
relationship to "japan" as "paris" has to "france" (see https://code.google.com/p/word2vec/#Interesting_properties_of_the_word_vectors).
>>> import wvlib
>>> wv = wvlib.load("text8.tar.gz").normalize()
>>> v = wv["paris"] - wv["france"] + wv["japan"]
>>> wv.nearest(v)[0]
Load word vectors and save with vectors in TSV format:
>>> import wvlib
>>> wv = wvlib.load("text8.tar.gz")
>>> wv.save("text8-tsv.tar.gz", vector_format="tsv")
Load word vectors, normalize, find nearest for each of a set of words
using locality sensitive hashing (LSH)-based approximate nearest
neighbors.
>>> import wvlib
>>> wv = wvlib.load("text8.tar.gz").normalize()
>>> for w in ["snowfall", "titanium", "craftsman", "apple", "anger",
... "leukemia", "yuan", "club", "cylinder", "mandarin", "boat"]:
... print w, wv.approximate_nearest(w)[0]
Load word vectors, filter to top-ranking only, and get exact cosine
similarity and approximate LSH-based similarity using 1000-bit hashes.
>>> import wvlib
>>> wv = wvlib.load('text8.tar.gz').filter_by_rank(1000)
>>> wv.similarity('university', 'church')
>>> wv.approximate_similarity('university', 'church', 1000)
"""
import sys
import os
import math
import json
import codecs
import tarfile
import logging
import traceback
import numpy
import heapq
try:
import numpy.numarray
with_numarray = True
except ImportError:
with_numarray = False
from functools import partial
from itertools import tee, izip, islice
from StringIO import StringIO
from types import StringTypes
from time import time
from collections import defaultdict
import struct
import ast #for ast.literal_eval
try:
from collections import OrderedDict
except ImportError:
from compat.ordereddict import OrderedDict
try:
from gmpy import popcount
with_gmpy = True
except ImportError:
# TODO: counting the number of set bits can take > 90% of the
# overall runtime in LSH-heavy programs. bin(i).count('1') is
# apparently the fastest pure python approach
# (http://stackoverflow.com/a/9831671), but remains so slow that
# using exact similarity can be faster overall. gmpy should be
# installed for a fast popcount() implementation.
def popcount(i):
return bin(i).count('1')
with_gmpy = False
logging.getLogger().setLevel(logging.DEBUG)
DEFAULT_ENCODING = "UTF-8"
WV_FORMAT_VERSION = 1
CONFIG_NAME = 'config.json'
VOCAB_NAME = 'vocab.tsv'
VECTOR_BASE = 'vectors'
# supported formats and likely filename extensions for each
WORD2VEC_FORMAT = 'w2v'
WORD2VEC_TEXT = 'w2vtxt'
WORD2VEC_BIN = 'w2vbin'
WVLIB_FORMAT = 'wvlib'
CID_FORMAT = 'cid'
SDV_FORMAT = 'sdv'
extension_format_map = {
'.tsv' : SDV_FORMAT,
'.bin' : WORD2VEC_BIN,
'.tar' : WVLIB_FORMAT,
'.tgz' : WVLIB_FORMAT,
'.tar.gz' : WVLIB_FORMAT,
'.tar.bz2' : WVLIB_FORMAT,
'.classes' : CID_FORMAT,
'.sdv' : SDV_FORMAT,
'.vec' : WORD2VEC_TEXT, # fastText vector output
}
# supported vector formats and filename extensions
NUMPY_FORMAT = 'npy'
TSV_FORMAT = 'tsv'
formats = sorted(list(set(extension_format_map.values())))
output_formats = sorted([WVLIB_FORMAT, WORD2VEC_BIN, SDV_FORMAT])
vector_formats = sorted([NUMPY_FORMAT, TSV_FORMAT])
class FormatError(Exception):
pass
class WVData(object):
TAR = 'tar'
DIR = 'dir'
def __init__(self, config, vocab, vectors):
# TODO: check config-vocab-vectors consistency
self.config = config
self.vocab = vocab
self._vectors = vectors
self._w2v_map = None
self._normalized = False
self._lsh = None
self._w2h_lsh = None
self._w2h_map = None
def words(self):
"""Return list of words in the vocabulary."""
return self.vocab.words()
def vectors(self):
"""Return vectors as numpy array."""
return self._vectors.vectors
def rank(self, w):
"""Return rank (ordinal, 0-based) of word w in the vocabulary."""
return self.vocab.rank(w)
def word_to_vector(self, w):
"""Return vector for given word.
For large numbers of queries, consider word_to_vector_mapping().
"""
return self.word_to_vector_mapping()[w]
def words_to_vector(self, words):
"""Return average vector for given words."""
w2v = self.word_to_vector_mapping()
return sum(w2v[w] for w in words)/len(words)
def word_to_unit_vector(self, w):
"""Return unit (normalized) vector for given word.
For large numbers of queries, consider normalize() and
word_to_vector_mapping().
"""
v = self.word_to_vector_mapping()[w]
if self._normalized:
return v
else:
return v/numpy.linalg.norm(v)
def word_to_vector_mapping(self):
"""Return dict mapping from words to vectors.
The returned data is shared and should not be modified by the
caller.
"""
if self._w2v_map is None:
self._w2v_map = dict(iter(self))
return self._w2v_map
def similarity(self, v1, v2):
"""Return cosine similarity of given words or vectors.
If v1/v2 is a string, look up the corresponding word vector.
This is not particularly efficient function. Instead of many
invocations, consider word_similarity() or direct computation.
"""
vs = [v1, v2]
for i, v in enumerate(vs):
if isinstance(v, StringTypes):
v = self.word_to_unit_vector(v)
else:
v = v/numpy.linalg.norm(v) # costly but safe
vs[i] = v
return numpy.dot(vs[0], vs[1])
def word_similarity(self, w1, w2):
"""Return cosine similarity of vectors for given words.
For many invocations of this function, consider calling
normalize() first to avoid repeatedly normalizing the same
vectors.
"""
w2v = self.word_to_vector_mapping()
v1, v2 = w2v[w1], w2v[w2]
if not self._normalized:
v1, v2 = v1/numpy.linalg.norm(v1), v2/numpy.linalg.norm(v2)
return numpy.dot(v1, v2)
def approximate_similarity(self, v1, v2, bits=None):
"""Return approximate cosine similarity of given words or vectors.
Uses random hyperplane-based locality sensitive hashing (LSH)
with given number of bits. If bits is None, estimate number of
bits to use.
LSH is initialized on the first invocation, which may take
long for large numbers of word vectors. For a small number of
invocations, similarity() may be more efficient.
"""
if self._w2h_lsh is None or (bits is not None and bits != self._w2h_lsh.bits):
if not with_gmpy:
logging.warning('gmpy not available, approximate similarity '
'may be slow.')
self._w2h_lsh = self._initialize_lsh(bits, fill=False)
self._w2h_map = {}
logging.info('init word-to-hash map: start')
for w, v in self:
self._w2h_map[w] = self._w2h_lsh.hash(v)
logging.info('init word-to-hash map: done')
hashes = []
for v in (v1, v2):
if isinstance(v, StringTypes):
h = self._w2h_map[v]
else:
h = self._w2h_lsh.hash(v)
hashes.append(h)
return self._w2h_lsh.hash_similarity(hashes[0], hashes[1])
def nearest(self, v, n=10, exclude=None, candidates=None):
"""Return nearest n words and similarities for given word or vector,
excluding given words.
If v is a string, look up the corresponding word vector.
If exclude is None and v is a string, exclude v.
If candidates is not None, only consider (word, vector)
values from iterable candidates.
Return value is a list of (word, similarity) pairs.
"""
if isinstance(v, StringTypes):
v, w = self.word_to_unit_vector(v), v
else:
v, w = v/numpy.linalg.norm(v), None
if exclude is None:
exclude = [] if w is None else set([w])
if not self._normalized:
sim = partial(self._item_similarity, v=v)
else:
sim = partial(self._item_similarity_normalized, v=v)
if candidates is None:
candidates = self.word_to_vector_mapping().iteritems()
nearest = heapq.nlargest(n+len(exclude), candidates, sim)
wordsim = [(p[0], sim(p)) for p in nearest if p[0] not in exclude]
return wordsim[:n]
def approximate_nearest(self, v, n=10, exclude=None,
exact_eval=0.1, bits=None,
search_hash_neighborhood=True):
"""Return approximate nearest n words and similarities for
given word or vector, excluding given words.
Uses random hyperplane-based locality sensitive hashing (LSH)
with given number of bits, evaluating a number of approximate
neighbors exactly (exact_eval argument).
LSH is initialized on the first invocation, which may take
long for large numbers of word vectors. For a small number of
NN queries, nearest() may be more efficient.
If search_hash_neighborhood is True, find approximate neigbors
by searching the Hamming neighborhood. This is more efficient
for hashes with comparatively high load factors (~1) but
inefficient for ones with low load factors.
If v is a string, look up the corresponding word vector.
If exclude is None and v is a string, exclude v.
If 0 < exact_eval < 1, evaluate that fraction of the
vocabulary exactly, otherwise evaluate up to exact_eval words.
If bits is None, estimate number of bits to use.
Return value is a list of (word, similarity) pairs.
"""
if exact_eval < 1.0:
exact_eval = int(len(self.words()) * exact_eval)
logging.info('evaluating %d words exactly' % exact_eval)
if self._lsh is None or (bits is not None and bits != self._lsh.bits):
self._lsh = self._initialize_lsh(bits)
if isinstance(v, StringTypes):
v, w = self.word_to_unit_vector(v), v
else:
v, w = v/numpy.linalg.norm(v), v
if search_hash_neighborhood:
candidates = islice(self._lsh.neighbors(v), exact_eval)
return self.nearest(w, n, exclude, candidates)
else:
# exact_eval nearest by hash similarity
sim = partial(self._lsh.item_similarity, h=self._lsh.hash(v),
bits=self._lsh.bits)
anearest = heapq.nlargest(exact_eval, self._lsh.iteritems(), sim)
# nearest vectors for up to exact_eval of nearest hashes
candidates = islice((wv for _, wvs in anearest for wv in wvs),
exact_eval)
return self.nearest(w, n, exclude, candidates)
def _lsh_bits(self, bits):
if bits is None:
w = self.config.word_count
bits = max(4, int(math.ceil(math.log(w, 2))))
logging.debug('init lsh: %d vectors, %d bits' % (w, bits))
return bits
def _initialize_lsh(self, bits, fill=True):
bits = self._lsh_bits(bits)
lsh = RandomHyperplaneLSH(self.config.vector_dim, bits)
if fill:
for w, v in self:
lsh.add(v, (w, v))
lf = lsh.load_factor()
logging.debug('init lsh: load factor %.2f' % lf)
if lf < 0.1:
logging.warning('low lsh load factor (%f), neighbors searches '
'may be slow' % lf)
return lsh
def normalize(self):
"""Normalize word vectors.
Irreversible. Has potentially high invocation cost, but should
reduce overall time when there are many invocations of
word_similarity()."""
if self._normalized:
return self
self._invalidate()
self._vectors.normalize()
self._normalized = True
return self
def filter_by_rank(self, r):
"""Discard vectors for words other than the r most frequent."""
if r < self.config.word_count:
self._invalidate()
self.config.word_count = r
self.vocab.shrink(r)
self._vectors.shrink(r)
return self
def save(self, name, format=None, vector_format=None):
"""Save in format to pathname name.
If format is None, determine format heuristically.
If vector_format is not None, save vectors in vector_format
instead of currently set format (config.format).
"""
vf = self.config.format
try:
if vector_format is not None:
self.config.format = vector_format
if format is None:
format = self.guess_format(name)
if format is None:
raise ValueError('failed to guess format for %s' % name)
logging.info('saving %s as %s with %s vectors' %
(name, format, self.config.format))
if format == self.TAR:
return self.save_tar(name)
elif format == self.DIR:
return self.save_dir(name)
elif format == WORD2VEC_BIN:
return self.save_bin(name)
elif format == SDV_FORMAT:
return self.save_sdv(name)
else:
raise NotImplementedError
finally:
self.config.format = vf
def save_tar(self, name, mode=None):
"""Save in tar format to pathname name using mode.
If mode is None, determine mode from filename extension.
"""
if mode is None:
if name.endswith('.tgz') or name.endswith('.gz'):
mode = 'w:gz'
elif name.endswith('.bz2'):
mode = 'w:bz2'
else:
mode = 'w'
f = tarfile.open(name, mode)
try:
vecformat = self.config.format
vecfile_name = VECTOR_BASE + '.' + vecformat
self._save_in_tar(f, CONFIG_NAME, self.config.savef)
self._save_in_tar(f, VOCAB_NAME, self.vocab.savef)
self._save_in_tar(f, vecfile_name, partial(self._vectors.savef,
format = vecformat))
finally:
f.close()
def save_dir(self, name):
"""Save to directory name."""
vecformat = self.config.format
vecfile_name = VECTOR_BASE + '.' + vecformat
self.config.save(os.path.join(name, CONFIG_NAME))
self.vocab.save(os.path.join(name, VOCAB_NAME))
self._vectors.save(os.path.join(name, vecfile_name))
def save_bin(self, name, max_rank=-1):
"""Save in word2vec binary format without newlines."""
vector_matrix=self.vectors() #list of ndarrays... whoa!
if max_rank:
to_save=max(max_rank, len(vector_matrix))
else:
to_save=len(vector_matrix)
words=self.words()
with open(name,"wb") as f:
f.write("%d %d\n"%(to_save,len(vector_matrix[0])))
for i in range(to_save):
if isinstance(words[i],unicode):
f.write(words[i].encode("utf8"))
else:
f.write(words[i])
f.write(" ")
vector_matrix[i].astype(numpy.float32).tofile(f)
f.flush()
def save_sdv(self, name):
"""Save in space-delimited values format."""
words, vectors = self.words(), self.vectors()
with open(name, 'wt') as f:
for w, v in self:
print >> f, w, ' '.join(str(i) for i in v)
def _invalidate(self):
"""Invalidate cached values."""
self._w2v_map = None
self._lsh = None
def __getitem__(self, word):
"""Return vector for given word."""
return self.word_to_vector_mapping()[word]
def __contains__(self, word):
"""Return True iff given word is in vocabulary (has vector)."""
return word in self.word_to_vector_mapping()
def __getattr__(self, name):
# delegate access to nonexistent attributes to config
return getattr(self.config, name)
def __iter__(self):
"""Iterate over (word, vector) pairs."""
#return izip(self.vocab.words(), self._vectors)
return izip(self.vocab.iterwords(), iter(self._vectors))
@classmethod
def load(cls, name, max_rank=None):
"""Return WVData from pathname name.
If max_rank is not None, only load max_rank most frequent words.
"""
format = cls.guess_format(name)
if format == cls.TAR:
wv = cls.load_tar(name, max_rank=max_rank)
elif format == cls.DIR:
wv = cls.load_dir(name, max_rank=max_rank)
else:
raise NotImplementedError
if max_rank is not None:
wv.filter_by_rank(max_rank)
return wv
@classmethod
def load_tar(cls, name, max_rank=None):
"""Return WVData from tar or tar.gz name.
If max_rank is not None, only load max_rank most frequent words."""
f = tarfile.open(name, 'r')
try:
return cls._load_collection(f, max_rank=max_rank)
finally:
f.close()
@classmethod
def load_dir(cls, name, max_rank=None):
"""Return WVData from directory name.
If max_rank is not None, only load max_rank most frequent words."""
d = _Directory.open(name, 'r')
try:
return cls._load_collection(d, max_rank=max_rank)
finally:
d.close()
@classmethod
def _load_collection(cls, coll, max_rank=None):
# abstracts over tar and directory
confname, vocabname, vecname = None, None, None
for i in coll:
if i.isdir():
continue
elif not i.isfile():
logging.warning('unexpected item: %s' % i.name)
continue
base = os.path.basename(i.name)
if base == CONFIG_NAME:
confname = i.name
elif base == VOCAB_NAME:
vocabname = i.name
elif os.path.splitext(base)[0] == VECTOR_BASE:
vecname = i.name
else:
logging.warning('unexpected file: %s' % i.name)
for i, n in ((confname, CONFIG_NAME),
(vocabname, VOCAB_NAME),
(vecname, VECTOR_BASE)):
if i is None:
raise FormatError('missing %s' % n)
config = Config.loadf(coll.extractfile(confname))
vocab = Vocabulary.loadf(coll.extractfile(vocabname),
max_rank=max_rank)
vectors = Vectors.loadf(coll.extractfile(vecname), config.format,
max_rank=max_rank)
return cls(config, vocab, vectors)
@staticmethod
def _save_in_tar(tar, name, savef):
# helper for save_tar
i = tar.tarinfo(name)
s = StringIO()
savef(s)
s.seek(0)
i.size = s.len
i.mtime = time()
tar.addfile(i, s)
@staticmethod
def _item_similarity(i, v):
"""Similarity of (word, vector) pair with normalized vector."""
return numpy.dot(i[1]/numpy.linalg.norm(i[1]), v)
@staticmethod
def _item_similarity_normalized(i, v):
"""Similarity of normalized (word vector) pair with vector."""
return numpy.dot(i[1], v)
@staticmethod
def guess_format(name):
if os.path.isdir(name):
return WVData.DIR
elif (name.endswith('.tar') or name.endswith('.gz') or name.endswith('.tgz') or name.endswith('.bz2')):
return WVData.TAR
elif name.endswith('.bin'):
return WORD2VEC_BIN
elif name.endswith('.sdv'):
return SDV_FORMAT
else:
return None
class _FileInfo(object):
"""Implements minimal part of TarInfo interface for files."""
def __init__(self, name):
self.name = name
def isdir(self):
return os.path.isdir(self.name)
def isfile(self):
return os.path.isfile(self.name)
class _Directory(object):
"""Implements minimal part part of TarFile interface for directories."""
def __init__(self, name):
self.name = name
self.listing = None
self.open_files = []
def __iter__(self):
if self.listing is None:
self.listing = os.listdir(self.name)
return (_FileInfo(os.path.join(self.name, i)) for i in self.listing)
def extractfile(self, name):
f = open(name)
self.open_files.append(f)
return f
def close(self):
for f in self.open_files:
f.close()
@classmethod
def open(cls, name, mode=None):
return cls(name)
class Vectors(object):
default_format = NUMPY_FORMAT
def __init__(self, vectors):
self.vectors = vectors
self._normalized = False
def normalize(self):
if self._normalized:
return self
for i, v in enumerate(self.vectors):
self.vectors[i] = v/numpy.linalg.norm(v)
self._normalized = True
return self
def shrink(self, s):
"""Discard vectors other than the first s."""
self.vectors = self.vectors[:s]
def to_rows(self):
return self.vectors
def save_tsv(self, f):
"""Save as TSV to file-like object f."""
f.write(self.__str__())
def savef(self, f, format):
"""Save in format to file-like object f."""
if format == TSV_FORMAT:
return self.save_tsv(f)
elif format == NUMPY_FORMAT:
return numpy.save(f, self.vectors)
else:
raise NotImplementedError(format)
def save(self, name, format=None, encoding=DEFAULT_ENCODING):
"""Save in format to pathname name.
If format is None, determine format from filename extension.
If format is None and the extension is empty, use default
format and append the appropriate extension.
"""
if format is None:
format = os.path.splitext(name)[1].replace('.', '')
if not format:
format = self.default_format
name = name + '.' + format
logging.debug('save vectors in %s to %s' % (format, name))
if Vectors.is_text_format(format):
with codecs.open(name, 'wt', encoding=encoding) as f:
return self.savef(f, format)
else:
with codecs.open(name, 'wb') as f:
return self.savef(f, format)
def to_tsv(self):
return self.__str__()
def __str__(self):
return '\n'.join('\t'.join(str(i) for i in r) for r in self.to_rows())
def __iter__(self):
return iter(self.vectors)
@classmethod
def from_rows(cls, rows):
return cls(rows)
@classmethod
def load_tsv(cls, f, max_rank=None):
"""Return Vectors from file-like object f in TSV.
If max_rank is not None, only load max_rank first vectors."""
rows = []
for i, l in enumerate(f):
if max_rank is not None and i >= max_rank:
break
#row = [float(i) for i in l.rstrip('\n').split()]
row = numpy.fromstring(l, sep='\t')
rows.append(row)
if (i+1) % 10000 == 0:
logging.debug('read %d TSV rows' % (i+1))
return cls.from_rows(rows)
@classmethod
def load_numpy(cls, f, max_rank=None):
"""Return Vectors from file-like object f in NumPy format.
If max_rank is not None, only load max_rank first vectors."""
# NOTE: the bit below would be better but doesn't work, as mmap
# cannot use existing file handles.
# if max_rank is not None:
# return cls(numpy.array(numpy.load(f, mmap_mode='r')[:max_rank]))
#We'll need to hack into the npy format to make this happen
# https://github.com/numpy/numpy/blob/master/doc/neps/npy-format.txt
if max_rank is not None and with_numarray:
magic_string=f.read(6)
if magic_string!='\x93NUMPY':
raise ValueError('The input does not seem to be an NPY file (magic string does not match).')
major_ver,minor_ver,header_len=struct.unpack("<BBH",f.read(1+1+2))
#TODO: check format versions?
format_dict_str=f.read(header_len).strip() #Dictionary string repr. with the array format
format_dict=ast.literal_eval(format_dict_str) #this should be reasonably safe
rows,cols=format_dict['shape'] #Shape of the array as stored in the file
new_shape=(min(rows,max_rank),cols) #Clipped shape of the array
array=numpy.numarray.fromfile(f,format_dict['descr'],new_shape[0]*new_shape[1])
array=array.reshape(new_shape)
v=cls(array)
else:
if max_rank is not None:
# numpy.numarray is gone in numpy 1.9, the hack used
# for partial load will no longer work
logging.warning('no numpy.numarray, -r disabled for numpy data')
# TODO: reshape anyway
v = cls(numpy.load(f))
return v
@classmethod
def loadf(cls, f, format, max_rank=None):
"""Return Vectors from file-like object f in format.
If max_rank is not None, only load max_rank first vectors."""
if format == TSV_FORMAT:
return cls.load_tsv(f, max_rank=max_rank)
elif format == NUMPY_FORMAT:
return cls.load_numpy(f, max_rank=max_rank)
else:
raise NotImplementedError(format)
@classmethod
def load(cls, name, format=None, encoding=DEFAULT_ENCODING, max_rank=None):
"""Return Vectors from pathname name in format.
If format is None, determine format from filename extension.
If max_rank is not None, only load max_rank first vectors."""
if format is None:
format = os.path.splitext(name)[1].replace('.', '')
if Vectors.is_text_format(format):
with codecs.open(name, 'rt', encoding=encoding) as f:
return cls.loadf(f, format, max_rank=max_rank)
else:
with codecs.open(name, 'rb') as f:
return cls.loadf(f, format, max_rank=max_rank)
@staticmethod
def is_text_format(format):
if format == TSV_FORMAT:
return True
elif format == NUMPY_FORMAT:
return False
else:
raise ValueError('Unknown format %s' % format)
class Vocabulary(object):
def __init__(self, word_freq):
assert not any((j for i, j in pairwise(word_freq) if i[1] < j[1])), \
'words not ordered by descending frequency'
self.word_freq = OrderedDict(word_freq)
assert len(self.word_freq) == len(word_freq), \
'vocab has duplicates: %s' % (' '.join(duplicates(w for w, f in word_freq)))
self._rank = None
def words(self):
return self.word_freq.keys()
def rank(self, w):
if self._rank is None:
self._rank = dict(((j, i) for i, j in enumerate(self.words())))
return self._rank[w]
def shrink(self, s):
"""Discard words other than the first s."""
self._invalidate()
self.word_freq = OrderedDict(islice(self.word_freq.iteritems(), s))
def iterwords(self):
return self.word_freq.iterkeys()
def to_rows(self):
return self.word_freq.iteritems()
def savef(self, f):
"""Save as TSV to file-like object f."""
f.write(self.__str__())
def save(self, name, encoding=DEFAULT_ENCODING):
"""Save as TSV to pathname name."""
with codecs.open(name, 'wt', encoding=encoding) as f:
return self.savef(f)
def _invalidate(self):
"""Invalidate cached values."""
self._rank = None
def __str__(self):
return '\n'.join('\t'.join(str(i) for i in r) for r in self.to_rows())
def __getitem__(self, key):
return self.word_freq[key]
def __setitem__(self, key, value):
self.word_freq[key] = value
def __delitem__(self, key):
del self.word_freq[key]
def __iter__(self):
return iter(self.word_freq)
def __contains__(self, item):
return item in self.word_freq
@classmethod
def from_rows(cls, rows):
return cls(rows)
@classmethod
def loadf(cls, f, max_rank=None, encoding=DEFAULT_ENCODING):
"""Return Vocabulary from file-like object f in TSV format.
If max_rank is not None, only load max_rank most frequent words."""
rows = []
for i, l in enumerate(f):
l=unicode(l,encoding)
if max_rank is not None and i >= max_rank:
break
l = l.rstrip()
row = l.split('\t')
if len(row) != 2:
raise ValueError('expected 2 fields, got %d: %s' % \
(len(row), l))
try:
row[1] = int(row[1])
except ValueError, e:
raise TypeError('expected int, got %s' % row[1])
rows.append(row)
return cls.from_rows(rows)
@classmethod
def load(cls, name, encoding=DEFAULT_ENCODING, max_rank=None):
"""Return Vocabulary from pathname name in TSV format.
If max_rank is not None, only load max_rank most frequent words."""
with codecs.open(name, 'rU', encoding=encoding) as f:
return cls.loadf(f, max_rank=max_rank)
class ConfigError(Exception):
pass
class Config(object):
def __init__(self, version, word_count, vector_dim, format):
self.version = version
self.word_count = word_count
self.vector_dim = vector_dim
self.format = format
def to_dict(self):
return { 'version' : self.version,
'word_count' : self.word_count,
'vector_dim' : self.vector_dim,
'format' : self.format,
}
def savef(self, f):
"""Save as JSON to file-like object f."""
return json.dump(self.to_dict(), f, sort_keys=True,
indent=4, separators=(',', ': '))
def save(self, name, encoding=DEFAULT_ENCODING):
"""Save as JSON to pathname name."""
with codecs.open(name, 'wt', encoding=encoding) as f:
return self.savef(f)
def __str__(self):
return str(self.to_dict())
@classmethod
def from_dict(cls, d):
try:
return cls(int(d['version']),
int(d['word_count']),
int(d['vector_dim']),
d['format'])
except KeyError, e: