forked from askerlee/topicvec
/
utils.py
executable file
·1379 lines (1130 loc) · 48.2 KB
/
utils.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
import numpy as np
import scipy.linalg
from scipy.stats.stats import spearmanr
import time
import re
import pdb
import sys
import os
import glob
import logging
memLogger = logging.getLogger("Mem")
logging.basicConfig( stream=sys.stdout, level=logging.DEBUG )
class Timer(object):
def __init__(self, name=None):
self.name = name
self.tstart = time.time()
self.tlast = self.tstart
self.firstCall = True
def getElapseTime(self, isStr=True):
totalElapsed = time.time() - self.tstart
# elapsed time since last call
interElapsed = time.time() - self.tlast
self.tlast = time.time()
firstCall = self.firstCall
self.firstCall = False
if isStr:
if self.name:
if firstCall:
return '%s elapsed: %.2f' % ( self.name, totalElapsed )
return '%s elapsed: %.2f/%.2f' % ( self.name, totalElapsed, interElapsed )
else:
if firstCall:
return 'Elapsed: %.2f' % ( totalElapsed )
return 'Elapsed: %.2f/%.2f' % ( totalElapsed, interElapsed )
else:
return totalElapsed, interElapsed
def printElapseTime(self):
print self.getElapseTime()
# Weight: nonnegative real matrix. If not specified, return the unweighted norm
def norm1(M, Weight=None):
if Weight is not None:
s = np.sum( np.abs( M * Weight ) )
else:
s = np.sum( np.abs(M) )
return s
def normF(M, Weight=None):
if Weight is not None:
# M*M: element-wise square
s = np.sum( M * M * Weight )
else:
s = np.sum( M * M )
return np.sqrt(s)
# given a list of matrices, return a list of their norms
def matSizes( norm, Ms, Weight=None ):
sizes = []
for M in Ms:
sizes.append( norm(M, Weight) )
return sizes
def sym(M):
return ( M + M.T ) / 2.0
def skew(M):
return ( M - M.T ) / 2.0
# Assume A has been approximately sorted by rows, and in each row, sorted by columns
# matrix F returned from loadBigramFile satisfies this
# print the number of elements >= A[0,0]/2^n
# return the idea cut point above which there are at least "fraction" of the elements
# these elements will be cut off to this upper limit
def getQuantileCut(A, fraction):
totalElemCount = A.shape[0] * A.shape[1]
maxElem = A[0,0]
cutPoint = maxElem
idealCutPoint = cutPoint
idealFound = False
while cutPoint >= 10:
aboveElemCount = np.sum( A >= cutPoint )
print "Cut point %.0f: %d/%.3f%%" %( cutPoint, aboveElemCount, aboveElemCount * 100.0 / totalElemCount )
if not idealFound and aboveElemCount >= totalElemCount * fraction:
idealCutPoint = cutPoint
idealFound = True
cutPoint /= 2.0
return idealCutPoint
# find the principal eigenvalue/eigenvector: e1 & v1.
# if e1 < 0, then the left principal singular vector is -v1, and the right is v1.
# much faster than numpy.linalg.eig / scipy.linalg.eigh
def power_iter(M):
MAXITER = 100
epsilon = 1e-6
vec = np.random.rand(len(M))
old_vec = vec
for i in xrange(MAXITER):
vec2 = np.dot( M, vec )
magnitude = np.linalg.norm(vec2)
vec2 /= magnitude
vec = vec2
if i%2 == 1:
error = np.linalg.norm( vec2 - old_vec )
#print "%d: %f, %f" %( i+1, magnitude, error )
if error < epsilon:
break
old_vec = vec2
vec2 = np.dot( M, vec )
if np.sum(vec2)/np.sum(vec) > 0:
eigen = magnitude
else:
eigen = -magnitude
return eigen, vec
# each column of vs is an eigenvector
def lowrank_fact(VV, N0):
timer1 = Timer( "lowrank_fact()" )
es, vs = np.linalg.eigh(VV)
es = es[-N0:]
vs = vs[ :, -N0: ]
E_sqrt = np.diag( np.sqrt(es) )
V = vs.dot(E_sqrt.T)
VV = V.dot(V.T)
return V, VV, vs,es
def save_embeddings( filename, vocab, V, matrixName ):
FMAT = open(filename, "wb")
print "Save matrix '%s' into %s" %(matrixName, filename)
vocab_size = len(vocab)
N = len(V[0])
#pdb.set_trace()
FMAT.write( "%d %d\n" %(vocab_size, N) )
for i in xrange(vocab_size):
line = vocab[i]
for j in xrange(N):
line += " %.5f" %V[i,j]
FMAT.write("%s\n" %line)
FMAT.close()
# load top maxWordCount words, plus extraWords
def load_embeddings( filename, maxWordCount=-1, extraWords={} ):
FMAT = open(filename)
print "Load embedding text file '%s'" %(filename)
V = []
word2id = {}
skippedWords = {}
vocab = []
precision = np.float32
try:
header = FMAT.readline()
lineno = 1
match = re.match( r"(\d+) (\d+)", header)
if not match:
raise ValueError(lineno, header)
vocab_size = int(match.group(1))
N = int(match.group(2))
if maxWordCount > 0:
maxWordCount = min(maxWordCount, vocab_size)
else:
maxWordCount = vocab_size
print "Will load %d words" %maxWordCount,
if len(extraWords) > 0:
print "\b, plus %d extra words" %(len(extraWords))
else:
print
# maxWordCount + len(extraWords) is the maximum num of words.
# V may contain extra rows that will be removed at the end
V = np.zeros( (maxWordCount + len(extraWords), N), dtype=precision )
wid = 0
orig_wid = 0
for line in FMAT:
lineno += 1
line = line.strip()
# end of file
if not line:
if orig_wid != vocab_size:
raise ValueError( lineno, "%d words declared in header, but %d read" %(vocab_size, len(V)) )
break
fields = line.split(' ')
fields = filter( lambda x: x, fields )
w = fields[0]
if w in extraWords:
del extraWords[w]
isInterested = True
elif orig_wid < maxWordCount:
isInterested = True
else:
isInterested = False
skippedWords[w] = 1
orig_wid += 1
if isInterested:
V[wid] = np.array( [ float(x) for x in fields[1:] ], dtype=precision )
word2id[w] = wid
vocab.append(w)
wid += 1
if orig_wid % 1000 == 0:
print "\r%d %d %d \r" %( orig_wid, wid, len(extraWords) ),
if orig_wid > vocab_size:
raise ValueError( "%d words declared in header, but more are read" %(vocab_size) )
except ValueError, e:
if len( e.args ) == 2:
print "Unknown line %d:\n%s" %( e.args[0], e.args[1] )
else:
exc_type, exc_obj, tb = sys.exc_info()
print "Source line %d - %s on File line %d:\n%s" %( tb.tb_lineno, e, lineno, line )
exit(2)
FMAT.close()
print "\n%d embeddings read, %d kept" %(orig_wid, wid)
#pdb.set_trace()
if wid < len(V):
V = V[:wid]
# V: embeddings, vocab: array of words, word2id: dict of word to index in V
return V, vocab, word2id, skippedWords
# borrowed from gensim.models.word2vec
# load top maxWordCount words, plus extraWords
def load_embeddings_bin( filename, maxWordCount=-1, extraWords={} ):
print "Load embedding binary file '%s'" %(filename)
word2id = {}
vocab = []
#origWord2id = {}
#origVocab = []
precision = np.float32
with open(filename, "rb") as fin:
header = fin.readline()
vocab_size, N = map(int, header.split())
if maxWordCount > 0:
maxWordCount = min(maxWordCount, vocab_size)
else:
maxWordCount = vocab_size
print "Will load %d words" %maxWordCount,
if len(extraWords) > 0:
print "\b, plus %d extra words" %(len(extraWords))
else:
print
# maxWordCount + len(extraWords) is the maximum num of words.
# V may contain extra rows that will be removed at the end
V = np.zeros( (maxWordCount + len(extraWords), N), dtype=precision )
full_binvec_len = np.dtype(precision).itemsize * N
#pdb.set_trace()
orig_wid = 0
wid = 0
while True:
# mixed text and binary: read text first, then binary
word = []
while True:
ch = fin.read(1)
if ch == ' ':
break
if ch != '\n': # ignore newlines in front of words (some binary files have newline, some don't)
word.append(ch)
word = b''.join(word)
if word[0].isupper():
word2 = word.lower()
# if the lowercased word hasn't been read, treat the embedding as the lowercased word's
# otherwise, add the capitalized word to V
if word2 not in word2id:
word = word2
#origWord2id[word] = orig_wid
#origVocab.append(word)
if w in extraWords:
del extraWords[w]
isInterested = True
elif orig_wid < maxWordCount:
isInterested = True
else:
isInterested = False
skippedWords[w] = 1
orig_wid += 1
if isInterested:
word2id[word] = wid
vocab.append(word)
V[wid] = np.fromstring( fin.read(full_binvec_len), dtype=precision )
wid += 1
else:
fin.read(full_binvec_len)
if orig_wid % 1000 == 0:
print "\r%d %d %d \r" %( orig_wid, wid, len(extraWords) ),
if orig_wid > vocab_size:
raise ValueError( "%d words declared in header, but more are read" %(vocab_size) )
if wid < len(V):
V = V[:wid]
print "\n%d embeddings read, %d embeddings kept" %(orig_wid, wid)
# V: embeddings, vocab: array of words, word2id: dict of word to index in V
return V, vocab, word2id, skippedWords
def loadBigramFile( bigram_filename, topWordNum, extraWords, kappa=0.01 ):
print "Loading bigram file '%s':" %bigram_filename
BIGRAM = open(bigram_filename)
lineno = 0
vocab = []
word2id = {}
# 1: headers, 2: bigrams. for error msg printing
stage = 1
# In order to disable smoothing, just set kappa to 0.
# But when smoothing is disabled, some entries in logb_i will be log of 0
# After smoothing, entries in b_i are always positive, thus logb_i is fine
# do_smoothing=True
timer1 = Timer( "loadBigramFile()" )
try:
header = BIGRAM.readline()
lineno += 1
match = re.match( r"# (\d+) words, \d+ occurrences", header )
if not match:
raise ValueError(lineno, header)
wholeVocabSize = int(match.group(1))
print "Totally %d words" %wholeVocabSize
# If topWordNum < 0, read all focus words
if topWordNum < 0:
topWordNum = wholeVocabSize
# skip params
header = BIGRAM.readline()
header = BIGRAM.readline()
lineno += 2
match = re.match( r"# (\d+) bigram occurrences", header)
if not match:
raise ValueError(lineno, header)
header = BIGRAM.readline()
lineno += 1
if header[0:6] != "Words:":
raise ValueError(lineno, header)
# vector log_u, unigram log-probs
log_u = []
i = 0
wc = 0
# Read the word list, build the word2id mapping
# Keep first topWordNum words and words in extraWords, if any
while True:
header = BIGRAM.readline()
lineno += 1
header = header.rstrip()
# "Words" field ends
if not header:
break
words = header.split("\t")
for word in words:
w, freq, log_ui = word.split(",")
if i < topWordNum or w in extraWords:
word2id[w] = i
log_u.append(float(log_ui))
vocab.append(w)
i += 1
wc += 1
# Usually these two should match, unless the bigram file is corrupted
if wc != wholeVocabSize:
raise ValueError( "%d words declared in header, but %d seen" %(wholeVocabSize, wc) )
vocab_size = len(vocab)
print "%d words seen, top %d & %d extra to keep. %d kept" %( wholeVocabSize, topWordNum, len(extraWords), vocab_size )
log_u = np.array(log_u)
u = np.exp(log_u)
# renormalize unigram probs
if topWordNum < wholeVocabSize:
u = u / np.sum(u)
log_u = np.log(u)
k_u = kappa * u
# original B, without smoothing
#B = []
G = np.zeros( (vocab_size, vocab_size), dtype=np.float32 )
F = np.zeros( (vocab_size, vocab_size), dtype=np.float32 )
header = BIGRAM.readline()
lineno += 1
if header[0:8] != "Bigrams:":
raise ValueError(lineno, header)
print "Read bigrams:"
stage = 2
line = BIGRAM.readline()
lineno += 1
contextWID = 0
#pdb.set_trace()
while True:
line = line.strip()
# end of file
if not line:
break
# If we have read the bigrams of all the wanted words
if contextWID == vocab_size:
# if some words in extraWords are not read, there is bug
break
# word ID, word, number of distinct neighbors, sum of freqs of all neighbors, cut off freq
orig_wid, w, neighborCount, neighborTotalOccur, cutoffFreq = line.split(",")
orig_wid = int(orig_wid)
neighborTotalOccur = float(neighborTotalOccur)
if orig_wid % 200 == 0:
print "\r%d\r" %orig_wid,
if orig_wid <= topWordNum or w in extraWords:
recordCurrWord = True
# remove it from the extra list, as a double-check measure
# when all wanted words are read, the extra list should be empty
if w in extraWords:
del extraWords[w]
else:
recordCurrWord = False
# x_{.j}
x_i = np.zeros(vocab_size, dtype=np.float32)
skipRemainingNeighbors = False
while True:
line = BIGRAM.readline()
lineno += 1
# Empty line. Should be end of file
if not line:
break
# A comment. Just in case of future extension
# Currently only the last line in the file is a comment
if line[0] == '#':
continue
# beginning of the next word. Continue at the outer loop
# Neighbor lines always start with '\t'
if line[0] != '\t':
break
# if the current context word is not wanted, skip these lines
if not recordCurrWord or skipRemainingNeighbors:
continue
line = line.strip()
neighbors = line.split("\t")
for neighbor in neighbors:
w2, freq2, log_bij = neighbor.split(",")
if w2 in word2id:
i = word2id[w2]
x_i[i] = int(freq2)
# when meeting the first focus word not in vocab, all following focus words are not in vocab
# since neighbors are sorted ascendingly by ID
# So they are skipped to speed up reading
else:
skipRemainingNeighbors = True
break
# only save in F & G when this word is wanted
if recordCurrWord:
# Question: whether set F to the original freq or smoothed freq (assign F before or after smoothing)?
F[contextWID] = x_i
"""
x_i_norm1 = np.sum(x_i)
utrans = x_i_norm1 * k_u
x_i = x_i * (1 - kappa) + utrans
# the smoothing shoudn't change the norm1 of x_i
# i.e. x_i_norm1 = np.sum(x_i)
# After normalization, b_i = ( normalized x_i )*( 1 - kappa ) + u * kappa
b_i = x_i / np.sum(x_i)
"""
x_i /= neighborTotalOccur
b_i = x_i *( 1 - kappa ) + k_u
g_i = np.log(b_i) - log_u
G[contextWID] = g_i
contextWID += 1
except ValueError, e:
if len( e.args ) == 2:
print "Unknown line %d:\n%s" %( e.args[0], e.args[1] )
else:
exc_type, exc_obj, tb = sys.exc_info()
print "Source line %d: %s" %(tb.tb_lineno, e)
if stage == 1:
print header
else:
print line
exit(0)
print
BIGRAM.close()
return vocab, word2id, G, F, u
# If noncore_size == -1, all noncore words are loaded into the upperright and lowerleft blocks
# word2preID_core are the IDs of words in the pretrained embedding file
# If vocab_core and word2preID_core are specified, core words are limited to words in them
# Otherwise the top core_size words are core words
def loadBigramFileInBlock( bigram_filename, core_size, noncore_size=-1, word2preID_core={}, prewords_skipped={}, kappa=0.02 ):
if len(word2preID_core) > 0:
corewords_specified = True
# recordUpperleft is always the negation of corewords_specified. But sometimes is semantically clearer
recordUpperleft = False
# this core_size is used in comparsion with the total word count in the header
# this size might be inaccurate, as some words in word2preID_core might be missing from this bigram file
core_size = len(word2preID_core)
else:
corewords_specified = False
recordUpperleft = True
# if core words are not specified, core_size should always > 0,
# otherwise I don't know how many words are core words
if core_size < 0:
raise ValueError( "Argument error: core_size = %d < 0 when word2preID_core is not specified" %core_size )
if len(prewords_skipped) > 0:
raise ValueError( "Argument error: word2preID_core is empty but prewords_skipped is not" )
# if corewords_specified, return a list of coreword IDs in the pretrained mapping
# otherwise, return empty list (just for return value conformity)
coreword_preIDs = []
if not recordUpperleft:
# do not record G11/F11
print "Loading bigram file '%s' into 2 blocks. Will skip %d words" \
%( bigram_filename, len(prewords_skipped) )
else:
print "Loading bigram file '%s' into 3 blocks." %bigram_filename
BIGRAM = open(bigram_filename)
lineno = 0
vocab_all = []
vocab_core = []
vocab_noncore = []
word2id_all = {}
# origID is the original ID in this bigram file
# preID is the ID in the pretrained vec file
word2origID_all = {}
word2id_noncore = {}
word2id_core = {}
# stage 1: header and unigrams, stage 2: bigrams. for error msg printing
stage = 1
# do_smoothing must be True. Otherwise some entries in logb_i will be log of 0
# After smoothing, entries in b_i are always positive, thus logb_i is fine
# To reduce code modifications, this flag is not removed
timer1 = Timer( "loadBigramFileInBlock()" )
#pdb.set_trace()
try:
header = BIGRAM.readline()
lineno += 1
match = re.match( r"# (\d+) words, \d+ occurrences", header )
if not match:
raise ValueError(lineno, header)
wholeVocabSize = int(match.group(1))
print "Totally %d words" %wholeVocabSize
# at least consider one noncore word
min_vocab_size = core_size + max( noncore_size, 1 )
if min_vocab_size > wholeVocabSize:
raise ValueError( "%d (%d + %d) words demanded, but only %d declared in header" %( min_vocab_size, core_size,
max( noncore_size, 1 ), wholeVocabSize) )
# all the words are included in the vocab_all
# in this case, vocab_size needs to be initialized
if not corewords_specified:
if noncore_size < 0:
vocab_size = wholeVocabSize
noncore_size = vocab_size - core_size
else:
# core_size will be updated later
# some core words in word2preID_core may not be present in this bigram file
vocab_size = core_size + noncore_size
# if corewords_specified, noncore_size & vocab_size will be computed later, needn't to be initialized
# skip params
header = BIGRAM.readline()
header = BIGRAM.readline()
lineno += 2
match = re.match( r"# (\d+) bigram occurrences", header )
if not match:
raise ValueError(lineno, header)
header = BIGRAM.readline()
lineno += 1
if header[0:6] != "Words:":
raise ValueError(lineno, header)
# vector log_u, log-probs of all unigrams (at most vocab_size unigrams)
log_u0 = []
log_u0_core = []
log_u0_noncore = []
wc = 0
core_wc = 0
noncore_wc = 0
skipped_wc = 0
# maximum ID in the original order of core words
max_core_origID = 0
# Read the focus list, build the word2id_all / word2id_core mapping
# Read all context words of the core_size words
# Read top core_size context words of remaining words
while True:
header = BIGRAM.readline()
lineno += 1
header = header.rstrip()
# "Words" field ends
if not header:
break
words = header.split("\t")
for word in words:
w, freq, log_ui = word.split(",")
# load core words only in word2preID_core, other words as noncore
# core words may not be consecutive, they may be interspersed by noncore words
# So put them into two sets of arrays
if corewords_specified:
if w in word2preID_core:
word2id_core[w] = core_wc
core_wc += 1
coreword_preIDs.append( word2preID_core[w] )
log_u0_core.append(float(log_ui))
vocab_core.append(w)
if wc > max_core_origID:
max_core_origID = wc
elif w in prewords_skipped:
skipped_wc += 1
elif noncore_size < 0 or noncore_wc < noncore_size :
word2id_noncore[w] = noncore_wc
noncore_wc += 1
log_u0_noncore.append(float(log_ui))
vocab_noncore.append(w)
word2origID_all[w] = wc
wc += 1
# load fresh core words
else:
if wc == vocab_size:
break
word2id_all[w] = wc
if wc < core_size:
word2id_core[w] = wc
else:
word2id_noncore[w] = wc - core_size
log_u0.append(float(log_ui))
vocab_all.append(w)
wc += 1
if corewords_specified:
# some core words may be missing from the bigram file. So recompute core_size
# If these two don't match, then some specified core words don't appear in the unigram list
if core_size != core_wc:
print "WARN: %d core words demanded, but only %d read" %(core_size, core_wc)
core_size = core_wc
noncore_size = noncore_wc
vocab_size = core_size + noncore_size
log_u0 = log_u0_core + log_u0_noncore
vocab_all = vocab_core + vocab_noncore
word2id_all = word2id_core.copy()
# insert noncore words into word2id_all
# core ID \in [ 0, coresize - 1 ]
# noncore ID \in [ core_size, ... ]
for w in word2id_noncore:
word2id_all[w] = word2id_noncore[w] + core_size
else:
# core words are consecutive. So orig ID = id
max_core_origID = core_size
word2origID_all = word2id_all
if vocab_size > 0 and wc < vocab_size:
print "WARN: %d words demanded, but only %d read" %(vocab_size, wc)
vocab_size = wc
print "%d words in file, top %d to read into vocab (%d core, %d noncore), %d skipped" \
%( wholeVocabSize, vocab_size, core_size, noncore_size, skipped_wc )
# unigram prob & logprob of all the words
log_u0 = np.array(log_u0)
u0 = np.exp(log_u0)
# re-normalization is needed, as some unigrams may be out of vocab_all
u0 /= np.sum(u0)
log_u0 = np.log(u0)
log_u_core = log_u0[:core_size]
log_u_noncore = log_u0[core_size:]
k_u0 = kappa * u0
k_u_core = k_u0[:core_size]
k_u_noncore = k_u0[core_size:]
### Reading bigrams begins ###
header = BIGRAM.readline()
lineno += 1
if header[0:8] != "Bigrams:":
raise ValueError(lineno, header)
print "Read bigrams:"
stage = 2
line = BIGRAM.readline()
lineno += 1
contextWID = 0
# new G12, F12
# G12/F12: the upperright block
G12 = np.zeros( (core_size, noncore_size), dtype=np.float32 )
F12 = np.zeros( (core_size, noncore_size), dtype=np.float32 )
# new G21, F21
# G21/F21: the lowerleft block
# the lower right block (biggest) G22/F22 is ignored
G21 = np.zeros( (noncore_size, core_size), dtype=np.float32 )
F21 = np.zeros( (noncore_size, core_size), dtype=np.float32 )
# when reading core words, keep the upperleft block, the whole vocab
if recordUpperleft:
# new G11, F11
# G11/F11: the upperleft block
G11 = np.zeros( (core_size, core_size), dtype=np.float32 )
F11 = np.zeros( (core_size, core_size), dtype=np.float32 )
rowLength = vocab_size
k_u = k_u0
log_u = log_u0
# when reading core words, only keep the upperright block, noncore_size words
else:
rowLength = noncore_size
k_u = k_u_noncore
log_u = log_u_noncore
# focusIDLimit: the limit of neighbor wid
# In the beginning, read all neighbors
focusIDLimit = vocab_size
# vars are initialized like those of a core word,
# So pretend the previous nonexistent word is a core word
lastContextIsCore = True
#pdb.set_trace()
core_readcount = 0
noncore_readcount = 0
coreMsg_printed = False
while True:
line = line.strip()
# end of file
if not line:
break
# We have read the bigrams of all the wanted words
if contextWID == vocab_size:
break
# word ID, word, number of distinct neighbors, sum of freqs of all neighbors, cut off freq
orig_wid, w, neighborCount, neighborTotalOccur, cutoffFreq = line.split(",")
orig_wid = int(orig_wid)
neighborTotalOccur = float(neighborTotalOccur)
if w in word2id_core:
# the current context word is a core word
contextIsCore = True
wid = word2id_core[w]
# context type switches from noncore to core, update relevant variables
# if context type doesn't change (last context is also core), then just keep vars unchanged
# context type switching should only happen very few times
if not lastContextIsCore:
focusIDLimit = vocab_size
if recordUpperleft:
rowLength = vocab_size
k_u = k_u0
log_u = log_u0
# when reading core words, only keep the upperright block, noncore_size words
else:
rowLength = noncore_size
k_u = k_u_noncore
log_u = log_u_noncore
lastContextIsCore = True
elif w in word2id_noncore:
contextIsCore = False
wid = word2id_noncore[w]
# context type switches from core to noncore, update relevant variables
# if context type doesn't change (last context is also noncore), then just keep vars unchanged
# context type switching should only happen very few times
if lastContextIsCore:
# in a row of noncore (context) word, only freqs of core (focus) words are recorded
focusIDLimit = max_core_origID
rowLength = core_size
k_u = k_u_core
log_u = log_u_core
lastContextIsCore = False
# x_{i.}
x_i = np.zeros(rowLength, dtype=np.float32)
if w in prewords_skipped:
saveCurrRow = False
skipRemainingNeighbors = True
else:
saveCurrRow = True
skipRemainingNeighbors = False
while True:
line = BIGRAM.readline()
lineno += 1
# Empty line. Should be end of file
if not line:
break
# Encounter a comment. Just in case of future extension
# Currently only the last line in the file is a comment after the header
if line[0] == '#':
continue
# Beginning of the next word. Continue at the outer loop
# Neighbor lines always start with '\t'
if line[0] != '\t':
break
if skipRemainingNeighbors:
continue
line = line.strip()
neighbors = line.split("\t")
for neighbor in neighbors:
w2, freq2, log_bij = neighbor.split(",")
# w2 in skip list, and surely not in word2id_all
# so check here to avoid setting skipRemainingNeighbors
if w2 in prewords_skipped:
continue
# when meeting the first focus word out of vocab_all, all following focus words are not in vocab_all
# since neighbors are sorted ascendingly by ID
# So they are skipped to speed up reading
if w2 not in word2id_all:
skipRemainingNeighbors = True
break
origID = word2origID_all[w2]
# On a noncore row. Should have focus word orig ID <= max_core_origID
# origIDs of core words may be interspersed by origIDs of noncore words
# but IDs of core words are consecutive, and preceding IDs of noncore words
if not contextIsCore and origID > max_core_origID:
skipRemainingNeighbors = True
break
freq2 = int(freq2)
# On a core (context) row.
# If recordUpperleft, use the map from whole vocab to IDs;
# otherwise use the map from core words to IDs
if contextIsCore:
if recordUpperleft:
# w2id: id of w2
w2id = word2id_all[w2]
x_i[w2id] = freq2
# don't keep upperleft block. core (focus) words are discarded
# w2id \in [ 0, noncore_size - 1 ]
elif w2 in word2id_noncore:
w2id = word2id_noncore[w2]
x_i[w2id] = freq2
# On a noncore (context) row. Only record core (focus) words
elif w2 in word2id_core:
w2id = word2id_core[w2]
x_i[w2id] = freq2
if not saveCurrRow:
continue
# Question: whether set F to the original freq or smoothed freq (assign F before or after smoothing)?
if contextIsCore:
if recordUpperleft:
F11[core_readcount] = x_i[:core_size]
F12[core_readcount] = x_i[core_size:]
else:
# As w2id \in [ 0, noncore_size - 1 ], no offset is needed
F12[core_readcount] = x_i
else:
F21[noncore_readcount] = x_i
"""
x_i_norm1 = np.sum(x_i)
utrans = x_i_norm1 * k_u
x_i = x_i * (1 - kappa) + utrans
# the smoothing shoudn't change the norm1 of x_i
# i.e. x_i_norm1 = np.sum(x_i)
# normalization
b_i = x_i / np.sum(x_i)
"""
x_i /= neighborTotalOccur
b_i = x_i * ( 1 - kappa ) + k_u
g_i = np.log(b_i) - log_u
if contextIsCore:
if recordUpperleft:
G11[core_readcount] = g_i[:core_size]
G12[core_readcount] = g_i[core_size:]
else:
# As w2id \in [ 0, noncore_size - 1 ], no offset is needed
G12[core_readcount] = g_i
else:
G21[noncore_readcount] = g_i
contextWID += 1
if contextIsCore:
core_readcount += 1
else:
noncore_readcount += 1
if orig_wid % 200 == 0:
print "\r%d (%d core, %d noncore)\r" %( orig_wid, core_readcount, noncore_readcount ),
if not coreMsg_printed and core_readcount == core_size:
print "\n%d core words are all read." %(core_size)
coreMsg_printed = True
except ValueError, e:
if len( e.args ) == 2:
print "Unknown line %d:\n%s" %( e.args[0], e.args[1] )
else:
exc_type, exc_obj, tb = sys.exc_info()
print "Source line %d: %s" %(tb.tb_lineno, e)