-
Notifications
You must be signed in to change notification settings - Fork 1
/
MainRunner.py
2220 lines (1745 loc) · 90.9 KB
/
MainRunner.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
__author__ = "Ivan Bilan"
# from __future__ import print_function
# pip install -U nltk
from nltk.corpus import stopwords
# conda install mingw libpython
# conda install gensim
from gensim import corpora, models
from gensim.models import Phrases
from sklearn.externals import joblib
from time import gmtime, strftime
import cPickle
from nltk.stem.porter import *
# from stemming.porter2 import stem
# from sklearn.linear_model import SGDClassifier
from sklearn import feature_selection
# pip install treetaggerwrapper
import treetaggerwrapper
import string
import codecs
import numpy
from pylab import *
from sklearn import metrics
from sklearn.feature_extraction.text import VectorizerMixin
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import FeatureUnion, Pipeline
# textstat is used for various readability index features, https://pypi.python.org/pypi/textstat/
from textstat.textstat import textstat
from PreprocessingClass import PreprocessingClass
from sklearn.preprocessing import StandardScaler
from FeatureClass import FeatureClass
from sklearn.base import BaseEstimator, TransformerMixin
class SingleFeatureExtractor(object):
"""
This function starts each feature according to its configuration.
Configurations include:
lowercase the whole sample
delete all punctuation marks in the sample
choose pre-scaling or no pre-scaling for feature vectors
"""
def extract_single_feature_pipeline(self, sentence, feature_function, lowercase=None, remove_punc=None, feature_mode=None, feature_name=None, custom_ending=None, write_pickle=1):
# print sentence
# print len(sentence), type(sentence)
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
list_single = list()
# print
if lowercase == 1:
sentence = sentence.lower()
elif lowercase == 2:
pass
if remove_punc == 1:
sentence = sentence.translate(remove_punctuation_map)
elif remove_punc == 2:
pass
# this is used for custom ending feature functions, 1 = skip, else = use specified ending string
if custom_ending == 1:
# print sentence
if feature_mode == "single":
return feature_function(sentence)
elif feature_mode == "single_whole":
return feature_function(sentence, 1)
elif feature_mode == "single_pre_scaled":
# print "working on suffix features"
function_result = feature_function(sentence, 5)
# print function_result
return function_result
# list_single.append([feature_function(sentence)])
elif isinstance(custom_ending, basestring):
if feature_mode == "single":
return feature_function(sentence, 0, custom_ending)
elif feature_mode == "single_whole":
# print "working on suffix features"
function_result = feature_function(sentence, 1, custom_ending)
# print function_result
return function_result
elif feature_mode == "single_pre_scaled":
# print "working on suffix features"
function_result = feature_function(sentence, 5, custom_ending)
# print function_result
return function_result
# list_single.append([feature_function(sentence, custom_ending)])
elif custom_ending == 2:
if feature_mode == "single_whole_ari":
# print "single_whole_ari"
try:
current_result = float(feature_function(sentence, 1))
if current_result < 0:
return 0
else:
return current_result
except:
return 0
else:
try:
return feature_function(sentence)
# list_single.append([feature_function(sentence)])
except:
return 0
class ItemSelector(BaseEstimator, TransformerMixin):
"""For data grouped by feature, select subset of data at a provided key.
The data is expected to be stored in a 2D data structure, where the first
index is over features and the second is over samples. i.e.
>> len(data[key]) == n_samples
Please note that this is the opposite convention to sklearn feature
matrixes (where the first index corresponds to sample).
ItemSelector only requires that the collection implement getitem
(data[key]). Examples include: a dict of lists, 2D numpy array, Pandas
DataFrame, numpy record array, etc.
>> data = {'a': [1, 5, 2, 5, 2, 8],
'b': [9, 4, 1, 4, 1, 3]}
>> ds = ItemSelector(key='a')
>> data['a'] == ds.transform(data)
ItemSelector is not designed to handle data grouped by sample. (e.g. a
list of dicts). If your data is structured this way, consider a
transformer along the lines of `sklearn.feature_extraction.DictVectorizer`.
Parameters
----------
key : hashable, required
The key corresponding to the desired value in a mappable.
"""
def __init__(self, key):
self.key = key
def fit(self, x, y=None):
return self
def transform(self, data_dict):
return data_dict[self.key]
class MeasureFeatures(BaseEstimator, SingleFeatureExtractor):
"""
Feature Cluster to evaluate
type/token ration, average word length, punctuation marks, capitalized words
"""
def __init__(self, comment, lang):
self.comment = comment
self.lang = lang
def get_feature_names(self):
return numpy.array(['type_token', 'avgwordlenght', 'punctuation', 'capitals'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "measure_cluster"
print "Unique_identifier: ", unique_identifier
X_average_word_len = list()
X_type_token = list()
X_punctuation = list()
X_capitals = list()
X_allcaps = list()
print "Started training Measure features"
timer_start = datetime.datetime.now().replace(microsecond=0)
featureObject = FeatureClass(self.lang)
for element in documents:
# print element
X_average_word_len.append(self.extract_single_feature_pipeline(element, featureObject.average_wordlength, 2, 2, "single", "average_word_len", 1))
X_type_token.append(self.extract_single_feature_pipeline(element, featureObject.type_token_ratio, 1, 1, "single", "typetoken", 1))
X_punctuation.append(self.extract_single_feature_pipeline(element, featureObject.general_punctuation_new, 2, 2, "single_pre_scaled", "punctuation", 1))
X_capitals.append(self.extract_single_feature_pipeline(element, featureObject.words_capitalized, 2, 2, "single_pre_scaled", "capitals", 1))
X_allcaps.append(self.extract_single_feature_pipeline(element, featureObject.AllCaps, 2, 2, "single_pre_scaled", "capitals", 1))
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Measure features" + " :" + str(timer_end - timer_start)
print
X = numpy.array([X_type_token, X_average_word_len, X_punctuation, X_capitals, X_allcaps]).T
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
print inner_feature_name, X
print X.shape
return X
def lda_preprocess(text):
return text.lower()
class LDA(BaseEstimator, VectorizerMixin):
"""
Uses gensim library for topic modeling
The code in this function is based on https://github.com/pan-webis-de/authorprofile15
"""
def __init__(self, lang):
self.number_of_topics = 100
self.preprocessor = lda_preprocess
self.tokenizer = None
self.language = lang
# print self.language
if self.language == "en":
self.stop_words = 'english'
elif self.language == "nl":
self.stop_words = 'dutch'
elif self.language == "es":
self.stop_words = 'spanish'
self.bigram = True
self.trigram = None
self.analyzer = 'word'
self.ngram_range = (1, 1)
self.input = 'content'
self.encoding = 'utf-8'
self.strip_accents = None
self.decode_error = 'strict'
self.lowercase = True
self.token_pattern = r"(?u)\b\w\w+\b"
def get_stop_words(self):
stop_lst = stopwords.words(self.stop_words)
# print self.stop_words
# stop_lst=[]
# if self.stop == "english":
# stop_lst = stopwords.words('english')
# print stop_lst
stop_lst.extend(["USER", "URL", "i'm", "rt"])
stop_lst.extend(list(string.punctuation))
# print "Stopword list------->",stop_lst
return set(stop_lst)
def get_feature_names(self):
return np.array(
["Topic_" + str(topic) for topic in xrange(0, self.number_of_topics)])
def _build_vocabulary(self, raw_documents, fixed_vocab=None):
analyze = self.build_analyzer()
'''
for document in raw_documents:
print document
print
'''
doc_token_lst = [analyze(document) for document in raw_documents]
if self.bigram or self.trigram:
bigram = Phrases(doc_token_lst)
if self.trigram:
trigram = []
if fixed_vocab:
vocabulary = self.vocabulary_
tfidf_model = self.tfidf_
corpus_vector = [vocabulary.doc2bow(text) for text in doc_token_lst]
else:
vocabulary = corpora.Dictionary(doc_token_lst)
corpus_vector = [vocabulary.doc2bow(text) for text in doc_token_lst]
tfidf_model = models.TfidfModel(corpus_vector)
self.tfidf_ = tfidf_model
return tfidf_model[corpus_vector], vocabulary
def fit(self, documents, y=None):
self.fit_transform(documents)
return self
def fit_transform(self, raw_documents, y=None):
# analyze = self.build_analyzer()
# doc_token_lst = [analyze(document) for document in raw_documents] # bigrams of phrases
# if self.bigram or self.trigram:
# bigram = Phrases(doc_token_lst)
#
# if self.trigram:
# trigram = []
#
# vocabulary = corpora.Dictionary(doc_token_lst)
# self.corpus_vector_ = [self.dictionary.doc2bow(text) for text in doc_token_lst]
#
# self.tfidf_ = models.TfidfModel(self.corpus_vector_)
# self.corpus_tfidf_ = self.tfidf_[self.corpus_vector_]
X, vocabulary = self._build_vocabulary(raw_documents, False)
self.vocabulary_ = vocabulary
self.lda_ = models.LdaModel(X, id2word=self.vocabulary_, num_topics=self.number_of_topics)
# intsead of LDA you can use HDP Model, which calculates the number of topics automatically
# self.lda_ = models.hdpmodel.HdpModel(X, id2word=self.vocabulary_) # , num_topics=self.number_of_topics
return self._fit_doc_topic(X)
def _fit_doc_topic(self, X):
Topic_X = []
for doc in X:
weight = np.zeros(self.number_of_topics)
for topic_id, prob in self.lda_[doc]:
weight[topic_id] = prob
Topic_X.append(weight)
# print Topic_X
return np.array(Topic_X)
def topics(self, n_topic_words, out_file):
with codecs.open(out_file, 'w') as out:
for i in range(0, self.number_of_topics):
topic_words = [term[1].encode('utf-8') for term in self.lda_.show_topic(i, n_topic_words)]
out.write("Top {} terms for topic #{} : {}".format(n_topic_words, i, ", ".join(topic_words)))
out.write("\n\n================================================================================\n")
def transform(self, documents):
# if not hasattr(self, 'vocabulary_'):
# self._check_vocabulary()
if not hasattr(self, 'vocabulary_') or len(self.vocabulary_) == 0:
raise ValueError("Vocabulary wasn't fitted or is empty!")
X, _ = self._build_vocabulary(documents, True)
return self._fit_doc_topic(X)
class FamilialFeatures(BaseEstimator, SingleFeatureExtractor):
"""
Computes familial tokens features
The code in this function is based on https://github.com/pan-webis-de/authorprofile15
"""
def __init__(self, comment, lang):
self.language = lang
if self.language == "en":
self.male = set([u'wife', u'gf', u'girlfriend'])
self.female = set([u'husband', u'bf', u'boyfriend', u'hubby'])
self.neutral = set([u'son', u'daughter', u'grandson', u'granddaughter', u'father', u'mother', u'brother', u'sister', u'uncle', u'aunt', u'cousin', u'nephew', u'niece', u'family', u'godson', u'goddaughter', u'grandchild', u'grandmother', u'grandfather', u'baby', u'babies', u'child', u'children', u'kids', u'kid', u'mom', u'parent'])
elif self.language == "nl":
self.male = set([u'vrouw', u'vriendin', u'lieve vrouw'])
self.female = set([u'man', u'bf', u'vriend', u'lieve man', u'manlief', u'vriendje'])
self.neutral = set([u'zoon', u'dochter', u'kleinzoon', u'kleindochter', u'vader', u'moeder', u'broer', u'zus', u'oom', u'tante', u'neef', u'nicht', u'niece', u'familie', u'petekind', u'kleinkind', u'grootmoeder', u'grootvader', u'baby', u'babys', u'kind', u'kinderen', u'ouder'])
elif self.language == "es":
self.male = set([u'esposa', u'novia', u'amiga', u'mujer', u'señora', u'vieja'])
self.female = set([u'esposo', u'marido', u'esposito', u'novio', u'amigo', u'novio', u'maridito', u'hombre'])
self.neutral = set([u'hijo', u'hija', u'hijos', u'hijas', u'nietos', u'nietas', u'papa', u'mama', u'abuelos', u'abuela', u'abuelo', u'hermano', u'hermana', u'tío', u'tía', u'primo', u'prima', u'sobrina', u'sobrino', u'crio', u'cría', u'bebes', u'familia', u'ahijado', u'ahijada', u'nieto', u'nieta', u'niños', u'niñas', u'mami', u'papi', u'pareja'])
self.comment = comment
self.preprocessing_counter = FeatureClass(self.language)
def get_feature_names(self):
return np.array(['male_bucket', 'female_bucket', 'neutral_bucket'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "familial_cluster"
print "Unique_identifier: ", unique_identifier
print "Started calculating Familial Features " + self.comment
timer_start = datetime.datetime.now().replace(microsecond=0)
featureObject = FeatureClass(self.language)
# single
male = re.compile(featureObject.regex_str(self.male), re.IGNORECASE)
# male = re.compile(r"\b(?:dw|my\b\W+\b(?:girlfriend|gf|wife))\W*", re.IGNORECASE)
# print regex_str(self.male)
female = re.compile(featureObject.regex_str(self.female), re.IGNORECASE)
neutral = re.compile(featureObject.regex_str(self.neutral), re.IGNORECASE)
male_count = list()
female_count = list()
neutral_count = list()
for index, doc in enumerate(documents):
male_counter = len(male.findall(doc.lower()))
female_counter = len(female.findall(doc.lower()))
neutral_counter = len(neutral.findall(doc.lower()))
male_count.append(self.preprocessing_counter.counter_pre_scaling(male_counter, len(doc.split())))
female_count.append(self.preprocessing_counter.counter_pre_scaling(female_counter, len(doc.split())))
neutral_count.append(self.preprocessing_counter.counter_pre_scaling(neutral_counter, len(doc.split())))
# print neutral_count
male_bucket = np.array(male_count)
female_bucket = np.array(female_count)
neutral_bucket = np.array(neutral_count)
X = np.array([male_bucket, female_bucket, neutral_bucket]).T
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
print X
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Familial Cluster" + " :" + str(timer_end - timer_start) + " " + self.comment
print
return X
class SmogARI(BaseEstimator):
"""
Compute SmogARI
"""
def get_feature_names(self):
return numpy.array(['smog_ari'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
X_list = list()
print "Started training SMOG ARI features"
timer_start = datetime.datetime.now().replace(microsecond=0)
for index, element in enumerate(documents):
# print element
X_list.append(self.extract_single_feature_pipeline(element, textstat.smog_index, 2, 2, "single_whole", "smog_ari", 2))
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for SMOG ARI features" + " :" + str(timer_end - timer_start)
print
X = numpy.array([X_list]).T
if not hasattr(self, 'scalar'):
self.scalar = StandardScaler().fit(X)
return self.scalar.transform(X)
class DifficultWordsARI(BaseEstimator):
"""
Compute DifficultWordsARI
"""
def get_feature_names(self):
return numpy.array(['difficult_words_ari'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
X_list = list()
print "Started training difficult_words features"
timer_start = datetime.datetime.now().replace(microsecond=0)
for index, element in enumerate(documents):
# print element
X_list.append(self.extract_single_feature_pipeline(element, textstat.difficult_words, 2, 2, "single_whole", "difficult_words_ari", 2))
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for difficult_words features" + " :" + str(timer_end - timer_start)
print
X = numpy.array([X_list]).T
# print inner_feature_name, X
print X.shape
if not hasattr(self, 'scalar'):
self.scalar = StandardScaler().fit(X)
return self.scalar.transform(X)
class FleschReadingEase(BaseEstimator):
"""
Compute FleschReadingEase
More readability functions are available at https://pypi.python.org/pypi/textstat/
"""
def __init__(self, comment):
self.comment = comment
def get_feature_names(self):
return numpy.array(['flesch_reading_ari'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "flesch_measure_cluster"
print "Unique_identifier: ", unique_identifier,
X_list = list()
print "Started training flesch_reading_ari features"
timer_start = datetime.datetime.now().replace(microsecond=0)
for index, element in enumerate(documents):
# print element
X_list.append(self.extract_single_feature_pipeline(element, textstat.flesch_reading_ease, 2, 2, "single_whole_ari", "flesch_reading_ari", 2))
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for flesch_reading_ari features" + " :" + str(timer_end - timer_start)
print
X = numpy.array([X_list]).T
print inner_feature_name, X
print X.shape
return X
class CounterFeatures(BaseEstimator, SingleFeatureExtractor):
"""
Compute usage of
connective words, emotion words, linked content, stop words, contractions, slang words and abbreviations.
"""
def __init__(self, comment, lang):
self.comment = comment
self.language = lang
def get_feature_names(self):
return numpy.array(['connective_words', 'emotion_words', 'linked_content', 'stop_words', 'contractions', 'slang_words', 'abreviations'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "counter_cluster"
print "Unique_identifier: ", unique_identifier
X_connectives = list()
X_emotion_words =list()
X_urls = list()
X_stop_words = list()
X_contractions = list()
X_slang_words = list()
X_abbreviations = list()
print "Started training Counter Feature " + self.comment
timer_start = datetime.datetime.now().replace(microsecond=0)
featureObject = FeatureClass(self.language)
for index, element in enumerate(documents):
X_connectives.append(self.extract_single_feature_pipeline(element, featureObject.connective_words, 1, 1, "single_pre_scaled", "connectives", 1))
X_emotion_words.append(self.extract_single_feature_pipeline(element, featureObject.emotion_words, 1, 1, "single_pre_scaled", "emotion_words", 1))
X_urls.append(self.extract_single_feature_pipeline(element, featureObject.catch_url, 2, 2, "single_pre_scaled", "url", 1))
X_stop_words.append(self.extract_single_feature_pipeline(element, featureObject.count_stop_words, 1, 2, "single_pre_scaled", "count_stop_words", 1))
X_contractions.append(self.extract_single_feature_pipeline(element, featureObject.contractions, 1, 2, "single_pre_scaled", "contractions", 1))
X_slang_words.append(self.extract_single_feature_pipeline(element, featureObject.slang_words, 2, 2, "single_pre_scaled", "slang_words", 1))
X_abbreviations.append(self.extract_single_feature_pipeline(element, featureObject.get_abbreviations, 1, 1, "single_pre_scaled", "abbreviations", 1))
'''
from unidecode import unidecode
print unidecode(element)
print X_connectives[index], X_emotion_words[index], X_urls[index], X_stop_words[index], X_contractions[index], X_slang_words[index], X_abbreviations[index]
'''
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Counter Feature" + " :" + str(timer_end - timer_start)
print
X = numpy.array([X_connectives, X_emotion_words, X_urls, X_stop_words, X_contractions, X_slang_words, X_abbreviations]).T
print inner_feature_name, X
print X.shape
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
# print "Counter Features: ", X
return X
class CounterFeatures2(BaseEstimator, SingleFeatureExtractor):
"""
Compute usage of
question marks, user mentions, hashtag uses, exclamation marks
"""
def __init__(self, comment, lang):
self.comment = comment
self.language = lang
self.preprocessing_counter = FeatureClass(self.language)
def get_feature_names(self):
return numpy.array(['question_marks', 'users', 'hashes', 'exclam_mark'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "counter_2_cluster"
print "Unique_identifier: ", unique_identifier
X_question_mark =list()
X_exclamation_mark = list()
X_hashes = list()
X_users = list()
print "Started training Counter Feature " + self.comment
timer_start = datetime.datetime.now().replace(microsecond=0)
for index, doc in enumerate(documents):
question_counter = float(len(re.findall(r"\?", doc)))
X_question_mark.append(self.preprocessing_counter.counter_pre_scaling_char(question_counter, len(doc)))
exlam_mark_counter = float(len(re.findall(r"\!", doc)))
X_exclamation_mark.append(self.preprocessing_counter.counter_pre_scaling_char(exlam_mark_counter, len(doc)))
hash_counter = float(len(re.findall(r"\#", doc)))
X_hashes.append(self.preprocessing_counter.counter_pre_scaling_char(hash_counter, len(doc)))
users_counter = float(len(re.findall(r"user", doc, re.IGNORECASE)))
X_users.append(self.preprocessing_counter.counter_pre_scaling(users_counter, len(doc.split())))
'''
from unidecode import unidecode
print unidecode(doc)
print X_question_mark[index], X_exclamation_mark[index], X_hashes[index], X_users[index]
'''
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Counter Feature" + " :" + str(timer_end - timer_start)
print
X = numpy.array([X_question_mark, X_exclamation_mark, X_hashes, X_users]).T
print inner_feature_name, X
print X.shape
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
# print "Counter Features: ", X
return X
class POSCluster(BaseEstimator, SingleFeatureExtractor):
"""
Compute usage of
various part-of-speech tags and the F-Measure feature
"""
def __init__(self, comment, lang):
self.comment = comment
self.language = lang
def get_feature_names(self):
return numpy.array(["plurality", "lexical_f_measure", "determiner", "pronouns", "adjectives", "cardinals", "to_preposition", "conjunctions", "verbs"])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "pos_cluster"
print "Unique_identifier: ", unique_identifier
X_plurality = list()
X_lexical_f_measure = list()
X_determiner = list()
X_pronouns = list()
X_adjectives = list()
X_cardinals = list()
X_to_preposition = list()
X_conjunctions = list()
X_verbs = list()
print "Started training POS Cluster for: " + self.comment
print "Length for: " + self.comment + ", is " + str(len(documents))
timer_start = datetime.datetime.now().replace(microsecond=0)
featureObject = FeatureClass(self.language)
for index, element in enumerate(documents):
# print element
X_plurality.append(self.extract_single_feature_pipeline(element, featureObject.plurality, 2, 2, "single_pre_scaled", "plurality", 1))
X_lexical_f_measure.append(self.extract_single_feature_pipeline(element, featureObject.lexical_Fmeasure_new, 2, 2, "single", "lexical_fmeasure", 1))
X_determiner.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "determiner", "determiner"))
X_pronouns.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "pronouns", "pronouns"))
X_adjectives.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "adjectives", "adjectives"))
X_cardinals.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "cardinal_num", "cardinal_num"))
X_to_preposition.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "to_pos", "to_pos"))
X_conjunctions.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "conjunctions", "conjunctions"))
X_verbs.append(self.extract_single_feature_pipeline(element, featureObject.each_part_of_speech, 2, 2, "single_pre_scaled", "verbs", "verbs"))
'''
from unidecode import unidecode
print unidecode(element)
print X_plurality[index], X_lexical_f_measure[index], X_determiner[index], X_pronouns[index], X_adjectives[index], X_cardinals[index], X_to_preposition[index], X_conjunctions[index], X_verbs[index]
'''
X = numpy.array([X_plurality, X_lexical_f_measure, X_determiner, X_pronouns, X_adjectives, X_cardinals, X_to_preposition, X_conjunctions, X_verbs]).T
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
print inner_feature_name, X
print X.shape
# plotting
plot_label = "POS Cluster"
# plot_feature_for_all_sets(inner_feature_name, unique_identifier, X, plot_label)
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for POS Cluster" + " :" + str(timer_end - timer_start) + " " + self.comment
print
return X
class StylisticEndings(BaseEstimator, SingleFeatureExtractor):
"""
Compute usage of
various adjectival and adverbial endings for English
"""
def __init__(self, comment, lang):
self.comment = comment
self.language = lang
def get_feature_names(self):
return numpy.array(['suf_able', 'suf_ful', 'suf_al', 'suf_ible', 'suf_ic', 'suf_ive', 'suf_less', 'suf_ous', 'suf_ly'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "stylistic_cluster"
print "Unique_identifier: ", unique_identifier
X_able = list()
X_ful = list()
X_al = list()
X_ible = list()
X_ic = list()
X_ive = list()
X_less = list()
X_ous = list()
X_ly = list()
print "Started training Stylistic Suffix Features EN " + self.comment
timer_start = datetime.datetime.now().replace(microsecond=0)
# print len(documents)
# print documents[2]
# sleep(10)
featureObject = FeatureClass(self.language)
for index, element in enumerate(documents):
result_able = self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "able", "able")
X_able.append(result_able)
X_ful.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ful", "ful"))
X_al.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "al", "al"))
X_ible.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ible", "ible"))
X_ic.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ic", "ic"))
X_ive.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ive", "ive"))
X_less.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "less", "less"))
X_ous.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ous", "ous"))
X_ly.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ly", "ly"))
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Stylistic Suffix Features EN " + " :" + str(timer_end - timer_start) + self.comment
print
X = numpy.array([X_able, X_ful, X_al, X_ible, X_ic, X_ive, X_less, X_ous, X_ly]).T
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
print inner_feature_name, X
print X.shape
return X
class StylisticEndingsDutch(BaseEstimator, SingleFeatureExtractor):
"""
Compute usage of
various adjectival and adverbial endings for Dutch
"""
def __init__(self, comment, lang):
self.comment = comment
self.language = lang
def get_feature_names(self):
# https://en.wiktionary.org/wiki/Category:Dutch_suffixes
return numpy.array(['jes', 'iek', 'eren'])
# 'achtig', 'baar', 'haftig', 'isch', 'lijks', 'vol'
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "stylistic_cluster"
print "Unique_identifier: ", unique_identifier
X_able = list()
X_ful = list()
X_al = list()
X_ible = list()
X_ic = list()
X_ive = list()
X_less = list()
X_ous = list()
X_ly = list()
print "Started training Stylistic Suffix Features NL " + self.comment
timer_start = datetime.datetime.now().replace(microsecond=0)
# print len(documents)
# print documents[2]
# sleep(10)
featureObject = FeatureClass(self.language)
for index, element in enumerate(documents):
'''
result_able = self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "achtig", "achtig")
X_able.append(result_able)
X_ful.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "baar", "baar"))
X_al.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "haftig", "haftig"))
X_ible.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "isch", "isch"))
X_ic.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "lijks", "lijks"))
X_ly.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "vol", "vol"))
'''
X_ive.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "jes", "jes"))
X_less.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "iek", "iek"))
X_ous.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "eren", "eren"))
from unidecode import unidecode
print unidecode(element)
print X_less[index], X_ive[index], X_ous[index]
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Stylistic Suffix Features NL " + " :" + str(timer_end - timer_start) + self.comment
print
# X_able, X_ful, X_al, X_ly, X_ible, X_ic,
X = numpy.array([X_ive, X_less, X_ous]).T
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
print inner_feature_name, X
print X.shape
return X
class StylisticEndingsSpanish(BaseEstimator, SingleFeatureExtractor):
"""
Compute usage of
various adjectival and adverbial endings for Spanish
"""
def __init__(self, comment, lang):
self.comment = comment
self.language = lang
def get_feature_names(self):
# http://spanish.about.com/od/spanishvocabulary/a/intro_to_suffixes_2.htm
return numpy.array(['ito', 'ada', 'anza', 'acho', 'acha', 'mente', 'ita', 'ote', 'dero'])
def fit(self, documents, y=None):
return self
def transform(self, documents):
unique_identifier = self.comment + "_" + str(len(documents))
inner_feature_name = unique_identifier + "stylistic_cluster"
print "Unique_identifier: ", unique_identifier
X_able = list()
X_ful = list()
X_al = list()
X_ible = list()
X_ic = list()
X_ive = list()
X_less = list()
X_ous = list()
X_ly = list()
print "Started training Stylistic Suffix Features ES" + self.comment
timer_start = datetime.datetime.now().replace(microsecond=0)
# print len(documents)
# print documents[2]
# sleep(10)
featureObject = FeatureClass(self.language)
for index, element in enumerate(documents):
result_able = self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ito", "ito")
X_able.append(result_able)
X_ful.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ada", "ada"))
X_al.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "anza", "anza"))
X_ible.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "acho", "acho"))
X_ic.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "acha", "acha"))
X_ive.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "mente", "mente"))
X_less.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ita", "ita"))
X_ous.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "ote", "ote"))
X_ly.append(self.extract_single_feature_pipeline(element, featureObject.stylistic_ending_custom, 1, 1, "single_pre_scaled", "dero", "dero"))
from unidecode import unidecode
print unidecode(element)
print X_able[index], X_ful[index], X_al[index], X_ible[index], X_ic[index], X_ive[index], X_less[index], X_ous[index], X_ly[index]
timer_end = datetime.datetime.now().replace(microsecond=0)
print "Training time for Stylistic Suffix Features ES " + " :" + str(timer_end - timer_start) + self.comment
print
X = numpy.array([X_able, X_ful, X_al, X_ible, X_ic, X_ive, X_less, X_ous, X_ly]).T
# dump and load
# dump_feature_for_all_sets(inner_feature_name, unique_identifier, X)
# X = load_feature_for_all_sets(unique_identifier, inner_feature_name)
print inner_feature_name, X
print X.shape
return X
class CategoricalCharNgramsVectorizer(TfidfVectorizer):
"""
Generates different categories of char n-grams and uses them as features
The code in this function is based on https://github.com/pan-webis-de/authorprofile15,
which is based on this paper:
6. Sapkota, U., Bethard, S., Montes, M., Solorio, T.: Not all character n-grams are created equal:A study in authorship attribution. In: Proceedings of the 2015 Conference of the North Amer-ican Chapter of the Association for Computational Linguistics: Human Language Technolo-gies. pp. 93–102. Association for Computational Linguistics, Denver, Colorado (May–June2015), http://www.aclweb.org/anthology/N15-1010
"""
_slash_W = string.punctuation + " "
_punctuation = r'''['\"“”-‘’.?!…,:;#\<\=\>@\(\)\*]'''
_beg_punct = lambda self, x: re.match('^' + self._punctuation + '\w+', x)
_mid_punct = lambda self, x: re.match(r'\w+' + self._punctuation + '(?:\w+|\s+)', x)
_end_punct = lambda self, x: re.match(r'\w+' + self._punctuation + '$', x)
# re.match is anchored at the beginning
_whole_word = lambda self, x, y, i, n: not (re.findall(r'(?:\W|\s)', x)) and (
i == 0 or y[i - 1] in self._slash_W) and (i + n == len(y) or y[i + n] in self._slash_W)
_mid_word = lambda self, x, y, i, n: not (
re.findall(r'(?:\W|\s)', x) or i == 0 or y[i - 1] in self._slash_W or i + n == len(y) or y[
i + n] in self._slash_W)
_multi_word = lambda self, x: re.match('\w+\s\w+', x)
_prefix = lambda self, x, y, i, n: not (re.findall(r'(?:\W|\s)', x)) and (i == 0 or y[i - 1] in self._slash_W) and (
not (i + n == len(y) or y[i + n] in self._slash_W))
_suffix = lambda self, x, y, i, n: not (re.findall(r'(?:\W|\s)', x)) and (
not (i == 0 or y[i - 1] in self._slash_W)) and (i + n == len(y) or y[i + n] in self._slash_W)
_space_prefix = lambda self, x: re.match(r'''^\s\w+''', x)
_space_suffix = lambda self, x: re.match(r'''\w+\s$''', x)
# def _whole_word(self,x, y, i, n):
# if i == 0 or y[i-1] in self._slash_W:
# if i + n == len(y) or y[i+n] in self._slash_W:
# print "here 2"
# return True
# return False