-
Notifications
You must be signed in to change notification settings - Fork 0
/
online_pmi_informed_ling.py
352 lines (300 loc) · 12.2 KB
/
online_pmi_informed_ling.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
from collections import defaultdict
import itertools as it
import sys, distances, igraph, utils
import numpy as np
import random, codecs
import DistanceMeasures as DM
from sklearn import metrics
#from lingpy import *
from utils import *
random.seed(1234)
##TODO: Add a ML based estimation of distance or a JC model for distance between two sequences
##Separate clustering code.
##Add doculect distance as regularization
MAX_ITER =15
tolerance = 0.001
infomap_threshold = 0.5
min_batch = 256
margin = 0.0
dataname = sys.argv[1]
if len(sys.argv) > 2:
lang_weight = float(sys.argv[2])
else:
lang_weight = 0.3
char_list = []
def read_data_ielex_type(fname):
line_id = 0
data_dict = defaultdict(lambda : defaultdict())
cogid_dict = defaultdict(lambda : defaultdict())
words_dict = defaultdict(lambda : defaultdict(list))
langs_dict = defaultdict()
langs_list = []
#f = codecs.open(fname, "r", "utf8")
f = open(fname)
header = f.readline().strip("\n").split("\t")
cogid_idx = header.index("cognate_class")
word_idx = header.index("asjp")
f.readline()
for line in f:
line = line.strip()
arr = line.split("\t")
lang, concept = arr[0], arr[2]
cogid = arr[cogid_idx]
cogid = cogid.replace("-","")
cogid = cogid.replace("?","")
#asjp_word = clean_word(arr[4].split(",")[0])
asjp_word = arr[word_idx].replace(" ","")
asjp_word = cleanASJP(asjp_word)
for ch in asjp_word:
if ch not in char_list:
char_list.append(ch)
if len(asjp_word) < 1:
continue
data_dict[concept][line_id,lang] = asjp_word
cogid_dict[concept][line_id,lang] = cogid
words_dict[lang][concept].append(asjp_word)
langs_dict[line_id] = lang
if lang not in langs_list:
langs_list.append(lang)
line_id += 1
f.close()
print(list(data_dict.keys()))
return (data_dict, cogid_dict, words_dict, langs_list, langs_dict)
def get_lang_distance(words_dict, pmidict, langs_list):
langDistance = defaultdict(float)
n_concepts = defaultdict(float)
for l1, l2 in it.combinations_with_replacement(langs_list, r=2):
#if l1 != l2: continue
for concept in words_dict[l1]:
if concept not in words_dict[l2]: continue
w1 = words_dict[l1][concept]
w2 = words_dict[l2][concept]
for x, y in it.product(w1, w2):
if pmidict is not None:
score = distances.sigmoid(distances.needleman_wunsch(x, y, scores=pmidict, gop=-2.5, gep=-1.75)[0])
#if x==y: print(l1, l2, x, y, score)
#print(x, y, score)
#score = max(0,distances.nw(x, y, lodict=pmidict, gp1=-2.5, gp2=-1.75)[0])
#score = 1.0 - (1.0/(1.0+np.exp(-score)))
else:
#print("LDN")
score = 1.0-distances.ldn(x, y)
#if x==y: print(score)
n_concepts[l1,l2] += 1.0
#n_concepts[l2,l1] += 1.0
langDistance[l1,l2] += score#/n_words
if l1 != l2:
langDistance[l2,l1] = langDistance[l1,l2]
n_concepts[l2,l1] = n_concepts[l1,l2]
#print(l1, l2, langDistance[l1,l2])
for k in langDistance:
langDistance[k] = langDistance[k]/n_concepts[k]
#print("Distance ", k, langDistance[k])
return langDistance
def igraph_clustering(matrix, threshold, method='labelprop'):
"""
Method computes Infomap clusters from pairwise distance data.
"""
random.seed(1234)
G = igraph.Graph()
vertex_weights = []
for i in range(len(matrix)):
G.add_vertex(i)
vertex_weights += [0]
# variable stores edge weights, if they are not there, the network is
# already separated by the threshold
weights = None
for i,row in enumerate(matrix):
for j,cell in enumerate(row):
if i < j:
if cell <= threshold:
G.add_edge(i, j, weight=1-cell, distance=cell)
weights = 'weight'
if method == 'infomap':
comps = G.community_infomap(edge_weights=weights,
vertex_weights=None)
elif method == 'labelprop':
comps = G.community_label_propagation(weights=weights,
initial=None, fixed=None)
elif method == 'ebet':
dg = G.community_edge_betweenness(weights=weights)
oc = dg.optimal_count
comps = False
while oc <= len(G.vs):
try:
comps = dg.as_clustering(dg.optimal_count)
break
except:
oc += 1
if not comps:
print('Failed...')
comps = list(range(len(G.sv)))
input()
elif method == 'multilevel':
comps = G.community_multilevel(return_levels=False)
elif method == 'spinglass':
comps = G.community_spinglass()
D = {}
for i,comp in enumerate(comps.subgraphs()):
vertices = [v['name'] for v in comp.vs]
for vertex in vertices:
D[vertex] = i+1
return D
def infomap_concept_evaluate_scores(d, lodict, langDistance, langs_dict, gop, gep):
average_fscore = []
f_scores = []
bin_mat, n_clusters = [], 0
f_preds = open("temp.cognates", "w")
f_preds.write("gloss\tlanguage\tasjp\tcognate class\n")
for concept in d:
ldn_dist_dict = defaultdict(lambda: defaultdict(float))
langs = list(d[concept].keys())
if len(langs) == 1:
print(concept)
continue
scores, cognates = [], []
for l1, l2 in it.combinations(langs, r=2):
if d[concept][l1].startswith("-") or d[concept][l2].startswith("-"): continue
w1, w2 = d[concept][l1], d[concept][l2]
lang1, lang2 = l1[1], l2[1]
raw_score = distances.needleman_wunsch(w1, w2, scores=lodict, gop=gop, gep=gep)[0]
score = 1.0 - (1.0/(1.0+np.exp(-raw_score)))
score = 1.0/(1.0+np.exp(-raw_score))
score = (score*(1.0-lang_weight))+(langDistance[lang1,lang2]*lang_weight)
#print(w1, w2,raw_score, score)
ldn_dist_dict[l1][l2] = 1.0-score
ldn_dist_dict[l2][l1] = ldn_dist_dict[l1][l2]
distMat = np.array([[ldn_dist_dict[ka][kb] for kb in langs] for ka in langs])
clust = igraph_clustering(distMat, infomap_threshold, method="labelprop")
predicted_labels = defaultdict()
predicted_labels_words = defaultdict()
for k, v in clust.items():
predicted_labels[langs[k]] = v
predicted_labels_words[langs[k],d[concept][langs[k]]] = v
f_preds.write(concept+"\t"+ langs[k][1]+"\t"+ d[concept][langs[k]]+"\t"+ str(v)+"\n")
predl, truel = [], []
#if args.eval:
for l in langs:
truel.append(cogid_dict[concept][l])
predl.append(predicted_labels[l])
scores = DM.b_cubed(truel, predl)
print(concept, len(langs), scores[0], scores[1], scores[2], len(set(clust.values())), len(set(truel)), sep="\t")
f_scores.append(list(scores))
n_clusters += len(set(clust.values()))
#if args.nexus:
#t = dict2binarynexus(predicted_labels, lang_list)
#bin_mat += t
#if args.eval:
f_scores = np.mean(np.array(f_scores), axis=0)
print(f_scores[0], f_scores[1], 2.0*f_scores[0]*f_scores[1]/(f_scores[0]+f_scores[1]))
f_preds.close()
return bin_mat
def calc_pmi(alignment_dict, char_list, scores, initialize=False):
sound_dict = defaultdict(float)
relative_align_freq = 0.0
relative_sound_freq = 0.0
count_dict = defaultdict(float)
if initialize == True:
for c1, c2 in it.product(char_list, repeat=2):
if c1 == "-" or c2 == "-":
continue
count_dict[c1,c2] += 0.001
count_dict[c2,c1] += 0.001
sound_dict[c1] += 2.0*0.001
sound_dict[c2] += 2.0*0.001
for alignment, score in zip(alignment_dict, scores):
#score = 1.0
for a1, a2 in alignment:
if a1 == "-" or a2 == "-":
continue
count_dict[a1,a2] += 1.0*score
count_dict[a2,a1] += 1.0*score
sound_dict[a1] += 2.0*score
sound_dict[a2] += 2.0*score
#relative_align_freq += 2.0
#relative_sound_freq += 2.0
relative_align_freq = sum(list(count_dict.values()))
relative_sound_freq = sum(list(sound_dict.values()))
for a in count_dict.keys():
m = count_dict[a]
if m <=0: print(a, m)
assert m>0
num = np.log(m)-np.log(relative_align_freq)
denom = np.log(sound_dict[a[0]])+np.log(sound_dict[a[1]])-(2.0*np.log(relative_sound_freq))
val = num - denom
count_dict[a] = val
return count_dict
data_dict, cogid_dict, words_dict, langs_list, langs_dict = read_data_ielex_type(dataname)
print("Character list \n\n", char_list)
print("Length of character list ", len(char_list))
word_list = []
langDistance = get_lang_distance(words_dict, None, langs_list)
#print(langDistance)
for concept in data_dict:
print(concept)
words = []
for idx in data_dict[concept]:
#words.append([data_dict[concept][idx], idx[1]])
words.append(data_dict[concept][idx])
for x, y in it.combinations(words, r=2):
#if distances.nw(x, y, lodict=None, gp1=-2.5,gp2=-1.75)[0] > 0.0:
#score = (distances.ldn(x[0], y[0])*(1.0-lang_weight)) + (langDistance[x[1], y[1]]*lang_weight)
#score = distances.ldn(x[0], y[0]) *langDistance[x[1], y[1]]
score = distances.ldn(x, y)
#print(x, y, score)
#if x[1] == y[1]: print(x, y)
if score <=1.0:
word_list += [[x,y]]
#print(x,y)
pmidict = None
n_examples, n_updates, alpha = len(word_list), 0, 0.75
n_wl = len(word_list)
print("Size of initial list ", n_wl)
pmidict = defaultdict(float)
for n_iter in range(MAX_ITER):
random.shuffle(word_list)
pruned_wl = []
n_zero = 0.0
print("Iteration ", n_iter)
for idx in range(0, n_wl, min_batch):
wl = word_list[idx:idx+min_batch]
eta = np.power(n_updates+2, -alpha)
algn_list, scores = [], []
for w1, w2 in wl:
#print(w1,w2,sc)
l1, l2 = w1[1], w2[1]
if not pmidict:
word_sim, alg = distances.needleman_wunsch(w1, w2, scores={}, gop =-2.5, gep=-1.75)
else:
word_sim, alg = distances.needleman_wunsch(w1, w2, scores=pmidict, gop=-2.5, gep=-1.75)
#print(w1, w2, s)
#combined_s = distances.sigmoid(s)*langDistance[l1,l2]
combined_s = (distances.sigmoid(word_sim)*(1.0-lang_weight))+((langDistance[l1,l2])*lang_weight)
if word_sim <= margin:
n_zero += 1.0
#continue
#s = s/max(len(w1), len(w2))
algn_list.append(alg)
#scores.append(distances.sigmoid(word_sim))
scores.append(distances.sigmoid(combined_s))
#pruned_wl.append([w1[::-1], w2[::-1], s])
pruned_wl.append([w1, w2])
mb_pmi_dict = calc_pmi(algn_list, char_list, scores, initialize=True)
for k, v in mb_pmi_dict.items():
pmidict_val = pmidict[k]
pmidict[k] = (eta*v) + ((1.0-eta)*pmidict_val)
n_updates += 1
print("Number of examples", n_wl, "Non zero examples", n_wl-n_zero, "number of updates", n_updates, sep="\t")
word_list = pruned_wl[:]
n_wl = len(word_list)
#infomap_concept_evaluate_scores(data_dict, pmidict, -2.5, -1.75)
langDistance = get_lang_distance(words_dict, pmidict, langs_list)
bin_mat = infomap_concept_evaluate_scores(data_dict, pmidict, langDistance,langs_dict, -2.5, -1.75)
sys.exit(1)
print("begin data;")
print(" dimensions ntax=", str(nlangs), "nchar=", str(nchar), ";\nformat datatype=restriction interleave=no missing= ? gap=-;\nmatrix\n")
for row, lang in zip(np.array(bin_mat).T, lang_list):
#print(row,len(row), "\n")
rowx = "".join([str(x) for x in row])
print(lang, "\t", rowx.replace("2","?"))
print(";\nend;")