forked from linguistica-uchicago/lxa5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_manifolds.py
419 lines (338 loc) · 15.8 KB
/
find_manifolds.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
#-*- coding: <utf-16> -*-
import codecs
import os
import sys
import string
import operator
mywords=dict()
from math import sqrt
from collections import defaultdict
import numpy
from numpy import *
#-----------------------------------------------------------------------#
# #
# This program takes a trigram file and a word list #
# and creates a file with lists of most similar words. #
# John Goldsmith and Wang Xiuli 2012. #
# #
#-----------------------------------------------------------------------#
#---------------------------------------------------------------------------#
# Variables to be changed by user
#---------------------------------------------------------------------------#
LatexFlag = True
PrintEigenvectorsFlag = True
unicodeFlag = False
FileEncoding = "ascii"
shortfilename = "english"
outshortfilename = "english"
languagename = "english"
datafilelocation = "linguistica/datasets/find_manifolds_files"
wordfolder = datafilelocation + languagename + "/dx1_files/"
trigramfolder = datafilelocation + languagename + "/trig/"
outfolder = datafilelocation + languagename + "/neighbors/"
NumberOfWordsForContext = 1000 # 40000
NumberOfEigenvectors = 11
NumberOfWordsForAnalysis = 500 #4000
NumberOfNeighbors = 9
punctuation = " $/+.,;:?!()\"[]"
if NumberOfWordsForAnalysis > NumberOfWordsForContext:
print "No -- the number of words to be shown must be no larger than the number of words used for the matrix."
#---------------------------------------------------------------------------#
# File names
#---------------------------------------------------------------------------#
infileTrigramsname = trigramfolder + shortfilename + "_trigrams.trig"
infileWordsname = wordfolder + shortfilename + ".dx1"
outfilenameEigenvectors = outfolder + outshortfilename + "_PoS_words_eigenvectors" + ".txt"
outfilenameNeighbors = outfolder + outshortfilename + "_PoS_closest" + "_" + str(NumberOfNeighbors ) + "_neighbors.txt"
outfilenameLatex = outfolder + outshortfilename + "_latex.tex"
outfilenameContexts = outfolder + outshortfilename + "_contexts.txt"
print "\n\nI am looking for: ", infileTrigramsname
#---------------------------------------------------------------------------#
# Variables
#---------------------------------------------------------------------------#
linecount = 0
#wordtoindex_context = dict() #takes word, gives its context-index
contexts = dict()
#contextwordlist = list() # this is a word list created from the trigram file.
analyzedwordlist = list() # this means that the info comes from the independent word file
analyzedworddict = dict()
#---------------------------------------------------------------------------#
# Open files for reading and writing
#---------------------------------------------------------------------------#
if unicodeFlag:
trigramfile =codecs.open(infileTrigramsname, encoding = FileEncoding)
wordfile =codecs.open(infileWordsname, encoding = FileEncoding)
if PrintEigenvectorsFlag:
outfileEigenvectors = codecs.open (outfilename1, "w",encoding = FileEncoding)
outfileNeighbors = codecs.open (outfileneighborsname, "w",encoding = FileEncoding)
else:
if PrintEigenvectorsFlag:
outfileEigenvectors = open (outfilenameEigenvectors, "w")
outfileNeighbors = open (outfilenameNeighbors, "w")
outfileLatex = open (outfilenameLatex, "w")
outfileContexts = open (outfilenameContexts, "w")
wordfile = open(infileWordsname)
trigramfile = open(infileTrigramsname)
print "Language is", languagename, ". File name:", shortfilename, ". Number of words", NumberOfWordsForContext, "."
if PrintEigenvectorsFlag:
print >>outfileEigenvectors,"#", \
languagename, "\n#", \
shortfilename,"\n#", \
"Number of words used for matrix", NumberOfWordsForContext, "\n#",\
"Number of words analyzed", NumberOfWordsForAnalysis,"\n#", \
"Number of neighbors identified", NumberOfNeighbors, "\n#","\n#"
print >>outfileNeighbors, "#", \
languagename, "\n#",\
shortfilename, "\n#",\
"Number of words used for context", NumberOfWordsForContext,"\n#", \
"Number of words analyzed", NumberOfWordsForAnalysis,"\n#", \
"Number of neighbors identified", NumberOfNeighbors,"\n#","\n#"
#---------------------------------------------------------------------------#
# Read trigram file
#---------------------------------------------------------------------------#
from_word_to_context = dict()
if infileTrigramsname[-5:]==".trig":
for line in wordfile:
pieces = line.split()
#print pieces[0]
if pieces[0] == "#":
continue
mywords[pieces[0]] = int(pieces[1])
print "1. Word file is ", infileWordsname
wordfile.close()
analyzedwordlist = sorted(mywords,key=mywords.__getitem__,reverse=True)
analyzedwordlist[NumberOfWordsForAnalysis:] = []
for i in range(NumberOfWordsForAnalysis):
analyzedworddict[analyzedwordlist[i]] = i
#from_word_to_context[analyzedwordlist[i]] = dict()
print "2. Reading in trigram file."
for line in trigramfile:
linecount += 1
line = line.split()
if line[0] == "#":
continue
thesewords = line[0].split("_")
#print thesewords
focus_word = thesewords[1]
if focus_word in analyzedworddict:
context = thesewords[0] + "_" + thesewords[2]
if not context in contexts:
contexts[context] = dict()
contexts[context][focus_word] = 1
if not focus_word in from_word_to_context:
from_word_to_context[focus_word] = list()
from_word_to_context[focus_word].append(context)
#Left trigrams
focus_word = thesewords[0]
if focus_word in analyzedworddict:
context = "_" + thesewords[1] + "+" + thesewords[2]
if not context in contexts:
contexts[context] = dict()
contexts[context][focus_word] = 1
if focus_word not in from_word_to_context:
from_word_to_context[focus_word] = list()
from_word_to_context[focus_word].append(context)
#Right trigrams
focus_word = thesewords[2]
if focus_word in analyzedworddict:
context = thesewords[0] + "+" + thesewords[1] + "_"
if not context in contexts:
contexts[context] = dict()
contexts[context][focus_word] = 1
if focus_word not in from_word_to_context:
from_word_to_context[focus_word] = list()
from_word_to_context[focus_word].append(context)
contextlist = contexts.keys()
print "%-50s %3d = number of contexts" % ("3. End of words and counts.", len(contextlist) )
#---------------------------------------------------------------------------#
# Count context features shared by words
#---------------------------------------------------------------------------#
print "%-50s" % "4. Counting context features shared by words...",
NearbyWords = zeros( (NumberOfWordsForAnalysis,NumberOfWordsForAnalysis) )
count = 0
for context in contexts:
count += 1
# if count%10000 == 0:
# print count/10000,
if len(contexts[context]) == 1:
continue
for word1 in contexts[context]:
w1 = analyzedworddict[word1]
for word2 in contexts[context]:
w2 = analyzedworddict[word2]
if not w1 == w2:
NearbyWords[w1,w2] += 1
print "Done.", count
#---------------------------------------------------------------------------#
# Normalize.
#---------------------------------------------------------------------------#
print "%-50s" % "5. Normalizing nearness measurements....",
Diameter = defaultdict()
count = 0
for w1 in range(NumberOfWordsForAnalysis):
for w2 in range(NumberOfWordsForAnalysis):
if w1 == w2:
continue
if not w1 in Diameter:
Diameter[w1] = 0
Diameter[w1] += NearbyWords[w1,w2]
count += 1
print "Done.", count
#---------------------------------------------------------------------------#
# Incidence graph
#---------------------------------------------------------------------------#
print "%-50s" % "6. We compute the incidence graph....",
incidencegraph= zeros( (NumberOfWordsForAnalysis,NumberOfWordsForAnalysis) )
count = 0
for w1 in range( NumberOfWordsForAnalysis ):
for w2 in range( NumberOfWordsForAnalysis ):
if w1 == w2:
incidencegraph[w1,w1] = Diameter[w1]
else:
incidencegraph[w1, w2] = NearbyWords[w1,w2]
count += 1
print "Done.", count
#---------------------------------------------------------------------------#
# Normalize the laplacian.
#---------------------------------------------------------------------------#
print "%-50s" % "7. We normalize the laplacian....",
#Normalize the laplacian:
count = 0
mylaplacian = zeros((NumberOfWordsForAnalysis,NumberOfWordsForAnalysis) )
for i in range(NumberOfWordsForAnalysis):
mylaplacian[i,i] = 1
for j in range(NumberOfWordsForAnalysis):
if not i == j:
if incidencegraph[i,j] == 0:
mylaplacian[i,j]=0
else:
mylaplacian[i,j] = -1 * incidencegraph[i,j]/ math.sqrt ( Diameter[i] * Diameter[j] )
count += 1
print "Done.", count
#---------------------------------------------------------------------------#
# Compute eigenvectors.
#---------------------------------------------------------------------------#
print "%-50s" % "8. Compute eigenvectors...",
myeigenvalues, myeigenvectors = numpy.linalg.eigh(mylaplacian)
print "Done."
formatstr = '%15d %15s %10.3f'
#---------------------------------------------------------------------------#
# Generate latex output.
#---------------------------------------------------------------------------#
if LatexFlag:
#Latex output
print >>outfileLatex, "%", infileWordsname
print >>outfileLatex, "\\documentclass{article}"
print >>outfileLatex, "\\usepackage{booktabs}"
print >>outfileLatex, "\\begin{document}"
data = dict() # key is eigennumber, value is list of triples: (index, word, eigen^{th} coordinate) sorted by increasing coordinate
print ("9. Printing contexts to latex file.")
formatstr = '%20d %15s %10.3f'
headerformatstr = '%20s %15s %10.3f'
NumberOfWordsToDisplayForEachEigenvector = 20
if PrintEigenvectorsFlag:
for eigenno in range(NumberOfEigenvectors):
print >>outfileEigenvectors
print >>outfileEigenvectors,headerformatstr %("Eigenvector number", "word" , myeigenvalues[eigenno])
print >>outfileEigenvectors,"_____________________________________________"
for wordno in range(NumberOfWordsForAnalysis):
print >>outfileEigenvectors, formatstr %(eigenno, analyzedwordlist[wordno], myeigenvectors[wordno,eigenno])
if LatexFlag:
for eigenno in range(NumberOfEigenvectors):
eigenlist=list()
#data[eigenno] = list()
data = list()
for wordno in range (NumberOfWordsForAnalysis):
eigenlist.append( (wordno,myeigenvectors[wordno, eigenno]) )
eigenlist.sort(key=lambda x:x[1])
print >>outfileLatex
print >>outfileLatex, "Eigenvector number", eigenno, "\n"
print >>outfileLatex, "\\begin{tabular}{lll}\\toprule"
print >>outfileLatex, " & word & coordinate \\\\ \\midrule "
for i in range(NumberOfWordsForAnalysis):
word = analyzedwordlist[eigenlist[i][0]]
coord = eigenlist[i][1]
if i < NumberOfWordsToDisplayForEachEigenvector or i > NumberOfWordsForAnalysis - NumberOfWordsToDisplayForEachEigenvector:
data.append((i, word , coord ))
#for eigenno in data.keys():
for (i, word, coord) in data:
if word == "&":
word = "\&"
print >>outfileLatex, "%5d & %10s & %10.3f \\\\" % (i, word, coord)
print >>outfileLatex, "\\bottomrule \n \\end{tabular}", "\n\n"
print >>outfileLatex, "\\newpage"
print >>outfileLatex, "\\end{document}"
#---------------------------------------------------------------------------#
# Finding coordinates in space of low dimensionality
#---------------------------------------------------------------------------#
print "10. Finding coordinates in space of low dimensionality."
coordinates = dict()
wordsdistance = dict()
closestNeighbors = dict() #a dict whose values are lists; the lists are the closest words to the key.
thislist = list()
for wordno in range(NumberOfWordsForAnalysis):
coordinates[wordno]= list()
for eigenno in range (1,NumberOfEigenvectors):
coordinates[wordno].append ( myeigenvectors[ wordno, eigenno ] )
for wordno1 in range(NumberOfWordsForAnalysis):
word = analyzedwordlist[wordno1]
wordsdistance[word] = list()
for wordno2 in range (NumberOfWordsForAnalysis):
distance = 0
for coordno in range(NumberOfEigenvectors-1):
x = coordinates[wordno1][coordno] - coordinates[wordno2][coordno]
distance += abs(x * x * x)
wordsdistance[word].append((wordno2,distance))
#---------------------------------------------------------------------------#
# Finding closest neighbors on the manifold's approximation
#---------------------------------------------------------------------------#
print "11. Finding closest neighbors on the manifold('s approximation)."
for wordno1 in range(NumberOfWordsForAnalysis):
word1 = analyzedwordlist[wordno1]
if not word1 in closestNeighbors:
closestNeighbors[word1] = list()
wordsdistance[word1].sort(key=lambda x:x[1])
print >>outfileNeighbors, word1,
count = 0
for (wordno2, distance) in wordsdistance[word1]:
if wordno1 == wordno2:
continue
count += 1
word2 = analyzedwordlist[wordno2]
print >>outfileNeighbors, word2,
closestNeighbors[word1].append(word2)
if count >= NumberOfNeighbors:
break
print >>outfileNeighbors
outfileNeighbors.close()
#---------------------------------------------------------------------------#
# Print contexts shared by nearby words
#---------------------------------------------------------------------------#
numberperrow= 5
for word in analyzedwordlist:
print >>outfileContexts,"\n", word,"\n\t",
number = 1
if (False):
for context in from_word_to_context[word]:
if len(contexts[context]) >100:
print >>outfileContexts, "%-25s %3d " % ( context, len(contexts[context])),
number += 1
if number == numberperrow:
number = 1
print >>outfileContexts, "\n\t",
these_contexts = set( from_word_to_context[word] )
for word2 in closestNeighbors[word]:
print >>outfileContexts, word2
these_contexts.intersection( set(from_word_to_context[word2]))
for context in these_contexts:
if len(contexts[context]) >100:
print >>outfileContexts, "%-25s %3d " % ( context, len(contexts[context])),
number += 1
if number == numberperrow:
number = 1
print >>outfileContexts, "\n\t",
print "Exiting successfully."
#os.popen("latex " + outfilenameLatex )
if PrintEigenvectorsFlag:
outfileEigenvectors.close()
outfileNeighbors.close()