-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·1545 lines (1380 loc) · 65.1 KB
/
main.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
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import atexit
import bisect
import collections
import cPickle as pickle
import datetime
import HTMLParser
import io
import operator
import os
import pdb
import re
import numpy as np
import pandas as pd
import pymysql
from sklearn.metrics import mutual_info_score
from scipy.stats import entropy
import decorators
import ngram
import viewcounts
import model
# set a few options
pd.options.mode.chained_assignment = None
pd.set_option('display.width', 1000)
class DbConnector(object):
def __init__(self, db):
self.db_host = '127.0.0.1'
self.db_connection = pymysql.connect(host=self.db_host,
port=3306,
user='root',
passwd='master',
db=db,
charset='utf8')
self.db_cursor = self.db_connection.cursor(pymysql.cursors.DictCursor)
self.db_cursor_nobuff = self.db_connection.cursor(
pymysql.cursors.SSCursor)
self.db = db
atexit.register(self.close)
def close(self):
self.db_cursor.close()
self.db_connection.close()
def execute(self, _statement, _args=None):
self.db_cursor.execute(_statement, _args)
if _statement.lower().startswith("select"):
return self.db_cursor.fetchall()
def commit(self):
self.db_cursor.connection.commit()
def fetch_cursor(self, _statement, _args):
self.db_cursor.execute(_statement, _args)
return self.db_cursor
def last_id(self):
return self.db_connection.insert_id()
def fetch_cursor_nobuff(self, _statement, _args):
self.db_cursor_nobuff.execute(_statement, _args)
return self.db_cursor_nobuff
class Wikigame(object):
def __init__(self, label):
# print(label)
self.label = label
self.data = None
self.graph = None
self.html_base_folder = os.path.join('data', label, 'wpcd', 'wp')
self.plaintext_folder = os.path.join('data', label, 'wpcd', 'plaintext')
self.cache_folder = os.path.join('data', label, 'cache')
self.link2pos_first, self.link2pos_last = {}, {}
self.length, self.pos2link, self.pos2linklength = {}, {}, {}
self.ib_length, self.lead_length = {}, {}
self.link_context, self.link_sets = None, None
# build some mappings from the database
self.db_connector = DbConnector(self.label)
pages = self.db_connector.execute('SELECT * FROM pages')
self.id2title = {p['id']: p['name'] for p in pages}
self.id2name = {p['id']: re.findall(r'\\([^\\]*?)\.htm', p['link'])[0]
for p in pages}
self.name2id = {v: k for k, v in self.id2name.items()}
games = self.db_connector.execute("""SELECT * FROM games
WHERE `game_name` LIKE 'PLAIN%'""")
self.game2start_target = {v['game_name']:
(self.id2name[v['start_page_id']],
self.id2name[v['goal_page_id']])
for v in games}
nodes = self.db_connector.execute('SELECT * FROM node_data')
self.id2deg_out = {p['node_id']: p['out_degree'] for p in nodes}
self.id2deg_in = {p['node_id']: p['in_degree'] for p in nodes}
links = self.db_connector.execute('''SELECT page_id,
SUM(amount) as links
FROM links GROUP BY page_id;''')
self.id2links = {p['page_id']: int(p['links']) for p in links}
def load_graph(self, graph_tool=False):
# read the graph
path = os.path.join('data', self.label, 'links.txt')
if graph_tool:
self.graph = self.read_edge_list_gt(path)
else:
self.graph = self.read_edge_list_nx(path)
def read_edge_list_gt(self, filename, directed=True, parallel_edges=False):
if gt is None:
import graph_tool.all as gt
graph = gt.Graph(directed=directed)
id_mapping = collections.defaultdict(lambda: graph.add_vertex())
graph.vertex_properties['NodeId'] = graph.new_vertex_property('string')
with io.open(filename, encoding='utf-8') as infile:
for line in infile:
line = line.strip().split()
if len(line) == 2:
src, dest = line
src_v, dest_v = id_mapping[src], id_mapping[dest]
graph.add_edge(src_v, dest_v)
elif len(line) == 1:
node = line[0]
_ = id_mapping[node]
for orig_id, v in id_mapping.iteritems():
graph.vertex_properties['NodeId'][v] = orig_id
if not parallel_edges:
gt.remove_parallel_edges(graph)
return graph
def read_edge_list_nx(self, filename, directed=True, parallel_edges=False):
if nx is None:
import networkx as nx
if directed:
if parallel_edges:
graph = nx.MultiDiGraph()
else:
graph = nx.DiGraph()
else:
graph = nx.Graph()
with io.open(filename, encoding='utf-8') as infile:
for line in infile:
line = line.strip().split()
if len(line) == 2:
src, dest = line
graph.add_edge(src, dest)
elif len(line) == 1:
graph.add_node(line)
return graph
def extract_plaintext(self):
class MLStripper(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.reset()
self.fed = []
def handle_data(self, dat):
self.fed.append(dat)
def get_data(self):
return ''.join(self.fed)
def reset(self):
self.fed = []
HTMLParser.HTMLParser.reset(self)
parser = MLStripper()
if not os.path.exists(self.plaintext_folder):
os.makedirs(self.plaintext_folder)
files = set(os.listdir(self.plaintext_folder))
file_last = sorted(files)[-1] if files else None
for i, a in enumerate(sorted(self.name2id.keys())):
ofname = self.plaintext_folder + a + '.txt'
if a + '.txt' in files:
if a + '.txt' != file_last:
continue
else:
print(a + '.txt', 'overwrite')
print(unicode(i+1) + '/' + unicode(len(self.name2id)) +
' ' + a + '.txt')
fname = os.path.join(self.html_base_folder + a[0].lower(),
a + '.htm')
with io.open(fname, encoding='utf-8') as infile:
data = infile.read()
data = data.split('<!-- start content -->')[1]
data = data.split('<div class="printfooter">')[0]
data = [d.strip() for d in data.splitlines()]
data = [d for d in data if d]
data[0] = data[0].split('</p></div></div>')[1]
text = []
for d in data:
parser.reset()
parser.feed(parser.unescape(d))
stripped_d = parser.get_data()
if stripped_d:
text.append(stripped_d)
text = '\n'.join(text)
with io.open(ofname, 'w', encoding='utf-8') as outfile:
outfile.write(text)
@decorators.Cached
def get_tfidf_similarity(self, start, target):
if start > target:
start, target = target, start
query = '''SELECT similarity FROM tfidf_similarities
WHERE page_id=%d AND target_page_id=%d''' % (start, target)
similarity = self.db_connector.execute(query)
return similarity[0]['similarity']
@decorators.Cached
def get_category_depth(self, node):
query = '''SELECT category_depth FROM node_data
WHERE node_id=%d''' % node
depth = self.db_connector.execute(query)
return depth[0]['category_depth']
@decorators.Cached
def get_category_distance(self, start, target):
if start > target:
start, target = target, start
query = '''SELECT distance FROM category_distances
WHERE page_id=%d AND target_page_id=%d''' % (start, target)
distance = self.db_connector.execute(query)
return distance[0]['distance']
@decorators.Cached
def get_spl(self, start, target):
""" get the shortest path length for two nodes from the database
if this is too slow, add an index to the table as follows:
ALTER TABLE path_lengths ADD INDEX page_id (page_id);
"""
query = '''SELECT path_length FROM path_lengths
WHERE page_id=%d AND target_page_id=%d''' % (start, target)
length = self.db_connector.execute(query)
if not length:
return np.NaN
else:
return length[0]['path_length']
def compute_link_positions(self):
print('computing link positions...')
class MLStripper(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def reset(self):
self.fed = []
HTMLParser.HTMLParser.reset(self)
parser = MLStripper()
link_regex = re.compile(('(<a (class="mw-redirect" )?'
'href="../../wp/[^/]+/(.+?)\.htm" '
'title="[^"]+">.+?</a>)'))
folder = os.path.join('data', self.label, 'wpcd', 'wp')
link2pos_first, link2pos_last, pos2link, pos2linklength = {}, {}, {}, {}
length, ib_length, lead_length = {}, {}, {}
for i, a in enumerate(self.name2id.keys()):
print(unicode(i+1), '/', unicode(len(self.name2id)), end='\r')
lpos_first, lpos_last, posl, posll = {}, {}, {}, {}
fname = os.path.join(folder, a[0].lower(), a + '.htm')
try:
with io.open(fname, encoding='utf-8') as infile:
data = infile.read()
except UnicodeDecodeError:
# there exist decoding errors for a few irrelevant pages
print(fname)
continue
data = data.split('<!-- start content -->')[1]
data = data.split('<div class="printfooter">')[0]
if self.label == WIKTI.label:
# skip a boilerplate line
data = data.split('\n', 2)[2].strip()
regex_results = link_regex.findall(data)
regex_results = [(r[0], r[2]) for r in regex_results]
for link in regex_results:
link = [l for l in link if l]
data = data.replace(link[0], ' [['+link[1]+']] ')
# find infobox
if '<table' in data[:100]:
idx = data.find('</table>')
data = data[:idx] + ' [[[ENDIB]]] ' + data[idx:]
else:
data = ' [[[ENDIB]]] ' + data
# find lead
idx = data.find('<span class="mw-headline"')
if idx == -1:
data += ' [[[ENDLEAD]]] '
else:
data = data[:idx] + ' [[[ENDLEAD]]] ' + data[idx:]
data = [d.strip() for d in data.splitlines()]
data = [d for d in data if d]
text = []
for d in data:
parser.reset()
parser.feed(parser.unescape(d))
stripped_d = parser.get_data()
if stripped_d:
text.append(stripped_d)
text = ' '.join(text)
text = text.replace(']][[', ']] [[')
words = (re.split(': |\. |, |\? |! |\n | |\(|\)', text))
words = [wo for wo in words if wo]
idx = words.index('[[[ENDLEAD]]]')
lead_length[a] = idx
del words[idx]
idx = words.index('[[[ENDIB]]]')
ib_length[a] = idx
del words[idx]
for wi, word in enumerate(reversed(words)):
if word.startswith('[['):
try:
aid = self.name2id[word[2:-2].replace('%25', '%')]
lpos_first[aid] = len(words) - wi - 1
except KeyError:
pass
for wi, word in enumerate(words):
if word.startswith('[['):
try:
aid = self.name2id[word[2:-2].replace('%25', '%')]
lpos_last[aid] = wi
posl[wi] = aid
posll[wi] = word.count('_') + 1
except KeyError:
pass
link2pos_first[a] = lpos_first
link2pos_last[a] = lpos_last
pos2link[a] = posl
pos2linklength[a] = posll
length[a] = len(words)
path = os.path.join('data', self.label, 'link_positions.obj')
with open(path, 'wb') as outfile:
pickle.dump([link2pos_first, link2pos_last, length, pos2link,
pos2linklength, ib_length, lead_length], outfile, -1)
def load_link_positions(self):
if not self.link2pos_first:
path = os.path.join('data', self.label, 'link_positions.obj')
with open(path, 'rb') as infile:
self.link2pos_first, self.link2pos_last, self.length,\
self.pos2link, self.pos2linklength, self.ib_length,\
self.lead_length = pickle.load(infile)
self.link_sets = {k: sorted(v.keys())
for k, v in self.pos2link.iteritems()}
@decorators.Cached
def get_link_possibilities(self, start, target):
return sorted([k for k, v in self.pos2link[start].items()
if v == self.name2id[target]])
@decorators.Cached
def get_link_context_count(self, start, pos):
if np.isnan(pos):
return np.NaN
else:
ctxt = sum(pos - 10 <= l <= pos + 10
for l in self.link_sets[start])
return ctxt
@decorators.Cached
def get_link_length(self, start, pos):
return self.pos2linklength[start][pos]
def load_data(self, force=False):
if force or self.data is None:
path = os.path.join('data', self.label, 'data.obj')
self.data = pd.read_pickle(path)
def save_data(self, data=None):
if data is None:
data = self.data
data.to_pickle(os.path.join('data', self.label, 'data.obj'))
def print_error(self, message):
print(' Error:', message)
@staticmethod
def apply_debug(df, func, label):
result = []
for i, d in enumerate(df.iterrows()):
if (i % 100) == 0:
print(' ', i, '/', df.shape[0], end='\r')
result.append(func(d[1]))
df[label] = result
def complete_dataframe(self):
print('complete_dataframe()')
self.load_data()
self.load_link_positions()
df = self.data
df['node_id'] = df['node'].apply(lambda n: self.name2id[n])
df['node_next_id'] = df['node_next'].apply(lambda n: self.name2id[n] if isinstance(n, unicode) else np.NaN)
df['degree_out'] = df['node_id'].apply(lambda n: self.id2deg_out[n])
df['degree_in'] = df['node_id'].apply(lambda n: self.id2deg_in[n])
print(' getting ngram frequencies...')
get_ngrams = lambda n: ngram.ngram_frequency.get_frequency(n)
df['ngram'] = df['node'].apply(get_ngrams)
df['ngram'] = df['ngram'].apply(np.exp)
print(' getting Wikipedia view counts...')
get_view_count = lambda n: viewcounts.viewcount.get_frequency(n['node'])
Wikigame.apply_debug(df, get_view_count, 'view_count')
print(' getting word counts and shortest paths...')
df['word_count'] = df['node'].apply(lambda n: self.length[n])
# spl_target = lambda d: self.get_spl(d['node_id'], d['target_id'])
# Wikigame.apply_debug(df, spl_target, 'spl_target')
print(' getting TF-IDF similarities...')
tidf_target = lambda d: 1 - self.get_tfidf_similarity(d['node_id'],
d['target_id'])
Wikigame.apply_debug(df, tidf_target, 'tfidf_target')
# print(' getting category statistics...')
# category_depth = lambda n: self.get_category_depth(n)
# # df['category_depth'] = df['node_id'].apply(category_depth)
# Wikigame.apply_debug(df, category_depth, 'category_depth')
#
# category_target = lambda d: self.get_category_distance(d['node_id'],
# d['target_id'])
# # df['category_target'] = df.apply(category_target, axis=1)
# Wikigame.apply_debug(df, category_target, 'category_target')
print(' getting link positions...')
link2pos_all = {}
for article, article_dict in self.pos2link.iteritems():
link2pos = collections.defaultdict(list)
for k, v in article_dict.iteritems():
link2pos[v].append(k)
link2pos_all[article] = link2pos
first, last, links_all = [], [], []
for i in range(df.shape[0] - 1):
print(' ', i+1, '/', df.shape[0], end='\r')
if df.iloc[i]['subject'] != df.iloc[i+1]['subject'] or\
df.iloc[i]['backtrack']:
# if data belongs to different missions or is a backtrack
first.append(np.NaN)
last.append(np.NaN)
links_all.append(np.NaN)
else:
a = df.iloc[i]['node']
b = df.iloc[i+1]['node_id']
first.append(self.link2pos_first[a][b])
last.append(self.link2pos_last[a][b])
links_all.append(link2pos_all[a][b])
first.append(np.NaN)
last.append(np.NaN)
links_all.append(np.NaN)
df['linkpos_first'] = first
df['linkpos_last'] = last
df['linkpos_all'] = links_all
# find out whether the linkposition was in the infobx or the lead
print(' getting infobox and lead positions...')
lp = 'linkpos_actual' if 'linkpos_actual' in df else 'linkpos_first'
ibs = [self.ib_length[d] for d in df['node']]
leads = [self.lead_length[d] for d in df['node']]
linkpos_ib, linkpos_lead = [], []
for p, i, l in zip(df[lp], ibs, leads):
print(' ', i+1, '/', df.shape[0], end='\r')
if np.isnan(p):
linkpos_ib.append(np.NaN)
linkpos_lead.append(np.NaN)
elif np.isnan(i):
linkpos_ib.append(np.NaN)
linkpos_lead.append(int(p < l))
else:
linkpos_ib.append(int(p < i))
linkpos_lead.append(int(i < p < l))
df['linkpos_ib'] = linkpos_ib
df['linkpos_lead'] = linkpos_lead
self.data = df
self.save_data()
def add_link_context(self):
print('add_link_context()')
self.load_data()
self.load_link_positions()
df = self.data
lp = 'linkpos_actual' if 'linkpos_actual' in df else 'linkpos_first'
# get link context
context = []
anchor_length = []
for i in range(df.shape[0] - 1):
print(' ', i+1, '/', df.shape[0], end='\r')
if (df.iloc[i]['subject'] != df.iloc[i+1]['subject']) or\
df.iloc[i]['backtrack']:
# if data belongs to different missions or is a backtrack
context.append(np.NaN)
anchor_length.append(np.NaN)
else:
a = df.iloc[i]['node']
b = df.iloc[i][lp]
context.append(self.get_link_context_count(a, b))
anchor_length.append(self.get_link_length(a, b))
# print(a, df.iloc[i+1]['node'], b, self.get_link_length(a, b))
# pdb.set_trace()
df['link_context'] = context + [np.NaN]
df['link_anchor_length'] = anchor_length + [np.NaN]
self.save_data()
def add_means(self):
print('add_means()')
self.load_data()
self.data['mission'] = self.data['start'] + '-' + self.data['target']
df = self.data
df = df.join(df.groupby('mission')['pl'].mean(), on='mission',
rsuffix='_mission_mean')
mission_mean_mean = df['pl_mission_mean'].mean()
df['above_pl_mission_mean'] = df['pl_mission_mean'] > mission_mean_mean
df = df.join(df.groupby('user')['pl'].mean(), on='user',
rsuffix='_user_mean')
user_mean_mean = df['pl_user_mean'].mean()
df['above_pl_user_mean'] = df['pl_user_mean'] > user_mean_mean
self.data = df
self.save_data()
def add_all_linkpos(self):
self.load_link_positions()
link2pos_all = {}
for article, article_dict in self.pos2link.iteritems():
link2pos = collections.defaultdict(list)
for k, v in article_dict.iteritems():
link2pos[v].append(k)
link2pos_all[article] = link2pos
self.load_data()
df = self.data
links_all = []
for i in range(df.shape[0] - 1):
print(' ', i+1, '/', df.shape[0], end='\r')
if df.iloc[i]['subject'] != df.iloc[i+1]['subject'] or\
df.iloc[i]['backtrack']:
# if data belongs to different missions or is a backtrack
links_all.append(np.NaN)
else:
a = df.iloc[i]['node']
b = df.iloc[i+1]['node_id']
links_all.append(link2pos_all[a][b])
links_all.append(np.NaN)
df['linkpos_all'] = links_all
self.data = df
self.save_data()
def create_correlation_data(self):
node_id = sorted(self.id2name.keys())
df = pd.DataFrame(data=node_id, columns=['node_id'])
df['node'] = [self.id2name[n] for n in node_id]
df['degree_in'] = [self.id2deg_in[n] for n in node_id]
df['degree_out'] = [self.id2deg_out[n] for n in node_id]
print(' getting category statistics...')
category_depth = lambda n: self.get_category_depth(n)
df['category_depth'] = df['node_id'].apply(category_depth)
# print(' getting ngram frequencies...')
# ngrams = []
# for i, n in enumerate(df['node']):
# print(' ', i+1, '/', len(df['node']), end='\r')
# ngrams.append(ngram.ngram_frequency.get_frequency(n))
# df['ngram'] = ngrams
print(' getting view counts...')
view_counts = []
for i, n in enumerate(df['node']):
print(' ', i+1, '/', len(df['node']), end='\r')
view_counts.append(viewcounts.viewcount.get_frequency(n))
df['view_count'] = view_counts
# df.to_pickle(os.path.join('data', self.label, 'data_correlation.obj'))
def lead_links(self):
self.load_link_positions()
ib_links, lead_links, ib_lead_links, rest_links = [], [], [], []
for i, node in enumerate(self.name2id.keys()):
print(i+1, '/', len(self.name2id), end='\r')
try:
ib_limit = self.ib_length[node]
lead_limit = self.lead_length[node]
except KeyError:
continue
for pos, link in self.pos2link[node].items():
if pos < ib_limit:
ib_links.append(link)
ib_lead_links.append(link)
elif ib_limit < pos < lead_limit:
lead_links.append(link)
ib_lead_links.append(link)
else:
rest_links.append(link)
for stat_label, stat_func in [
('mean', np.mean),
('median', np.median)
]:
print(stat_label)
for label, func in [
('degree_in', lambda x: self.id2deg_in[x]),
('ngram', lambda x: np.exp(ngram.ngram_frequency.get_frequency(self.id2name[x]))),
('view_count', lambda x: viewcounts.viewcount.get_frequency(self.id2name[x])),
]:
ib = stat_func([func(l) for l in ib_links])
lead = stat_func([func(l) for l in lead_links])
ib_lead = stat_func([func(l) for l in ib_lead_links])
rest = stat_func([func(l) for l in rest_links])
if label == 'ngram':
ib, lead = np.log(ib), np.log(lead)
ib_lead, rest = np.log(ib_lead), np.log(rest)
print(' %s:' % label)
print(' %.4f IB' % ib)
print(' %.4f Lead' % lead)
print(' %.4f IB & Lead' % ib_lead)
print(' %.4f Rest' % rest)
def lead_links_all(self):
self.load_link_positions()
links, ibs, leads = [], [], []
for i, node in enumerate(self.name2id.keys()):
print(i+1, '/', len(self.name2id), end='\r')
try:
ib_limit = self.ib_length[node]
lead_limit = self.lead_length[node]
except KeyError:
continue
for pos, link in self.pos2link[node].items():
links.append(link)
ibs.append(0)
leads.append(0)
if pos < ib_limit:
ibs[-1] = 1
elif ib_limit < pos < lead_limit:
leads[-1] = 1
df = pd.DataFrame(data=zip(links, ibs, leads), columns=['target', 'ib', 'lead'])
for label, func in [
('degree_in', lambda x: self.id2deg_in[x]),
('ngram', lambda x: np.exp(ngram.ngram_frequency.get_frequency(self.id2name[x]))),
('view_count', lambda x: viewcounts.viewcount.get_frequency(self.id2name[x])),
]:
print(label)
df[label] = df['target'].apply(func)
df.to_pickle('data/data_ib_lead_rest_wikispeedia.obj')
def debug(self):
self.load_link_positions()
for i, node in enumerate(self.name2id.keys()):
ib_links, lead_links, ib_lead_links, rest_links = [], [], [], []
print(node)
try:
ib_limit = self.ib_length[node]
lead_limit = self.lead_length[node]
except KeyError:
print('KeyError')
continue
for pos, link in self.pos2link[node].items():
if pos < ib_limit:
ib_links.append(link)
ib_lead_links.append(link)
elif ib_limit < pos < lead_limit:
lead_links.append(link)
ib_lead_links.append(link)
else:
rest_links.append(link)
for stat_label, stat_func in [
('mean', np.mean),
('median', np.median)
]:
print(stat_label)
for label, func in [
('degree_in', lambda x: self.id2deg_in[x]),
('ngram', lambda x: np.exp(ngram.ngram_frequency.get_frequency(self.id2name[x]))),
('view_count', lambda x: viewcounts.viewcount.get_frequency(self.id2name[x])),
]:
ib = stat_func([func(l) for l in ib_links])
lead = stat_func([func(l) for l in lead_links])
ib_lead = stat_func([func(l) for l in ib_lead_links])
rest = stat_func([func(l) for l in rest_links])
if label == 'ngram':
ib, lead = np.log(ib), np.log(lead)
ib_lead, rest = np.log(ib_lead), np.log(rest)
print(' %s:' % label)
print(' %.4f IB' % ib)
print(' %.4f Lead' % lead)
# print(' %.4f IB & Lead' % ib_lead)
print(' %.4f Rest' % rest)
pdb.set_trace()
def compare_models_stepwise(self):
self.load_data()
self.data = self.data[~self.data['backtrack']]
self.data = self.data[self.data['spl'] == 3] # TODO
self.data = self.data[self.data['successful']]
self.load_link_positions()
df_result = pd.DataFrame(columns=['df', 'pl', 'step', 'model', 'kld'])
for label, df_full in [
('all', self.data),
# ('usa', self.data[self.data['usa']]),
('no usa', self.data[~self.data['usa']]),
]:
print('+++++++++++++++++', label, '+++++++++++++++++')
for pl in [
4,
5,
6,
7
]:
df = df_full[df_full['pl'] == pl]
print('----------------PATH LENGTH', pl, '----------------')
for step in range(pl-1):
print('\n--------', step, '--------')
# df = df[df['node'] == 'Africa']
first = df[df['step'] == step]['node_id']
pos = df[df['step'] == step]['linkpos_first']
second = df[df['step'] == step]['node_next_id']
gm = model.GroundTruthModel(first, pos, second, self)
gm.compute()
mdls = []
for mdl in [
model.UniformModel,
model.DegreeModel,
model.ViewCountModel,
model.NgramModel,
model.CategoryModel,
model.TfidfModel,
model.LinkPosModel,
## model.LinkPosDegreeModel,
## model.LinkPosNgramModel,
## model.LinkPosViewCountModel,
]:
mdls.append(mdl(first, pos, self))
# compare models
results = {}
for n in mdls:
n.compute()
kld = gm.get_kld(n)
results[n.label] = kld
idx = df_result.index.shape[0]
df_result.loc[idx] = [label, pl, step, n.label, kld]
for r in sorted(results.items(), key=operator.itemgetter(1)):
print('%.2f\t%s' % (r[1], r[0]))
df_result.to_pickle(os.path.join('data', self.label, 'models.obj'))
def compare_mi(self):
self.load_data()
self.load_link_positions()
step = 0
df = self.data
degs = df[df['step'] == step+1]['degree_in']
ngrams = df[df['step'] == step+1]['ngram']
nodes = df[df['step'] == step+1]['node_id']
ct = np.histogram2d(degs, ngrams)[0]
mi = mutual_info_score(None, None, ct) / max(entropy(degs), entropy(ngrams))
print('degs ngrams %.4f' % mi)
ct = np.histogram2d(degs, nodes)[0]
mi = mutual_info_score(None, None, ct) / max(entropy(degs), entropy(nodes))
print('degs nodes %.4f' % mi)
ct = np.histogram2d(ngrams, nodes)[0]
mi = mutual_info_score(None, None, ct) / max(entropy(ngrams), entropy(nodes))
print('ngrams nodes %.4f' % mi)
# degs = np.histogram(degs, bins=100, density=True)[0]
# ngrams = np.histogram(ngrams, bins=100, density=True)[0]
# nodes = np.histogram(nodes, bins=100, density=True)[0]
def je(a, b):
ct = np.histogram2d(a, b)[0]
return entropy(ct.flatten())
def je3(a, b, c):
ct = np.histogramdd([a, b, c])[0]
return entropy(ct.flatten())
x = degs
y = ngrams
z = nodes
cmi = je(x, z) + je(y, z) - je3(x, y, z) - entropy(np.histogram(z)[0])
print('degs ngrams nodes %.4f' % cmi)
pdb.set_trace()
# @decorators.Cached
def get_source2target(self, kind, step=None, spl=None, pl=None,
no_usa=False):
self.load_data(force=True)
df = self.data
if no_usa:
self.data = self.data[~self.data['usa']]
df['target'] = df['node'].shift(-1)
df['target_id'] = df['node_id'].shift(-1)
df = df[~df['backtrack']]
df = df.dropna()
if kind == 'successful':
df = df[df['successful']]
elif kind == 'unsuccessful':
df = df[~df['successful']]
elif kind == 'successful_first':
df = df[(df['successful']) & (df['step'] == 0)]
elif kind == 'successful_middle':
df = df[(df['successful']) & (df['step'] != 0) &
(df['distance-to-go'] != 1)]
elif kind == 'successful_last':
df = df[(df['successful']) & (df['distance-to-go'] == 1)]
elif kind == 'successful_first_limited':
df = df[(df['successful']) & (df['step'] == 0) & (df['spl'] <= 5)]
elif kind == 'successful_middle_limited':
df = df[(df['successful']) & (df['step'] != 0) & (df['distance-to-go'] != 1) & (df['spl'] <= 5)]
elif kind == 'successful_last_limited':
df = df[(df['successful']) & (df['distance-to-go'] == 1) & (df['spl'] <= 5)]
elif kind == 'successful_first_limited_pl':
df = df[(df['successful']) & (df['step'] == 0) & (df['spl'] <= 5) & (df['pl'] <= 10)]
elif kind == 'successful_middle_limited_pl':
df = df[(df['successful']) & (df['step'] != 0) & (df['distance-to-go'] != 1) & (df['spl'] <= 5) & (df['pl'] <= 10)]
elif kind == 'successful_last_limited_pl':
df = df[(df['successful']) & (df['distance-to-go'] == 1) & (df['spl'] <= 5) & (df['pl'] <= 10)]
elif kind == 'successful_high_deg_targets':
df2 = df[(df['successful']) & (df['step'] == 0)]
df2['target_deg_in'] = df2['target_id'].apply(lambda x: self.id2deg_in[x])
targets = set(df2[df2['target_deg_in'] >= 100]['target'])
df = df[(df['successful']) & (df['target'].isin(targets))]
elif kind == 'successful_low_deg_targets':
df2 = df[(df['successful']) & (df['step'] == 0)]
df2['target_deg_in'] = df2['target_id'].apply(lambda x: self.id2deg_in[x])
pdb.set_trace()
targets = set(df2[df2['target_deg_in'] < 100]['target'])
df = df[(df['successful']) & (df['target'].isin(targets))]
elif kind == 'successful_deg_above_median':
df2 = df[(df['successful']) & (df['step'] == 0)]
df2['target_deg_in'] = df2['target_id'].apply(lambda x: self.id2deg_in[x])
targets = set(df2[df2['target_deg_in'] > 28]['target'])
df = df[(df['successful']) & (df['target'].isin(targets))]
elif kind == 'successful_deg_below_median':
df2 = df[(df['successful']) & (df['step'] == 0)]
df2['target_deg_in'] = df2['target_id'].apply(lambda x: self.id2deg_in[x])
targets = set(df2[df2['target_deg_in'] <= 28]['target'])
df = df[(df['successful']) & (df['target'].isin(targets))]
if step is not None:
df = df[df['step'] == step]
if spl is not None:
df = df[df['spl'] == spl]
if pl is not None:
df = df[df['pl'] == pl]
df = df[['node', 'node_id', 'node_next', 'node_next_id']]
df.columns = ['source', 'source_id', 'target', 'target_id']
df['amount'] = df.groupby(['source', 'target']) \
.transform('count')['source_id']
df = df.drop_duplicates(subset=['source', 'target'])
source2target = {}
for source in set(df['source']):
df_sub = df[df['source'] == source]
zipped = zip(df_sub['target'], df_sub['amount'])
source2target[source] = {self.name2id[k]: v for k, v in zipped}
return source2target
# @decorators.Cached
def get_model_df(self, kind, step=None, spl=None, pl=None, no_usa=False):
source2target = self.get_source2target(kind, step, spl, pl, no_usa)
self.load_link_positions()
results = []
for idx, key in enumerate(sorted(self.length.keys())):
print(idx+1, '/', len(self.length), key, end='\r')
ib_length = self.ib_length[key]
lead_length = self.lead_length[key]
targets = sorted(set(self.link2pos_first[key].keys()))
target2amount = {k: 0 for k in targets}
try:
target2amount.update(source2target[key])
except KeyError:
pass
link2pos = collections.defaultdict(list)
for pos, link in self.pos2link[key].iteritems():
if link in targets:
link2pos[link].append(pos)
link2pos = {k: sorted(v) for k, v in link2pos.iteritems()}
if not link2pos:
# no outlinks on page
continue
source = [key] * len(link2pos)
source_id = [self.name2id[key]] * len(link2pos)
linkpos_first = [[link2pos[t][0]] for t in targets]
linkpos_last = [[link2pos[t][-1]] for t in targets]
linkpos_ib = [
[l for l in link2pos[t] if l < ib_length] for t in targets
]
linkpos_lead = [
[l for l in link2pos[t] if ib_length < l < lead_length]
for t in targets
]
linkpos_ib_lead = [
[l for l in link2pos[t] if l < lead_length]
for t in targets
]
linkpos_not_ib = [
[l for l in link2pos[t] if l > ib_length] for t in targets
]
linkpos_not_lead = [
[l for l in link2pos[t] if l > lead_length or l < ib_length]
for t in targets
]
linkpos_not_ib_lead = [
[l for l in link2pos[t] if l > lead_length] for t in targets
]
linkpos_all = [link2pos[t] for t in targets]
word_count = [self.length[key]] * len(link2pos)
target = [self.id2name[t] for t in targets]
target_id = targets
amount = [target2amount[t] for t in targets]
df = pd.DataFrame(
data=zip(source, source_id, linkpos_first, linkpos_last,
linkpos_ib, linkpos_lead, linkpos_ib_lead,
linkpos_not_ib, linkpos_not_lead, linkpos_not_ib_lead,
linkpos_all,
word_count, target, target_id, amount),
columns=['source', 'source_id', 'linkpos_first', 'linkpos_last',
'linkpos_ib', 'linkpos_lead', 'linkpos_ib_lead',
'linkpos_not_ib',
'linkpos_not_lead', 'linkpos_not_ib_lead',
'linkpos_all',
'word_count', 'target', 'target_id', 'amount']
)
results.append(df)
df = pd.concat(results)
suffix = ''
if step is not None:
suffix += '_step_' + unicode(step)
if spl is not None:
suffix += '_spl_' + unicode(spl)
if pl is not None:
suffix += '_pl_' + unicode(pl)
usa_suffix = '_no_usa' if no_usa else ''
stepwise = 'stepwise/' if step is not None else ''
df.to_pickle('data/clickmodels/' + stepwise + 'wikispeedia_' + kind +
usa_suffix + suffix + '.obj')
def get_model_df_stats(self):
def print_stats(data, label):
print('max: %.2f, mean: %.2f, median: %.2f, (%s)' % (max(data), np.mean(data), np.median(data), label))
# get statistics for all nodes
print_stats(self.id2deg_in.values(), 'all nodes')
self.load_data(force=True)
df_full = self.data
df_successful = df_full[df_full['successful']]
df_unsuccessful = df_full[~df_full['successful']]
for df, label in [
(df_successful, 'successful games'),
(df_unsuccessful, 'unsuccessful games'),
]:
targets = df[df['step'] == 0]['target_id']
target_indegs = [self.id2deg_in[t] for t in targets]
print_stats(target_indegs, label)
df2 = df_successful
df2['target_deg_in'] = df2['target_id'].apply(lambda x: self.id2deg_in[x])
pdb.set_trace()
def get_stats(self):
stats = {