parser.py
8.03 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
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
import gc
import random
import resource
from copy import deepcopy
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from keras.utils.np_utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
from utils import Tree
from models import (
KerasModel,
ParserModel,
)
from encoders import (
FeaturesFactory,
TargetsFactory,
)
class Parser(BaseEstimator, TransformerMixin, KerasModel):
def __init__(self, params):
self.params = params
self.features_factory = FeaturesFactory(self.params)
self.targets_factory = TargetsFactory(self.params)
self.model = None
def create(self):
return ParserModel(
self.params,
self.features_factory,
self.targets_factory,
).model
def create_generator(self, batches, multiple):
if not multiple:
for batch in batches:
yield batch
else:
n_batches = len(batches)
batch_idx = 0
while True:
yield batches[batch_idx]
batch_idx = (batch_idx + 1) % n_batches
def batchify_X(self, trees):
raw = self.features_factory.transform(trees)
output = []
words_batch = 0
n_cols = len(raw)
batch = [[] for _ in range(n_cols)]
for row_idx, tree in enumerate(trees):
words_batch += len(tree.tokens)
for col_idx in range(n_cols):
batch[col_idx].append(raw[col_idx][row_idx])
if words_batch > self.params.batch_size:
output_batch = [pad_sequences(x, padding='post') for x in batch]
batch = [[] for _ in range(n_cols)]
output.append(output_batch)
words_batch = 0
if words_batch > 0:
output_batch = [pad_sequences(x, padding='post') for x in batch]
output.append(output_batch)
return output
def batchify_y(self, trees):
raw = self.targets_factory.transform(trees)
output = []
words_batch = 0
n_cols = len(raw)
batch = [[] for _ in range(n_cols)]
for row_idx, tree in enumerate(trees):
words_batch += len(tree.tokens)
for col_idx in range(n_cols):
batch[col_idx].append(raw[col_idx][row_idx])
if words_batch > self.params.batch_size:
padded_batch = [pad_sequences(x, padding='post') for x in batch]
output_batch = []
for target, padded_target in zip(self.params.targets, padded_batch):
if target == 'head':
output_batch.append(to_categorical(padded_target, num_classes=padded_target.shape[1]))
elif target in ['feats', 'sent']:
output_batch.append(padded_target)
else:
output_batch.append(to_categorical(padded_target, num_classes=self.targets_factory.encoders[target].vocab_size))
batch = [[] for _ in range(n_cols)]
output.append(output_batch)
words_batch = 0
if words_batch > 0:
padded_batch = [pad_sequences(x, padding='post') for x in batch]
output_batch = []
for target, padded_target in zip(self.params.targets, padded_batch):
if target == 'head':
output_batch.append(to_categorical(padded_target, num_classes=padded_target.shape[1]))
elif target in ['feats', 'sent']:
output_batch.append(padded_target)
else:
output_batch.append(to_categorical(padded_target, num_classes=self.targets_factory.encoders[target].vocab_size))
batch = [[] for _ in range(n_cols)]
output.append(output_batch)
return output
def batchify_weights(self, trees):
output = []
words_batch = 0
n_cols = len(self.params.targets)
batch = [[] for _ in range(n_cols)]
for row_idx, tree in enumerate(trees):
words_batch += len(tree.tokens)
sample_weight = np.log(len(tree.tokens))
if not self.params.train_partial or self.params.full_tree in tree.comments:
targets = {
'head',
'deprel',
'lemma',
'upostag',
'xpostag',
'feats',
'semrel',
}
elif self.params.partial_tree in tree.comments:
targets = {
'lemma',
'upostag',
'xpostag',
'feats',
}
else:
targets = set()
for col_idx, target in enumerate(self.params.targets):
batch[col_idx].append(sample_weight if target in targets else 1e-9)
if words_batch > self.params.batch_size:
output.append(batch)
batch = [[] for _ in range(n_cols)]
words_batch = 0
if words_batch > 0:
output.append(batch)
batch = [[] for _ in range(n_cols)]
return output
def fit(self, trees, shuffle=True):
trees = sorted(trees, key=lambda x: len(x.tokens))
if self.model is None:
self.features_factory = self.features_factory.fit(trees)
self.targets_factory = self.targets_factory.fit(trees)
self.model = self.create()
batches = list(zip(
self.batchify_X(trees),
self.batchify_y(trees),
self.batchify_weights(trees),
),
)
try:
for epoch_idx in range(self.params.epochs):
if shuffle:
random.shuffle(batches)
for batch_idx, batch in enumerate(batches):
losses = self.model.train_on_batch(
x=batch[0],
y=batch[1],
sample_weight=[np.array(w) for w in batch[2]],
# class_weight=['auto']*len(self.params.targets),
)
if not isinstance(losses, list):
losses = [losses]
print(epoch_idx, batch_idx, list(zip(self.model.metrics_names, losses)))
except KeyboardInterrupt:
pass
def predict(self, trees):
trees = sorted(trees, key=lambda x: len(x.tokens))
output_trees = []
tree_idx = 0
for batch in self.batchify_X(trees):
batch_trees = trees[tree_idx:(tree_idx + batch[0].shape[0])]
batch_probs = self.model.predict_on_batch(batch)
if not isinstance(batch_probs, list):
batch_probs = [batch_probs]
batch_preds = self.targets_factory.inverse_transform(batch_probs, batch_trees)
for row_idx, old_tree in enumerate(batch_trees):
row_probs = [p[row_idx] for p in batch_probs]
row_preds = [p[row_idx] for p in batch_preds]
emb = None
new_tokens = []
for token_idx, token in enumerate(old_tree.tokens):
new_token = deepcopy(token)
for field, pred in zip(self.params.targets, row_preds):
if field == 'sent':
emb = pred
else:
new_token.fields[field] = pred[token_idx]
new_tokens.append(new_token)
output_trees.append(Tree(
tree_id=old_tree.id,
tokens=new_tokens,
words=old_tree.words,
comments=old_tree.comments,
probs=row_probs if self.params.save_probs else None,
emb=emb,
))
tree_idx += 1
output_trees = sorted(output_trees, key=lambda x: x.id)
return output_trees