-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_adversarial_permutation.py
More file actions
executable file
·79 lines (63 loc) · 2.7 KB
/
make_adversarial_permutation.py
File metadata and controls
executable file
·79 lines (63 loc) · 2.7 KB
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
#! /usr/bin/env python
import argparse
import os
import sys
import gzip
import time
import random
import math
from collections import defaultdict
""" Read a permutation file and randomized the end of the permutation in adversarial way (i.e. copying the beginning of another permutation of a different category) """
def randomize_perm(filename_permutations, percentage_randomized):
cat_ranks = defaultdict(list)
with open(filename_permutations, 'r') as file_:
for line in file_:
fields = line.strip().split("\t")
if len(fields) < 3:
continue
page_id = int(fields[0].strip())
cat = str(fields[1]).strip()
rank = [x.strip() for x in str(fields[2]).split(',')]
ranks = []
for x in rank:
if len(x)>0:
ranks.append(int(x))
cat_ranks[cat].append((page_id, ranks))
randomized_ranks = []
categories = list(cat_ranks.keys())
for cat, page_ranks in cat_ranks.items():
for page_rank in page_ranks:
page, old_ranks = page_rank
rand_other_cat = None
while True:
ra = random.choice(categories)
if ra <> cat:
rand_other_cat = ra
break
other_page, other_ranking = random.choice(cat_ranks[rand_other_cat])
new_ranking = []
new_ranking_set = set()
# first add the original positions
pos_stop = percentage_randomized * len(old_ranks)
for i in range(int(pos_stop)):
new_ranking.append(old_ranks[i])
new_ranking_set.add(old_ranks[i])
# second add the other positions from a random adversarial ranking
for x in other_ranking:
if x not in new_ranking_set:
new_ranking_set.add(x)
new_ranking.append(x)
assert len(new_ranking) == len(old_ranks)
print "\t".join([str(page), cat, ",".join([str(x) for x in new_ranking])])
"""
./make_adversarial_permutation.py -f ../dataset/rankings-category-8-small-10percent.txt -p 0.5 > ../dataset/rankings-category-8-small-10percent-adversarial50.txt
"""
def main():
#print "MUST USE TransitiveType NOT SimpleType for yago"
parser = argparse.ArgumentParser(description='Sample yago')
parser.add_argument('-f', '--filename_yago', action='store', dest='filename', required=True)
parser.add_argument('-p', '--fractio_randomized', action='store', dest='fraction_randomized', required=True)
conf = parser.parse_args()
randomize_perm(conf.filename, float(conf.fraction_randomized))
if __name__ == '__main__':
main()