-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
309 lines (252 loc) · 9.6 KB
/
util.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import gzip
import logging
import sys
import numpy as np
import os
import os.path
import tensorflow as tf
from nltk import FreqDist
if (sys.version_info > (3, 0)):
pass
else: # Python 2.7 imports
from io import open
def LoadEmbedding(embeddingsPath, commentSymbol=None):
# Check that the embeddings file exists
if not os.path.isfile(embeddingsPath):
print("The embeddings file %s was not found" % embeddingsPath)
exit()
# :: Read in word embeddings ::
logging.info("Read file: %s" % embeddingsPath)
word2Idx = {}
embeddings = []
embeddingsIn = gzip.open(embeddingsPath, "rt") if embeddingsPath.endswith('.gz') else open(embeddingsPath)
embeddingsDimension = None
for line in embeddingsIn:
if isinstance(line, unicode):
split = line.rstrip().split(" ")
else:
split = line.rstrip().decode("utf8").split(" ")
if len(split) > 2:
word = split[0]
if embeddingsDimension == None:
embeddingsDimension = len(split) - 1
if (len(
split) - 1) != embeddingsDimension: # Assure that all lines in the embeddings file are of the same length
print("ERROR: A line in the embeddings file had more or less dimensions than expected. Skip token.")
continue
if len(word2Idx) == 0: # Add padding+unknown
word2Idx["PADDING_TOKEN"] = len(word2Idx)
vector = np.zeros(embeddingsDimension)
embeddings.append(vector)
word2Idx["UNKNOWN_TOKEN"] = len(word2Idx)
vector = np.random.uniform(-0.25, 0.25, embeddingsDimension) # Alternativ -sqrt(3/dim) ... sqrt(3/dim)
embeddings.append(vector)
vector = np.array([float(num) for num in split[1:]])
if word not in word2Idx:
embeddings.append(vector)
word2Idx[word] = len(word2Idx)
embeddings = np.array(embeddings)
return embeddings, word2Idx
def readCoNLLTrain(inputPath, cols, word2idx, labelkey):
"""
Reads in a CoNLL file
"""
logging.info("Read file: %s" % inputPath)
sentences = []
sentenceTemplate = {name: [] for name in cols.values() + ['raw_tokens', 'raw_labels']}
sentence = {name: [] for name in sentenceTemplate.keys()}
label2idx = {"O": 0}
newData = False
numTokens = 0
numUnknownTokens = 0
missingTokens = FreqDist()
for line in open(inputPath):
line = line.strip()
if len(line) == 0:
if newData:
sentences.append(sentence)
sentence = {name: [] for name in sentenceTemplate.keys()}
newData = False
continue
splits = line.split()
for colIdx, colName in cols.items():
val = splits[colIdx]
if colName == 'tokens':
numTokens += 1
idx = word2idx['UNKNOWN_TOKEN']
if word2idx.has_key(val):
idx = word2idx[val]
else:
numUnknownTokens += 1
missingTokens[val] += 1
sentence['raw_tokens'].append(val)
sentence[colName].append(idx)
elif colName == labelkey:
if not label2idx.has_key(val):
label2idx[val] = len(label2idx)
idx = label2idx[val]
sentence[colName].append(idx)
sentence['raw_labels'].append(val)
newData = True
if numTokens > 0:
logging.info("Unknown-Tokens: %.2f%%" % (numUnknownTokens / float(numTokens) * 100))
if newData:
sentences.append(sentence)
return sentences, label2idx
def readCoNLL(inputPath, cols, word2idx, labelkey, label2idx):
"""
Reads in a CoNLL file
"""
logging.info("Read file: %s" % inputPath)
sentences = []
sentenceTemplate = {name: [] for name in cols.values() + ['raw_tokens', 'raw_labels']}
sentence = {name: [] for name in sentenceTemplate.keys()}
newData = False
numTokens = 0
numUnknownTokens = 0
missingTokens = FreqDist()
for line in open(inputPath):
line = line.strip()
if len(line) == 0:
if newData:
sentences.append(sentence)
sentence = {name: [] for name in sentenceTemplate.keys()}
newData = False
continue
splits = line.split()
for colIdx, colName in cols.items():
val = splits[colIdx]
if colName == 'tokens':
numTokens += 1
idx = word2idx['UNKNOWN_TOKEN']
if val in word2idx.keys():
idx = word2idx[val]
else:
numUnknownTokens += 1
missingTokens[val] += 1
sentence['raw_tokens'].append(val)
sentence[colName].append(idx)
elif colName == labelkey:
idx = label2idx[val]
sentence[colName].append(idx)
sentence['raw_labels'].append(val)
newData = True
if numTokens > 0:
logging.info("Unknown-Tokens: %.2f%%" % (numUnknownTokens / float(numTokens) * 100))
if newData:
sentences.append(sentence)
return sentences
def prepare(dataset, labelKey, seq_max_len, is_padding=True):
X = []
y = []
tmp_x = []
tmp_y = []
for idx in range(len(dataset)):
c = dataset[idx]['tokens']
# print("c", c, "l", l)
l = dataset[idx][labelKey]
# empty line
if is_padding:
tmp_x.append(padding(c, seq_max_len))
tmp_y.append(padding(l, seq_max_len))
else:
tmp_x.append(c)
tmp_y.append(l)
# print(X)
return tmp_x, tmp_y
# use "0" to padding the sentence
def padding(Sequence, seq_max_len):
seq_out = []
if len(Sequence) < seq_max_len:
for i in range(len(Sequence)):
seq_out.append(Sequence[i])
for i in range(len(Sequence), seq_max_len):
seq_out.append(0)
elif len(Sequence) >= seq_max_len:
for i in range(seq_max_len):
seq_out.append(Sequence[i])
return seq_out
def create_model(session, Model, ckpt_file, labelKey, label2Idx, word2Idx, num_steps, num_epochs, embedding_matrix,
logger):
# create model, reuse parameters if exists
model = Model(labelKey=labelKey, label2Idx=label2Idx, word2Idx=word2Idx, num_steps=num_steps, num_epochs=num_epochs,
embedding_matrix=embedding_matrix, is_training=True)
ckpt = tf.train.get_checkpoint_state(ckpt_file)
if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
logger.info("Reading model parameters from %s" % ckpt.model_checkpoint_path)
model.saver.restore(session, ckpt.model_checkpoint_path)
else:
logger.info("Created model with fresh parameters.")
session.run(tf.global_variables_initializer())
return model
def nextBatch(X, y, start_index, batch_size):
last_index = start_index + batch_size
X_batch = list(X[start_index:min(last_index, len(X))])
y_batch = list(y[start_index:min(last_index, len(X))])
if last_index > len(X):
left_size = last_index - (len(X))
for i in range(left_size):
index = np.random.randint(len(X))
X_batch.append(X[index])
y_batch.append(y[index])
X_batch = np.array(X_batch)
y_batch = np.array(y_batch)
return X_batch, y_batch
def nextRandomBatch(X, y, batch_size):
X_batch = []
y_batch = []
for i in range(batch_size):
index = np.random.randint(len(X))
X_batch.append(X[index])
y_batch.append(y[index])
X_batch = np.array(X_batch)
y_batch = np.array(y_batch)
return X_batch, y_batch
def save_model(sess, model, path, model_saved_name, logger):
checkpoint_path = os.path.join(path, model_saved_name)
model.saver.save(sess, checkpoint_path)
logger.info("model saved")
def cal_recall(guessed, correct, idx2Label):
assert (len(guessed) == len(correct))
label_pred = [idx2Label[element] for element in guessed]
label_correct = [idx2Label[element] for element in correct]
idx = 0
correctCount = 0
count = 0
while idx < len(label_pred):
if label_pred[idx][0] == 'B': # A new chunk starts
count += 1
if label_pred[idx] == label_correct[idx]:
idx += 1
correctlyFound = True
while idx < len(label_pred) and label_pred[idx][0] == 'I': # Scan until it no longer starts with I
if label_pred[idx] != label_correct[idx]:
correctlyFound = False
idx += 1
if idx < len(label_pred):
if label_correct[idx][0] == 'I': # The chunk in correct was longer
correctlyFound = False
if correctlyFound:
correctCount += 1
else:
idx += 1
else:
idx += 1
return count, correctCount
def getTransition(y_train_batch, num_class):
transition_batch = []
for m in range(len(y_train_batch)):
y = [num_class] + list(y_train_batch[m]) + [0]
for t in range(len(y)):
if t + 1 == len(y):
continue
i = y[t]
j = y[t + 1]
if i == 0:
break
transition_batch.append(i * (num_class + 1) + j)
transition_batch = np.array(transition_batch)
return transition_batch