-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtrain_label_classifier.py
250 lines (220 loc) · 10.1 KB
/
train_label_classifier.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
import os
import jsonlines
import codecs
import json
import numpy as np
import pickle
from sklearn import svm
from sklearn.externals import joblib
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, Normalizer
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
labeltoint = {'SUPPORTS': 0, 'REFUTES': 1, 'NOT ENOUGH INFO': 2}
intolabel = ['SUPPORTS', 'REFUTES', 'NOT ENOUGH INFO']
# generate features for train set
def populate_train(gold_train, entailment_predictions_train):
x_train = []
y_train = []
i = 1
gold_train = jsonlines.open(gold_train)
for instance in gold_train:
y_train.append(labeltoint[instance['label']])
entailment_results_file = entailment_predictions_train + "/claim_" + str(i) + ".json"
entailment_results_file = codecs.open(entailment_results_file, "r", "utf-8").readlines()
support_count = 0
refute_count = 0
nei_count = 0
support_confidence = 0
refute_confidence = 0
nei_confidence = 0
support_max_conf_score = 0.0
refute_max_conf_score = 0.0
nei_max_conf_score = 0.0
nei_min_conf_score = 1.0
evidence_so_far = []
for line in entailment_results_file:
line = json.loads(line)
evi = [line['premise_source_doc_id'], line['premise_source_doc_line_num']]
if evi in evidence_so_far:
continue
else:
evidence_so_far.append(evi)
maxIndex = np.argmax(np.asarray(line["label_probs"]))
if maxIndex == 0:
support_count += 1
support_confidence += line["label_probs"][maxIndex]
elif maxIndex == 1:
refute_count += 1
refute_confidence += line["label_probs"][maxIndex]
else:
nei_count += 1
nei_confidence += line["label_probs"][maxIndex]
if support_max_conf_score < line["label_probs"][0]:
support_max_conf_score = line["label_probs"][0]
if refute_max_conf_score < line["label_probs"][1]:
refute_max_conf_score = line["label_probs"][1]
if nei_max_conf_score < line["label_probs"][2]:
nei_max_conf_score = line["label_probs"][2]
if nei_min_conf_score > line["label_probs"][2]:
nei_min_conf_score = line["label_probs"][2]
features = [nei_max_conf_score, support_max_conf_score, refute_max_conf_score, nei_min_conf_score,
nei_count, nei_confidence, support_count, support_confidence, refute_count, refute_confidence]
if nei_count != 0:
features.append(float(nei_confidence) / float(nei_count))
else:
features.append(0)
if support_count != 0:
features.append(float(support_confidence) / float(support_count))
else:
features.append(0)
if refute_count != 0:
features.append(float(refute_confidence) / float(refute_count))
else:
features.append(0)
x_train.append(features)
# TODO:
# get defacto features here, if required
i += 1
return x_train, y_train
def predict_test(predictions_test, entailment_predictions_test, new_predictions_file):
clf = joblib.load('label_classifier.pkl')
i = 1
previous_predictions = jsonlines.open(predictions_test)
with jsonlines.open(new_predictions_file, mode='w') as writer:
for pred in previous_predictions:
new_pred = {'id': pred['id'], 'predicted_evidence': []}
entailment_results_file = entailment_predictions_test + "/claim_" + str(i) + ".json"
entailment_results_file = codecs.open(entailment_results_file, "r", "utf-8").readlines()
support_evidence = []
refute_evidence = []
nei_evidence = []
support_count = 0
refute_count = 0
nei_count = 0
support_confidence = 0
refute_confidence = 0
nei_confidence = 0
support_scores = []
refute_scores = []
nei_scores = []
support_max_conf_score = 0.0
refute_max_conf_score = 0.0
nei_max_conf_score = 0.0
nei_min_conf_score = 1.0
for line in entailment_results_file:
line = json.loads(line)
evi = [line['premise_source_doc_id'], line['premise_source_doc_line_num']]
if evi in support_evidence or evi in refute_evidence or evi in nei_evidence:
continue
maxIndex = np.argmax(np.asarray(line["label_probs"]))
if maxIndex == 0:
support_count += 1
support_confidence += line["label_probs"][maxIndex]
support_evidence.append(evi)
support_scores.append(line["label_probs"][0])
elif maxIndex == 1:
refute_count += 1
refute_confidence += line["label_probs"][maxIndex]
refute_evidence.append(evi)
refute_scores.append(line["label_probs"][1])
else:
nei_count += 1
nei_confidence += line["label_probs"][maxIndex]
nei_evidence.append(evi)
nei_scores.append(line["label_probs"][2])
if support_max_conf_score < line["label_probs"][0]:
support_max_conf_score = line["label_probs"][0]
if refute_max_conf_score < line["label_probs"][1]:
refute_max_conf_score = line["label_probs"][1]
if nei_max_conf_score < line["label_probs"][2]:
nei_max_conf_score = line["label_probs"][2]
if nei_min_conf_score > line["label_probs"][2]:
nei_min_conf_score = line["label_probs"][2]
# print(support_scores)
# print(support_evidence)
# print(support_count)
features = [nei_max_conf_score, support_max_conf_score, refute_max_conf_score, nei_min_conf_score,
nei_count, nei_confidence, support_count, support_confidence, refute_count, refute_confidence]
if nei_count != 0:
features.append(float(nei_confidence) / float(nei_count))
nei_scores, nei_evidence = zip(*sorted(zip(nei_scores, nei_evidence), reverse=True))
else:
features.append(0)
if support_count != 0:
features.append(float(support_confidence) / float(support_count))
support_scores, support_evidence = zip(*sorted(zip(support_scores, support_evidence), reverse=True))
else:
features.append(0)
if refute_count != 0:
features.append(float(refute_confidence) / float(refute_count))
refute_scores, refute_evidence = zip(*sorted(zip(refute_scores, refute_evidence), reverse=True))
else:
features.append(0)
# get defacto features here, if required
features = np.asarray(features)
features = features.reshape(1, features.shape[0])
# print(features)
new_pred['predicted_label'] = intolabel[clf.predict(features)[0]]
if new_pred['predicted_label'] == "SUPPORTS":
if support_count == 0:
new_pred['predicted_label'] = "NOT ENOUGH INFO"
else:
new_pred['predicted_evidence'] = support_evidence[:5]
elif new_pred['predicted_label'] == "REFUTES":
if refute_count == 0:
new_pred['predicted_label'] = "NOT ENOUGH INFO"
else:
new_pred['predicted_evidence'] = refute_evidence[:5]
else:
new_pred['predicted_evidence'] = []
writer.write(new_pred)
i += 1
predictions_train = "predictions/predictions_train.jsonl"
gold_train = "data/subsample_train_concatenation_oie_sentence_final.jsonl"
entailment_predictions_train = "rte/entailment_predictions_train_concatenate_oie_triple"
predictions_test = "data/dev_sentence_selection_final.jsonl"
entailment_predictions_test = "rte/entailment_predictions"
new_predictions_file = "predictions/new_dev_bert_test.jsonl"
x_train, y_train = populate_train(gold_train, entailment_predictions_train)
# x_test = x_train[7000:]
# y_test = y_train[7000:]
x_train = x_train[:2500]
y_train = y_train[:2500]
x_train = np.asarray(x_train)
y_train = np.asarray(y_train)
# x_test = np.asarray(x_test)
# y_test = np.asarray(y_test)
print(x_train)
print(y_train)
print(x_train.shape)
print(y_train.shape)
clf = RandomForestClassifier(max_depth=3, n_estimators=50, criterion="entropy")
# clf= Pipeline([('scaler', Normalizer()), ('clf', svm.SVC())])
# clf= Pipeline([('scaler', MinMaxScaler()), ('clf', svm.SVC())])
clf.fit(x_train, y_train)
print("Fit Done")
joblib.dump(clf, 'label_classifier.pkl')
# clf = joblib.load('filename.pkl')
# estimator = clf.estimators_[5]
# from sklearn.tree import export_graphviz
# print(estimator)
# # Export as dot file
# export_graphviz(estimator, out_file='tree.dot',
# feature_names=['nei_max_conf_score', 'support_max_conf_score', 'refute_max_conf_score',
# 'nei_count', 'nei_confidence', 'support_count', 'support_confidence',
# 'refute_count', 'refute_confidence','avg_nei', 'avg_sup', 'avg_ref'],
# class_names=['0', '1', '2'],
# rounded=True, proportion=False,
# precision=2, filled=True)
#
# # Convert to png using system command (requires Graphviz)
# from subprocess import call
# call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])
# print(clf.score(x_test,y_test))
# print(clf.score(x_train,y_train))
# y_pred = clf.predict(x_test)
# print(y_pred)
# print(y_pred.shape)
# print(classification_report(y_test, y_pred, target_names=['SUPPORTS', "REFUTES", "NEI"]))
predict_test(predictions_test, entailment_predictions_test, new_predictions_file)