-
Notifications
You must be signed in to change notification settings - Fork 0
/
featurizer_old.py
629 lines (557 loc) · 19.5 KB
/
featurizer_old.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#!/usr/bin/env
import os
import numpy as np
from scipy import sparse
import operator
import re
import multiprocessing
from collections import Counter
import colibricore
import utils
import gen_functions
class Featurizer:
"""
Featurizer
=====
Class to extract features from raw and tagged text files
Parameters
-----
raw : list
The raw data comes in an array where each entry represents a text
instance in the data file.
tagged : list
The tagged data comes in a list of lists, where each row represents a
text instance and the columns represent word - lemma - pos -
sentence number respectively
features : dict
Subset any of the entries in the following dictionary:
features = {
'simple_stats' : {},
'token_ngrams' : {'n_list' : [1, 2, 3]},
'char_ngrams' : {'n_list' : [1, 2, 3]},
'lemma_ngrams' : {'n_list' : [1, 2, 3]},
'pos_ngrams' : {'n_list' : [1, 2, 3]}
}
Attributes
-----
self.tagged : list
The tagged parameter
self.raw : list
The raw parameter
self.modules : dict
Template dict with all the helper classes
self.helpers : list
List to call all the helper classes
self.features : dict
Container of the featurized instances for the different feature types
self.vocabularies : dict
Container of the name of each feature index for the different feature types
"""
def __init__(self, raws, tagged, directory, features):
self.tagged = tagged
self.raw = raws
self.directory = directory
self.modules = {
'simple_stats': SimpleStats,
'token_ngrams': TokenNgrams,
'lemma_ngrams': LemmaNgrams,
'pos_ngrams': PosNgrams,
'char_ngrams': CharNgrams,
}
self.helpers = [v(**features[k]) for k, v in self.modules.items() if k in features.keys()]
self.feats = {}
self.vocabularies = {}
def fit_transform(self):
"""
Featurizer
=====
Function to extract every helper feature type
Transforms
-----
self.features : dict
The featurized instances of every helper are written to this dict
self.vocabularies : dict
The name of each feature index for every feature type is written to this dict
"""
for helper in self.helpers:
feats, vocabulary = helper.fit_transform(self.raw, self.tagged, self.directory)
self.feats[helper.name] = feats
self.vocabularies[helper.name] = vocabulary
def return_instances(self, helpernames):
"""
Information extractor
=====
Function to extract featurized instances in any combination of feature types
Parameters
------
helpernames : list
List of the feature types to combine
Names of feature types correspond with the keys of self.modules
Returns
-----
instances : scipy csr matrix
Featurized instances
Vocabulary : list
List with the feature name per index
"""
submatrices = [self.feats[name] for name in helpernames]
instances = sparse.hstack(submatrices).tocsr()
vocabulary = np.hstack([self.vocabularies[name] for name in helpernames])
return instances, vocabulary
class SimpleStats:
def __init__(self):
pass
def fit(self):
pass
def transform(self):
pass
def fit_transform(self):
self.fit()
self.transform()
class CocoNgrams:
def __init__(self, ngrams, blackfeats):
self.ngrams = ngrams
self.blackfeats = set(blackfeats)
def fit(self, tmpdir, lines, mt = 1):
self.lines = lines
ngram_file = tmpdir + 'ngrams.txt'
with open(ngram_file, 'w', encoding = 'utf-8') as txt:
for line in lines:
txt.write(line)
classfile = tmpdir + 'ngrams.colibri.cls'
# Build class encoder
classencoder = colibricore.ClassEncoder()
classencoder.build(ngram_file)
classencoder.save(classfile)
# Encode corpus data
corpusfile = tmpdir + 'ngrams.colibri.dat'
classencoder.encodefile(ngram_file, corpusfile)
# Load class decoder
self.classdecoder = colibricore.ClassDecoder(classfile)
# Train model
options = colibricore.PatternModelOptions(mintokens = mt, maxlength = max(self.ngrams), doreverseindex=True)
self.model = colibricore.IndexedPatternModel()
self.model.train(corpusfile, options)
def transform(self, write = False):
rows = []
cols = []
data = []
vocabulary = []
items = list(zip(range(self.model.__len__()), self.model.items()))
for i, (pattern, indices) in items:
vocabulary.append(pattern.tostring(self.classdecoder))
docs = [index[0] - 1 for index in indices]
counts = Counter(docs)
unique = counts.keys()
rows.extend(unique)
cols.extend([i] * len(unique))
data.extend(counts.values())
if write:
with open(write, 'w', encoding = 'utf-8') as sparse_out:
sparse_out.write(' '.join([str(x) for x in data]) + '\n')
sparse_out.write(' '.join([str(x) for x in rows]) + '\n')
sparse_out.write(' '.join([str(x) for x in cols]) + '\n')
sparse_out.write(str(len(self.lines)) + ' ' + str(self.model.__len__()))
instances = sparse.csr_matrix((data, (rows, cols)), shape = (len(self.lines), self.model.__len__()))
if len(self.blackfeats) > 0:
blackfeats_indices = []
for bf in self.blackfeats:
regex = re.compile(bf)
matches = [i for i, f in enumerate(vocabulary) if regex.match(f)]
regex_left = re.compile(r'.+' + ' ' + bf + r'$')
matches += [i for i, f in enumerate(vocabulary) if regex_left.match(f)]
regex_right = re.compile(r'^' + bf + ' ' + r' .+')
matches += [i for i, f in enumerate(vocabulary) if regex_right.match(f)]
regex_middle = re.compile(r'.+' + ' ' + bf + ' ' + r'.+')
matches += [i for i, f in enumerate(vocabulary) if regex_middle.match(f)]
blackfeats_indices.extend(matches)
to_keep = list(set(range(len(vocabulary))) - set(blackfeats_indices))
instances = sparse.csr_matrix(instances[:, to_keep])
vocabulary = list(np.array(vocabulary)[to_keep])
return instances, vocabulary
class TokenNgrams(CocoNgrams):
"""
Token ngram extractor
=====
Class to extract token ngrams from all documents
Parameters
-----
kwargs : dict
n_list : list
The values of N (1 - ...)
blackfeats : list
Features to exclude
Attributes
-----
self.name : str
The name of the module
self.n_list : list
The n_list parameter
self.blackfeats : list
The blackfeats parameter
self.feats : list
List of feature names, to keep track of the values of feature indices
"""
def __init__(self, **kwargs):
self.name = 'token_ngrams'
self.n_list = [int(x) for x in kwargs['n_list']]
if 'blackfeats' in kwargs.keys():
self.blackfeats = kwargs['blackfeats']
else:
self.blackfeats = []
CocoNgrams.__init__(self, self.n_list, self.blackfeats)
self.feats = []
def fit(self, tagged_data, directory):
"""
Model fitter
=====
Function to make an overview of all the existing features
Parameters
-----
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Attributes
-----
feats : dict
dictionary of features and their count
"""
tmpdir = directory + 'tmp/'
if not os.path.isdir(tmpdir):
os.mkdir(tmpdir)
tokenized = [' '.join([t[0] for t in instance]) + '\n' for instance in tagged_data]
CocoNgrams.fit(self, tmpdir, tokenized)
def transform(self):
"""
Model transformer
=====
Function to featurize instances based on the fitted features
Parameters
-----
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Attributes
-----
instances : list
The documents represented as feature vectors
"""
instances, feats = CocoNgrams.transform(self)
return(instances, feats)
def fit_transform(self, raw_data, tagged_data, directory):
"""
Fit transform
=====
Function to perform the fit and transform sequence
Parameters
-----
raw_data : list
Each entry represents a text instance in the data file
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Returns
-----
self.transform(tagged_data) : list
The featurized instances
self.feats : list
The vocabulary
"""
self.fit(tagged_data, directory)
return self.transform()
class LemmaNgrams:
"""
Lemma ngram extractor
=====
Class to extract Lemma ngrams from all documents
Parameters
-----
kwargs : dict
n_list : list
The values of N (1 - ...)
blackfeats : list
Features to exclude
Attributes
-----
self.name : str
The name of the module
self.n_list : list
The n_list parameter
self.blackfeats : list
The blackfeats parameter
self.feats : list
List of feature names, to keep track of the values of feature indices
"""
def __init__(self, **kwargs):
self.name = 'lemma_ngrams'
self.n_list = kwargs['n_list']
if 'blackfeats' in kwargs.keys():
self.blackfeats = kwargs['blackfeats']
else:
self.blackfeats = []
self.feats = []
def fit(self, tagged_data):
"""
Model fitter
=====
Function to make an overview of all the existing features
Parameters
-----
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Attributes
-----
feats : dict
dictionary of features and their count
"""
feats = {}
for inst in tagged_data:
for n in self.n_list:
tokens = [t[1] for t in inst]
feats.update(utils.freq_dict(["_".join(item) for item in \
utils.find_ngrams(tokens, n)]))
self.feats = [i for i, j in sorted(feats.items(), reverse = True,
key = operator.itemgetter(1)) if not bool(set(i.split("_")) &
set(self.blackfeats))]
def transform(self, tagged_data):
"""
Model transformer
=====
Function to featurize instances based on the fitted features
Parameters
-----
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Attributes
-----
instances : list
The documents represented as feature vectors
"""
instances = []
for inst in tagged_data:
tok_dict = {}
for n in self.n_list:
tokens = [t[1] for t in inst]
tok_dict.update(utils.freq_dict(["_".join(item) for item in \
utils.find_ngrams(tokens, n)]))
instances.append([tok_dict.get(f, 0) for f in self.feats])
return np.array(instances)
def fit_transform(self, raw_data, tagged_data, directory):
"""
Fit transform
=====
Function to perform the fit and transform sequence
Parameters
-----
raw_data : list
Each entry represents a text instance in the data file
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Returns
-----
self.transform(tagged_data) : list
The featurized instances
self.feats : list
The vocabulary
"""
self.fit(tagged_data)
return self.transform(tagged_data), self.feats
class PosNgrams:
"""
Part-of-Speech tag ngram extractor
=====
Class to extract PoS ngrams from all documents
Parameters
-----
kwargs : dict
n_list : list
The values of N (1 - ...)
blackfeats : list
Features to exclude
Attributes
-----
self.name : str
The name of the module
self.n_list : list
The n_list parameter
self.blackfeats : list
The blackfeats parameter
self.feats : list
List of feature names, to keep track of the values of feature indices
"""
def __init__(self, **kwargs):
self.name = 'pos_ngrams'
self.n_list = [int(x) for x in kwargs['n_list']]
if 'blackfeats' in kwargs.keys():
self.blackfeats = kwargs['blackfeats']
else:
self.blackfeats = []
self.feats = []
def fit(self, tagged_data):
"""
Model fitter
=====
Function to make an overview of all the existing features
Parameters
-----
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Attributes
-----
feats : dict
dictionary of features and their count
"""
feats = {}
for inst in tagged_data:
for n in self.n_list:
tokens = [t[2] for t in inst]
feats.update(utils.freq_dict(["_".join(item) for item in \
utils.find_ngrams(tokens, n)]))
self.feats = [i for i, j in sorted(feats.items(), reverse = True,
key = operator.itemgetter(1)) if not bool(set(i.split("_")) &
set(self.blackfeats))]
def transform(self, tagged_data):
"""
Model transformer
=====
Function to featurize instances based on the fitted features
Parameters
-----
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Attributes
-----
instances : list
The documents represented as feature vectors
"""
instances = []
for inst in tagged_data:
tok_dict = {}
for n in self.n_list:
tokens = [t[2] for t in inst]
tok_dict.update(utils.freq_dict(["_".join(item) for item in \
utils.find_ngrams(tokens, n)]))
instances.append([tok_dict.get(f, 0) for f in self.feats])
return np.array(instances)
def fit_transform(self, raw_data, tagged_data, directory):
"""
Fit transform
=====
Function to perform the fit and transform sequence
Parameters
-----
raw_data : list
Each entry represents a text instance in the data file
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Returns
-----
self.transform(tagged_data) : list
The featurized instances
self.feats : list
The vocabulary
"""
self.fit(tagged_data)
return self.transform(tagged_data), self.feats
class CharNgrams:
"""
Character ngram extractor
=====
Class to extract character ngrams from all documents
Parameters
-----
kwargs : dict
n_list : list
The values of N (1 - ...)
blackfeats : list
Features to exclude
Attributes
-----
self.name : str
The name of the module
self.n_list : list
The n_list parameter
self.blackfeats : list
The blackfeats parameter
self.feats : list
List of feature names, to keep track of the values of feature indices
"""
def __init__(self, **kwargs):
self.name = 'char_ngrams'
self.n_list = [int(x) for x in kwargs['n_list']]
if 'blackfeats' in kwargs.keys():
self.blackfeats = kwargs['blackfeats']
else:
self.blackfeats = []
self.feats = []
def fit(self, raw_data):
"""
Model fitter
=====
Function to make an overview of all the existing features
Parameters
-----
raw_data : list
Each entry represents a text instance in the data file
Attributes
-----
feats : dict
dictionary of features and their count
"""
feats = {}
for inst in raw_data:
inst = list(inst)
for n in self.n_list:
feats.update(utils.freq_dict(["".join(item) for item in utils.find_ngrams(inst, n)]))
self.feats = [i for i,j in sorted(feats.items(), reverse=True,
key=operator.itemgetter(1)) if not bool(set(i.split("_")) &
set(self.blackfeats))]
def transform(self, raw_data):
"""
Model transformer
=====
Function to featurize instances based on the fitted features
Parameters
-----
raw_data : list
Each entry represents a text instance in the data file
Attributes
-----
instances : list
The documents represented as feature vectors
"""
instances = []
for inst in raw_data:
inst = list(inst)
char_dict = {}
for n in self.n_list:
char_dict.update(utils.freq_dict(["".join(item) for item in utils.find_ngrams(inst, n)]))
instances.append([char_dict.get(f,0) for f in self.feats])
return np.array(instances)
def fit_transform(self, raw_data, tagged_data, directory):
"""
Fit transform
=====
Function to perform the fit and transform sequence
Parameters
-----
raw_data : list
Each entry represents a text instance in the data file
tagged_data : list
List of lists, where each row represents a text instance and the columns
represent word - lemma - pos - sentence number respectively
Returns
-----
self.transform(tagged_data) : list
The featurized instances
self.feats : list
The vocabulary
"""
self.fit(raw_data)
return self.transform(raw_data), self.feats