-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathkoppel11.py
250 lines (209 loc) · 6.33 KB
/
koppel11.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
'''-- Jakob Koehler & Tolga Buz
Reproduction of Koppel11
'''
#--- Parameters:
# n-gram size
n = 4
# length of feature list
featureLength = 20000
# Score threshold (needed for open set)
threshold = 0
# number of k repetitions
repetitions = 100
# minimum size of document
# (increases precision, but deteriorates recall,
# if there are many small documents)
minlen = 0
# candidates with less than this amount of words in trainingdata are not
# attributed to
mintrainlen = 500
#--- Imports:
from math import sqrt
import jsonhandler
import random
import argparse
#--- Methods:
'''- create Vector:
gets a string (e.g. Book), splits it into and returns a vector
with all possible n-grams/features'''
def createVector(s):
vector = {}
words = s.split()
for word in words:
if len(word) <= n:
add(vector, word)
else:
for i in range(len(word) - n + 1):
add(vector, word[i:i + n])
return vector
'''- add:
adds n-grams to our featurelist-vector, if is not included yet
(containing all possible n-grams/features)'''
def add(vector, ngram):
if ngram in vector:
vector[ngram] += 1
else:
vector[ngram] = 1
'''- selectFeatures:
selects the x most frequent n-grams/features (x=featureLength)
to avoid a (possibly) too big featurelist'''
def selectFeatures(vector):
return sorted(vector, key=vector.get, reverse=True)[:min(len(vector), featureLength)]
'''- createFeatureMap:
creates Feature Map that only saves
the features that actually appear more frequently than 0.
Thus, the featurelist needs less memory and can work faster'''
def createFeatureMap(s, features):
fmap = {}
vec = createVector(s)
for ngram in features:
if ngram in vec:
fmap[ngram] = vec[ngram]
return fmap
'''- cosSim:
calculates cosine similarity of two vectors v1 and v2.
-> cosine(X, Y) = (X * Y)/(|X|*|Y|)
'''
def cosSim(v1, v2):
sp = float(0)
len1 = 0
len2 = 0
for ngram in v1:
len1 += v1[ngram] ** 2
for ngram in v2:
len2 += v2[ngram] ** 2
len1 = sqrt(len1)
len2 = sqrt(len2)
for ngram in v1:
if ngram in v2:
sp += v1[ngram] * v2[ngram]
return sp / (len1 * len2)
'''- minmax:
calculates minmax similarity of two vectors v1 and v2.
-> minmax(X, Y) = sum(min(Xi, Yi))/sum(max(Xi, Yi))
This baseline method will be used for further evaluation.
'''
def minmax(v1, v2):
minsum = 0
maxsum = 0
for ngram in v1:
if ngram in v2:
# ngram is in both vectors
minsum += min(v1[ngram], v2[ngram])
maxsum += max(v1[ngram], v2[ngram])
else:
# ngram only in v1
maxsum += v1[ngram]
for ngram in v2:
if ngram not in v1:
# ngram only in v2
maxsum += v2[ngram]
if maxsum == 0:
return 0
return float(minsum) / maxsum
'''- training:
Turns a given string into a n-gram vector
and returns its feature list.
'''
def training(s):
print("training...")
vec = createVector(s)
print("selecting features...")
fl = selectFeatures(vec)
print("done")
return fl
'''- testSim:
args: two vectors, a featurelist
and func(to decide whether to use cosine or minmax similarity).
uses createFeatureMap and cosSim or minmax
and returns the similarity value of the two vectors
'''
def testSim(x, y, fl, func):
fx = createFeatureMap(x, fl)
fy = createFeatureMap(y, fl)
if func == 0:
return cosSim(fx, fy)
else:
return minmax(fx, fy)
'''- getRandomString:
Returns a random part of a string s
that has a given length
'''
def getRandomString(s, length):
words = s.split()
r = random.randint(0, len(words) - length)
return "".join(words[r:r + length])
#--- main:
def main():
#
parser = argparse.ArgumentParser(
description="Tira submission for PPM approach (koppel11)")
parser.add_argument("-i", action="store", help="path to corpus directory")
parser.add_argument("-o", action="store", help="path to output directory")
args = vars(parser.parse_args())
corpusdir = args["i"]
outputdir = args["o"]
if corpusdir == None or outputdir == None:
parser.print_help()
return
candidates = jsonhandler.candidates
unknowns = jsonhandler.unknowns
jsonhandler.loadJson(corpusdir)
jsonhandler.loadTraining()
texts = {}
# texts = frozenset() would this work??
corpus = ""
print("loading texts for training")
deletes = []
for cand in candidates:
texts[cand] = ""
for file in jsonhandler.trainings[cand]:
texts[cand] += jsonhandler.getTrainingText(cand, file)
# if frozenset() is used:
# texts.add(jsonhandler.getTrainingText(cand, file))
print("text " + file + " read")
if len(texts[cand].split()) < mintrainlen:
del texts[cand]
deletes.append(cand)
else:
corpus += texts[cand]
newcands = []
for cand in candidates:
if cand not in deletes:
newcands.append(cand)
candidates = newcands
words = [len(texts[cand].split()) for cand in texts]
minwords = min(words)
print(minwords)
fl = training(corpus)
authors = []
scores = []
for file in unknowns:
print("testing " + file)
utext = jsonhandler.getUnknownText(file)
ulen = len(utext.split())
if ulen < minlen:
authors.append("None")
scores.append(0)
else:
wins = [0] * len(candidates)
textlen = min(ulen, minwords)
print(textlen)
ustring = "".join(utext.split()[:textlen])
for i in range(repetitions):
rfl = random.sample(fl, len(fl) // 2)
sims = []
for cand in candidates:
candstring = getRandomString(texts[cand], textlen)
sims.append(testSim(candstring, ustring, rfl, 1))
wins[sims.index(max(sims))] += 1
score = max(wins) / float(repetitions)
if score >= threshold:
authors.append(candidates[wins.index(max(wins))])
scores.append(score)
else:
authors.append("None")
scores.append(score)
print("storing answers")
jsonhandler.storeJson(outputdir, unknowns, authors, scores)
main()