-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension2
169 lines (115 loc) · 5.05 KB
/
extension2
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
#!/usr/bin/env python
import optparse, json, sys
from smoothedBLEU import smoothedBLEU
import models
import numpy as np
from sklearn.preprocessing import Imputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
optparser = optparse.OptionParser()
optparser.add_option("-r", "--readTranslationFiles", dest="input", default="data-others/translations.tsv",
help="Read Translation Files.")
optparser.add_option("-s", "--readSurvey", dest='survey', default='data-train/survey.tsv')
optparser.add_option("-d", "--baselineData", dest='data', default=None, help="Data for learning algorithms")
optparser.add_option("-l", "--language-model", dest="lm", default="data-others/lm", help="File containing ARPA-format language model (default=data/lm)")
(opts, _) = optparser.parse_args()
if opts.data is None:
# substitute strings in survey.tsv
sub = {'YES': 1, 'NO': 0, 'UNKNOWN': float('NaN')}
f_survey = open(opts.survey)
txt = f_survey.read().splitlines()
workerFeatures = {}
for i in xrange(1, len(txt)):
t = txt[i].split('\t')
# key: workerID, value: features
workerFeatures[t[0]] = [sub[x] if x in sub.keys() else int(x) for x in t[1:]]
f_survey.close()
workerFeatures['n/a'] = [float('NaN') for _ in xrange(6)]
# sys.stderr.write(workerFeatures,'\n')
sys.stderr.write("Building data set...\n")
file = open(opts.input)
txt = file.read().splitlines()
sourceDict = {}
referenceDict = {}
candidateDict = {}
workerDict = {}
for i in xrange(1, len(txt)): # ignore header (0)
sentenceList = txt[i].split("\t")
sourceDict[i] = sentenceList[1] # Urdu
referenceDict[i] = sentenceList[2:6] # LDC sentences
candidateDict[i] = sentenceList[6:10] # Turkers translated
workerDict[i] = sentenceList[10:]
best_idx = {} # labels for supervised training
feats = {} # corresponding worker-level features
# load language model (borrowed from homework 2)
lm = models.LM(opts.lm)
######### build dataset
for i in xrange(1, len(candidateDict) + 1):
scores = [0.0 for _ in candidateDict[i]]
for (j, candidate) in enumerate(candidateDict[i]):
if candidate != 'n/a':
for reference in referenceDict[i]:
if reference != 'n/a':
try:
scores[j] += smoothedBLEU(candidate, reference)
except:
pass
best_idx[i] = np.argmax(scores)
feats[i] = []
for ID in workerDict[i]:
feats[i] += workerFeatures[ID]
# average length of reference sentences (to compute sentence length features)
avg_ref_len = np.mean( [len(ref) if ref != 'n/a' else 0 for ref in referenceDict[i]] )
for candidate in candidateDict[i]:
# language model features
lm_state = lm.begin()
logprob = 0.0
for word in candidate.split():
(lm_state, word_logprob) = lm.score(lm_state, word)
logprob += word_logprob
logprob += lm.end(lm_state)
feats[i] += [logprob if candidate != 'n/a' else float('NaN')]
# sentence length features
feats[i] += [ len(candidate)/ avg_ref_len if candidate != 'n/a' else float('NaN') ]
feats[i] += [ avg_ref_len / len(candidate) if candidate != 'n/a' else float('NaN') ]
#
with open(r'data-train/data.json', 'w') as fp:
json.dump([feats, best_idx, candidateDict], fp, default=str)
else:
with open(r'data-train/data.json', 'rb') as fp:
feats, best_idx, candidateDict = json.load(fp)
############### Classification
y = np.array(map(int, best_idx.values()))
X = np.array(feats.values())
# fill in missing/unknown values
imp = Imputer(missing_values='NaN', strategy='most_frequent', copy=False)
X = imp.fit_transform(X)
# 20% used for training data, as specified in proposal
X_train, y_train = X[0:358, ], y[0:358, ]
sys.stderr.write("Training classifier(s)...\n")
np.random.seed(2)
rf = RandomForestClassifier(n_estimators=150)
rf.fit(X_train, y_train)
# svm_param_grid = [
# {'C': [1, 10, 100, 1000], 'kernel': ['linear']},
# {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
# ]
# svc = GridSearchCV( SVC(), svm_param_grid )
# svm = svc.fit(X_train, y_train).best_estimator_
# predicts index of best translation (0,1,2, or 3)
predictions = rf.predict(X)
################# write output to file
# out = open("baseline_output.txt", 'w')
if opts.data is None:
for (i, p) in enumerate(predictions):
sys.stdout.write(candidateDict[i + 1][p] + '\n')
else:
for (i, p) in enumerate(predictions):
sys.stdout.write(candidateDict[str(i + 1)][p].encode('utf-8') + '\n')
# out.close()
# out = open("oracle_output.txt", 'w')
# # 'best' translations corresponding to best_idx computed above
# for (i, c) in enumerate(y):
# out.write(candidateDict[i + 1][c] + '\n')
# out.close()