-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_verbs.py
192 lines (127 loc) · 5.57 KB
/
train_verbs.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
from utils import *
from scipy.spatial.distance import cosine
from scipy.stats import spearmanr
from verb import Verb
from tqdm import tqdm, trange
def test_verbs(verbs, w2v_nn, test_data, dset='GS', verbose=False):
# Predict similarity for GS test data, using learned verb representations
test_pairs = []
if verbose: print '\n\nTesting on '+dset+' data . . .'
for row in test_data.iterrows():
if dset == 'GS':
pid, v, s, o, t, gt_score, hilo = row[1]
svo1_vec = verbs[v].V(w2v_nn[s], w2v_nn[o]) # "verb"
svo2_vec = verbs[t].V(w2v_nn[s], w2v_nn[o]) # "landmark" (target)
elif dset == 'KS':
pid, s1,v1,o1, s2,v2,o2, gt_score = row[1]
svo1_vec = verbs[v1].V(w2v_nn[s1], w2v_nn[o1])
svo2_vec = verbs[v2].V(w2v_nn[s2], w2v_nn[o2])
similarity = 1 - cosine(svo1_vec, svo2_vec) # TODO: test different distances
test_pairs.append((similarity, gt_score))
# Compute spearman R for full data
rho_, pvalue = spearmanr(*zip(*test_pairs))
if verbose: print '\trho: {}\n\tpvalue: {}'.format(rho_, pvalue)
return rho_, pvalue
def train_verbs(params):
# Build and train model for each verb
verbs = {}
it = params['w2v_svo'].items()
loop = tqdm(it, desc='', leave=True) if params['verbose'] else it
for v, s_o in loop:
if params['verbose']: loop.set_description('Training: "' + v + '"')
P = params.copy()
P['test_data'] = params['test_data'][v]
P['sentences'], P['subjects'], P['objects'] = format_data(P['w2v_nn'], s_o)
verbs[v] = parameterize(Verb, P)
if P['optimizer'] == 'SGD':
parameterize(verbs[v].SGD, P)
elif P['optimizer'] == 'ADAD':
parameterize(verbs[v].ADA_delta, P)
return verbs
def L_combined(verb, train_data, test_ratio):
L_test = verb.L(*verb.test_data) * test_ratio
L_train = verb.L(*train_data) * (1 - test_ratio)
def get_best_verbs(trained_verbs, train_data, test_ratio):
all_verbs = defaultdict(lambda: list())
for verbs in trained_verbs:
for v, verb in verbs.items():
all_verbs[v].append(verb)
for v, verbs in all_verbs.items():
L = lambda verb: L_combined(verb, train_data, test_ratio)
all_verbs[v] = sorted(verbs, key=L)
return {v:verbs[0] for v,verbs in all_verbs.items()}
def train_trials(params):
"""
Train all verbs `n_trials` individual times.
"""
best_acc_gs = 0.0
best_acc_ks = 0.0
loop = trange if params['verbose'] else range
trained_verbs = []
for k in loop(params['n_trials']):
P = test_to_params(params)
# Train verbs
verbs = train_verbs(P)
# Update saved weights for best-scoring parameters
curr_acc_gs = test_verbs(verbs, P['w2v_nn'], P['gs_data'], dset='GS', verbose=P['verbose'])[0]
if curr_acc_gs > best_acc_gs:
save_verbs(verbs, P['save_file'] + '-GS.npy')
best_acc_gs = curr_acc_gs
curr_acc_ks = test_verbs(verbs, P['w2v_nn'], P['ks_data'], dset='KS', verbose=P['verbose'])[0]
if curr_acc_ks > best_acc_ks:
save_verbs(verbs, P['save_file'] + '-KS.npy')
best_acc_ks = curr_acc_ks
trained_verbs.append(verbs)
# Save metadata for this run
save_meta(params, P['save_file'] + '_meta.npy')
print '\n\n\n~~~~ best individual verbs ~~~~'
curr_acc_gs = test_verbs(verbs, P['w2v_nn'], P['gs_data'], dset='GS', verbose=P['verbose'])[0]
curr_acc_ks = test_verbs(verbs, P['w2v_nn'], P['ks_data'], dset='KS', verbose=P['verbose'])[0]
if __name__ == '__main__':
# ------------------------------------------------------------------------
# Parameters
params = {
'save_file' : 'data/nonsparse',
'verbose' : True,
'train' : True,
'rank' : 20,
'batch_size' : 20,
'epochs' : 500,
'n_trials' : 10,
'learning_rate' : 1.0,
'init_noise' : 0.1,
'optimizer' : 'ADAD',
'rho' : 0.95,
'eps' : 1e-6,
'cg' : 0, # set to 0 for full data,
'ck' : 0, # set to -1 for full data (minus 1 point),
'n_stop' : 0.1,
'data_ratio' : 0.1,
'stop_t' : 1e-6,
'norm' : 'L1',
'lamb_P' : 1e-2,
'lamb_Q' : 1e-0,
'lamb_R' : 1e-1,
}
# ------------------------------------------------------------------------
# Load & filter test data
gs_file = 'data/eval/GS2011data.txt'
ks_file = 'data/eval/KS2014.txt'
gs_data, ks_data, test_vs = load_test_data(params['cg'], params['ck'], gs_file=gs_file, ks_file=ks_file)
# ------------------------------------------------------------------------
# Load & filter word/triplet vectors
nn_file = 'data/w2v/w2v-nouns.npy'
svo_file = 'data/w2v/w2v-svo-triplets.npy'
w2v_nn, w2v_svo_full = load_word2vec(test_vs, nn_file=nn_file, svo_file=svo_file)
params.update({
'w2v_nn': w2v_nn,
'w2v_svo_full': w2v_svo_full,
'gs_data': gs_data,
'ks_data': ks_data,
})
# ------------------------------------------------------------------------
# Train / load verb parameters
train_trials(params)
# verbs = load_verbs(params['save_file'] + '.npy')
# test_verbs(verbs, w2v_nn, gs_data, dset='GS', verbal=True)
# test_verbs(verbs, w2v_nn, ks_data, dset='KS', verbal=True)