-
Notifications
You must be signed in to change notification settings - Fork 1
/
mercari.py
1736 lines (1452 loc) · 68.3 KB
/
mercari.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
import gc
import time
import numpy as np
import pandas as pd
import sys, os, psutil
from scipy.sparse import csr_matrix, hstack, vstack
from sklearn.svm import LinearSVR
from sklearn.linear_model import Ridge, SGDRegressor
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
from multiprocessing import Process, Pool, Queue, JoinableQueue
import functools
from scipy.special import erfinv
import re
import unidecode
from sklearn.preprocessing import OneHotEncoder
from nltk.tokenize import TweetTokenizer
import warnings
import math
from threading import Thread
warnings.filterwarnings("ignore", category=DeprecationWarning)
NUM_BRANDS = 4000
NUM_CATEGORIES = 1000
NAME_MIN_DF = 10
MAX_FEATURES_ITEM_DESCRIPTION = 5000
Hash_binary = True
ensemble = True
OOF = True
non_alphanums = re.compile(u'[^A-Za-z0-9]+')
#####################################################################
# Multi processing classes
#####################################################################
class BaseWorker(Process):
def __init__(self, q_in, q_out):
self.task_queue: Queue = q_in
self.result_queue: Queue = q_out
super(BaseWorker, self).__init__()
def check_mem(self, dsp=""):
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0] / 2. ** 30
print("%s MEMORY USAGE for PID %5d : %.3f" % (dsp, pid, memoryUse))
class HashingWorker(BaseWorker):
def run(self):
# Get what's on the queue
# The queue should contain :
# an id for ordering purposes
# a data set
# a vectorizer that implements fit_transform
pid = os.getpid()
while True:
# self.check_mem("Hashing Worker")
id_, data_, hashing_vectorizer_ = self.task_queue.get(block=True)
new_data = hashing_vectorizer_.fit_transform(data_)
self.task_queue.task_done()
self.result_queue.put([id_, new_data])
del new_data, data_, hashing_vectorizer_, id_
gc.collect()
class ApplySeriesWorker(BaseWorker):
def run(self):
# Get what's on the queue
# The queue should contain :
# an id for ordering purposes
# a pd.Series
# a function to apply to the Series
pid = os.getpid()
while True:
# self.check_mem("Apply Series Worker")
id_, data_, func_ = self.task_queue.get(block=True)
new_data = data_.apply(func_)
self.task_queue.task_done()
self.result_queue.put([id_, new_data])
del new_data, data_, func_, id_
gc.collect()
class ApplyWorker(BaseWorker):
def run(self):
# Get what's on the queue
# The queue should contain
# an id for ordering purposes
# a pd.DataFrame to apply a function on
# a function to be applied on the pd.DataFrame
# the axis on which the function has to be applied (usually 1)
# a Boolean to say if data is passed as raw data to the function
pid = os.getpid()
while True:
# self.check_mem("Apply Worker")
id_, data_, func_, axis_, raw_ = self.task_queue.get(block=True)
new_data = data_.apply(func_, axis=axis_, raw=raw_)
self.task_queue.task_done()
self.result_queue.put([id_, new_data])
del new_data, data_, func_, id_
gc.collect()
class HashingManager(object):
def __init__(self, nb_workers=1):
self.q_jobs = JoinableQueue()
self.q_results = Queue()
self.nb_workers = nb_workers
self.hashing_workers = [HashingWorker(q_in=self.q_jobs, q_out=self.q_results)
for _ in range(self.nb_workers)]
for wk in self.hashing_workers:
wk.start()
def apply(self, data_, hashing_vectorizer_):
# Split data in chuncks and put on queue
for id_, chunk_ in enumerate(np.array_split(data_, self.nb_workers)):
self.q_jobs.put([id_, chunk_, hashing_vectorizer_])
del id_, chunk_
gc.collect()
# Wait for tasks to complete
# Useless to wait, the get statement will do this
# plus the join will create a deadlock... stupid me
# self.q_jobs.join()
data_list = []
for i in range(self.nb_workers):
id, result = self.q_results.get()
data_list.append([id, result])
del id, result
gc.collect()
the_result = vstack([data_ for id_, data_ in sorted(data_list, key=lambda x: x[0])]).tocsr()
del data_list
gc.collect()
return the_result
def __del__(self):
for wk in self.hashing_workers:
wk.terminate()
class ApplySeriesManager(object):
def __init__(self, nb_workers=1):
self.q_jobs = JoinableQueue()
self.q_results = Queue()
self.nb_workers = nb_workers
self.apply_series_workers = [ApplySeriesWorker(self.q_jobs, self.q_results) for _ in range(self.nb_workers)]
for wk in self.apply_series_workers:
wk.start()
def apply(self, data_, func_):
# Split data in chuncks and put on queue
for id_, chunk_ in enumerate(np.array_split(data_, self.nb_workers)):
self.q_jobs.put([id_, chunk_, func_])
del id_, chunk_
gc.collect()
# Wait for tasks to complete
# self.q_jobs.join()
data_list = []
for i in range(self.nb_workers):
id, result = self.q_results.get()
data_list.append([id, result])
del id, result
gc.collect()
the_result = pd.concat([data_ for id_, data_ in sorted(data_list, key=lambda x: x[0])],
axis=0,
ignore_index=True)
del data_list
gc.collect()
return the_result
def __del__(self):
for wk in self.apply_series_workers:
wk.terminate()
class ApplyManager(object):
def __init__(self, nb_workers=1):
self.q_jobs = JoinableQueue()
self.q_results = Queue()
self.nb_workers = nb_workers
self.apply_workers = [ApplyWorker(self.q_jobs, self.q_results) for _ in range(self.nb_workers)]
for wk in self.apply_workers:
wk.start()
def apply(self, df=None, func=None, axis=0, raw=True):
# Split data in chuncks and put on queue
for id_, chunk_ in enumerate(np.array_split(df, self.nb_workers)):
self.q_jobs.put([id_, chunk_, func, axis, raw])
del id_, chunk_
gc.collect()
# Wait for tasks to complete
# self.q_jobs.join()
data_list = []
for i in range(self.nb_workers):
id, result = self.q_results.get()
data_list.append([id, result])
del id, result
gc.collect()
the_result = pd.concat([data_ for id_, data_ in sorted(data_list, key=lambda x: x[0])],
axis=0,
ignore_index=True)
del data_list
gc.collect()
return the_result
def __del__(self):
for wk in self.apply_workers:
wk.terminate()
def fit_sgd_models(csr_ridge_trn, folds, y):
# print("THREADING EXPERIMENT")
sgd_list = []
for fold_n, (trn_idx, val_idx) in enumerate(folds.split(csr_ridge_trn)):
sgd_list.append((
"liblinear_fold_" + str(fold_n),
LinearSVR(C=0.025,
dual=True,
epsilon=0.0,
fit_intercept=True,
intercept_scaling=1.0,
loss='squared_epsilon_insensitive',
max_iter=50,
random_state=0,
tol=0.0001,
verbose=0),
trn_idx,
val_idx
))
sgd_list.append((
"ridge_fold_" + str(fold_n),
Ridge(solver="sag",
fit_intercept=True,
alpha=0.5,
tol=0.05,
random_state=666,
max_iter=100),
trn_idx,
val_idx
))
model_list = []
for i in range(folds.n_splits):
# print("Create a thread for %s" % sgd_list[i * 2][0])
th1 = FitterThread(
name=sgd_list[i * 2][0],
model=sgd_list[i * 2][1],
data=csr_ridge_trn[sgd_list[i * 2][2]],
target=y[sgd_list[i * 2][2]]
)
# print("Create a thread for %s" % sgd_list[i * 2 + 1][0])
th2 = FitterThread(
name=sgd_list[i * 2 + 1][0],
model=sgd_list[i * 2 + 1][1],
data=csr_ridge_trn[sgd_list[i * 2 + 1][2]],
target=y[sgd_list[i * 2 + 1][2]]
)
th1.start()
th2.start()
th1.join()
th2.join()
# Check the model has been fitted
val_preds_1 = sgd_list[i * 2][1].predict(csr_ridge_trn[sgd_list[i * 2][3]])
val_preds_2 = sgd_list[i * 2 + 1][1].predict(csr_ridge_trn[sgd_list[i * 2 + 1][3]])
print("Validation score for %s = %.6f"
% (sgd_list[i * 2][0], mean_squared_error(y[sgd_list[i * 2][3]], val_preds_1) ** .5))
print("Validation score for %s = %.6f"
% (sgd_list[i * 2 + 1][0], mean_squared_error(y[sgd_list[i * 2 + 1][3]], val_preds_2) ** .5))
model_list.append(sgd_list[i * 2][1])
model_list.append(sgd_list[i * 2 + 1][1])
return model_list
class FitterThread(Thread):
""" Thread that fits a model on given data """
def __init__(self, name, model, data, target):
Thread.__init__(self)
self.model = model
self.name = name
self.data = data
self.target = target
def run(self):
self.model.fit(self.data, self.target)
#####################################################################
# Text preprocessing
#####################################################################
def preprocess(text):
# Replace punctuation with tokens so we can use them in our model
try:
text = unidecode.unidecode(text)
text = str(text).lower()
except:
text="missing"
text = text.lower()
text = text.replace('❌', ' <HECROSS_MA ')
text = text.replace('⛔', ' <NO_ENT_EM')
text = text.replace('‼️', ' <HEAVY_EXCLAMATION> ')
text = text.replace('⭕', ' <HEAVY_LARGE_CIRCLE> ')
text = text.replace('❤️', ' <HEAVY_HEART_MARK> ')
text = text.replace('❗️', ' <HEAVY_EXCLAMATION_MARK ')
text = text.replace('✔', ' <HEAVY_CHECK_MARK> ')
text = text.replace('⭐️', ' <WHITE_MEDIUM_STAR_MARK> ')
text = text.replace('✅', ' <WHITE_HEAVY_CHECK_MARK> ')
text = text.replace('☺️', ' <SMILING_FACE_EMOJI> ')
text = text.replace('《', ' <DOUBLE_BRACKET_QUOTES> ')
text = text.replace('➡', ' <BLACK_RIGHTWARDS_ARROW> ')
text = text.replace('✴️', ' <EIGHT_POINTEDP_STAR> ')
# text = re.sub('\&', " and ", text, flags=re.IGNORECASE)
text = re.sub('\%', " percent ", text, flags=re.IGNORECASE)
text = text.replace('.', ' <.> ')
text = text.replace(',', ' <,> ')
text = text.replace(',', ' <HEAVY_COMMA> ')
text = text.replace('"', ' <"> ')
text = text.replace("”", ' <RIGHT_DBLE_QUOT> ')
text = text.replace("''", ' <''> ')
text = text.replace('=', ' <=> ')
text = text.replace('+', ' <+> ')
text = text.replace('^^', ' <^^> ')
text = text.replace('^', ' <^> ')
text = text.replace('@', ' <@> ')
text = text.replace('*', ' <*> ')
text = text.replace(';', ' <;> ')
text = re.sub('\$', " dollar ", text, flags=re.IGNORECASE)
text = text.replace('!', ' <!> ')
text = text.replace('|', ' <|> ')
text = text.replace('∥', ' <PARALLEL_MARK> ')
text = text.replace('?', ' <?> ')
text = text.replace('~', ' <~> ')
text = text.replace('[', ' <[> ')
text = text.replace(']', ' <]> ')
text = text.replace('{', ' <{> ')
text = text.replace('}', ' <}> ')
text = text.replace('(', ' <(> ')
text = text.replace(')', ' <)> ')
text = text.replace('--', ' <--> ')
text = text.replace('-', ' <-> ')
# text = text.replace("\", ' <BLACKSLASH_MARK> ')
text = text.replace("/", ' </> ')
# text = text.replace('[rm]', ' <REMOVED_PRICE> ')
# text = text.replace('\n', ' <NEW_LINE> ')
text = text.replace(':', ' <:> ')
text = text.replace('#', ' <#> ')
text = text.replace('gb', ' gb ')
text = text.replace('tb', ' tb ')
text = text.replace('karat', ' carat ')
text = text.replace('14k', ' 14carat ')
text = text.replace('14kt', ' 14carat ')
text = text.replace('18k', ' 18carat ')
text = text.replace('10k', ' 10carat ')
text = text.replace('nmd', ' nmds ')
text = text.replace('oz', ' oz ')
words = text.split()
words = ' '.join(words)
return words
def name_preprocess(text):
# Replace punctuation with tokens so we can use them in our model
try:
text = unidecode.unidecode(text)
text = str(text).lower()
except:
text = "missing"
text = text.replace('❌', ' <HEAVY_CROSS_')
text = text.replace('⭕', ' <HEAVY_LARGE_CIRCLE> ')
text = text.replace('⏳', ' <Hourglass_With_Flowing_Sand> ')
text = text.replace('♨', ' <HOT_SPRINGS> ')
text = text.replace('✌️️', ' <VICTORY_HAND> ')
text = text.replace('⛅', ' <SUN_BEHIND_CLOUD> ')
text = text.replace('♌', ' <LEO_MARK> ')
text = text.replace('☠', ' <SKULL_CROSSBONES> ')
text = text.replace('⬇', ' <DOWNWARDS_BLACK_ARROW> ')
text = text.replace('♠️️', ' <BLACK_SPADE> ')
text = text.replace('♤', ' <WHITE_SPADE> ')
text = text.replace('⚫️', ' <MEDIUM_BLACK_CIRCLE> ')
text = text.replace('⁉️', ' <EXCLAMATION_QUESTION_MARK> ')
text = text.replace('⛄', ' <SNOW_MAN_NO_SNOW> ')
text = text.replace('⚁', ' <DIE_FACE_EMOJI> ')
text = text.replace('✈️', ' <Airplane_Emoji> ')
text = text.replace('♢', ' <WHITE_DIAMON> ')
text = text.replace('➰', ' <Curly_Loop> ')
text = text.replace('➕', ' <HEAVY_PLUS_SIGN_EMOJI> ')
text = text.replace('✂', ' <Black_Scissors_EMOJI> ')
text = text.replace('❄️', ' <SNOWFLAKE_EMOJI> ')
text = text.replace('☒', ' <BALLOT_BOX> ')
text = text.replace('☘️', ' <SHAMROCK_EMOJI> ')
text = text.replace('⚠', ' <WARNING_SIGN_EMOJI> ')
text = text.replace('⚜', ' <Fleur_De_Lis_EMOJI> ')
text = text.replace('☮', ' <PEACE_SYMBOL> ')
text = text.replace('☄', ' <COMET_EMOJI> ')
text = text.replace('❣', ' <HEAVY_HEART_EXCLAMATION_Mark> ')
text = text.replace('❥', ' <ROTATE_HEAVY_BLACK_HEART_BULLET> ')
text = text.replace('✉️', ' <ENVELOPE_EMOJI> ')
text = text.replace('✖︎', ' <HEAVY_BLACK_CROSS> ')
text = text.replace('‼️', ' <HEAVY_EXCLAMATION> ')
text = text.replace('✮', ' <HEAVY_OUTLINED_BLACK_STAR> ')
text = text.replace('★', ' <HEAVY_OUTLINED_WHITE_STAR> ')
text = text.replace('⛔', ' <NO_ENTRY_EMOJI> ')
text = re.sub('⚡️', ' <HEAVY_VOLTAGE_SIGN_EMOJI> ', text, flags=re.IGNORECASE)
text = re.sub('⚡', ' <HEAVY_VOLTAGE_SIGN_EMOJI> ', text, flags=re.IGNORECASE)
text = text.replace('❤️', ' <HEAVY_HEART_MARK> ')
text = text.replace('☕️', ' <HOT_BEVERAGE_EMOJI> ')
text = text.replace('❗️', ' <HEAVY_EXCLAMATION_MARK> ')
text = text.replace('✔', ' <HEAVY_CHECK_MARK> ')
text = re.sub('⭐️', ' <WHITE_MEDIUM_STAR_MARK> ', text, flags=re.IGNORECASE)
text = re.sub('⭐', ' <WHITE_MEDIUM_STAR_MARK> ', text, flags=re.IGNORECASE)
text = text.replace('❤⭐', ' <HEART_WHITE_MEDIUM_STAR_MARK> ')
text = text.replace('❤', ' <HEAVY_HEART_MARK> ')
text = text.replace('▪️', ' <BLACK_SMALL_SQUARE> ')
text = text.replace('✅', ' <WHITE_HEAVY_CHECK_MARK> ')
text = text.replace('❎', ' <Negative_Squared_Cross_Mark> ')
text = text.replace('•', ' <BULLET_MARK> ')
text = text.replace('●', ' <HEAVY_BULLET_MARK> ')
text = text.replace('©', ' <COPY_RIGHT_SIGN> ')
text = text.replace('®', ' <REGISTERED_SIGN_MARK> ')
text = text.replace('♡', ' <HEART_SYMBOL> ')
text = text.replace('☆', ' <WHITE_STAR_SYMBOL> ')
text = text.replace('★', ' <BLACK_STAR_SYMBOL> ')
text = text.replace('✨', ' <SPARKLES_EMOJI ')
text = text.replace('☺️', ' <SMILING_FACE_EMOJI> ')
text = text.replace('《', ' <DOUBLE_LEFT_BRACKET_QUOTES> ')
text = text.replace('》', ' <DOUBLE_RIGHT_BRACKET_QUOTES> ')
text = text.replace('〰', ' <WAVY_DASH_EMOJI> ')
text = text.replace('➡', ' <BLACK_RIGHTWARDS_ARROW> ')
text = text.replace('✴️', ' <EIGHT_POINTED_STAR> ')
# text = re.sub('\&', " and ", text, flags=re.IGNORECASE)
# text = re.sub('\%', " percent ", text, flags=re.IGNORECASE)
text = text.replace('.', ' <PERIOD> ')
text = text.replace(',', ' <COMMA> ')
text = text.replace(',', ' <HEAVY_COMMA> ')
text = text.replace('"', ' <QUOTATION_MARK> ')
text = text.replace("”", ' <RIGHT_DOUBLE_QUOTATION_MARK> ')
text = text.replace("''", ' <DOUBLE_QUOTATION_MARK> ')
text = text.replace('=', ' <EQUAL_SIGN_MARK> ')
text = text.replace('+', ' <PLUSL_SIGN> ')
text = text.replace('^^', ' <_DOUBLE_CARET_MARK> ')
text = text.replace('^', ' <CARET_MARK> ')
text = text.replace('@', ' <AT_SIGN> ')
text = text.replace('*', ' <STAR_MARK> ')
text = text.replace(';', ' <SEMICOLON> ')
# text = re.sub('\$', " dollar ", text, flags=re.IGNORECASE)
text = text.replace('!', ' <EXCLAMATION_MARK> ')
text = text.replace('|', ' <VERTICAL_BAR_MARK> ')
text = text.replace('∥', ' <PARALLEL_MARK> ')
text = text.replace('?', ' <QUESTION_MARK> ')
text = text.replace('~', ' <TILDE_MARK> ')
text = text.replace('[', ' <LEFT_SQUARE_BRACKET> ')
text = text.replace(']', ' <RIGHT_SQUARE_BRACKET> ')
text = text.replace('{', ' <LEFT_CURLY_BRACKET> ')
text = text.replace('}', ' <RIGHT_CURLY_BRACKET> ')
text = text.replace('(', ' <LEFT_PAREN> ')
text = text.replace(')', ' <RIGHT_PAREN> ')
text = text.replace('--', ' <HYPHENS> ')
text = text.replace('-', ' <HYPHENS> ')
# text = text.replace("\", ' <BLACKSLASH_MARK> ')
text = text.replace("/", ' <SLASH_MARK> ')
text = text.replace('?', ' <QUESTION_MARK> ')
# text = text.replace('[rm]', ' <REMOVED_PRICE> ')
# text = text.replace('\n', ' <NEW_LINE> ')
text = text.replace(':', ' <COLON> ')
text = text.replace('#', ' <HASH> ')
text = text.replace('gb', ' gb ')
text = text.replace('tb', ' tb ')
text = text.replace('karat', ' carat ')
text = text.replace('14k', ' 14carat ')
text = text.replace('14kt', ' 14carat ')
text = text.replace('18k', ' 18carat ')
text = text.replace('10k', ' 10carat ')
text = text.replace('nmd', ' nmds ')
text = text.replace('oz', ' oz ')
text = re.sub("\'ve", " have ", text, flags=re.IGNORECASE)
text = re.sub("n't", " not ", text, flags=re.IGNORECASE)
text = re.sub("i'm", "i am", text, flags=re.IGNORECASE)
text = re.sub("\'re", " are ", text, flags=re.IGNORECASE)
text = re.sub("\'d", " would ", text, flags=re.IGNORECASE)
text = re.sub("\'ll", " will ", text, flags=re.IGNORECASE)
text = re.sub("\'s", "", text, flags=re.IGNORECASE)
words = text.split()
words = ' '.join(words)
return words
def simple_preprocess(text):
"""Just making sure we have text"""
try:
text = unidecode.unidecode(text)
text = str(text).lower()
except:
text = "missing"
return text
def process_cond_id(z):
try:
if z > 5:
return 1
elif z < 1:
return 1
else:
return z
except:
return 1
def process_shipping(z):
try:
if z not in [0, 1]:
return 0
else:
return z
except:
return 0
def simulate_test(test):
if test.shape[0] < 800000:
indices = np.random.choice(test.index.values, 2800000)
test_ = pd.concat([test, test.iloc[indices]], axis=0)
return test_.copy()
else:
return test
def normalize_text(text):
return u" ".join(
[x for x in [y for y in non_alphanums.sub(' ', text).lower().strip().split(" ")]])
def cpuStats(disp=""):
""" @author: RDizzl3 @address: https://www.kaggle.com/rdizzl3"""
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0] / 2. ** 30
print("%s MEMORY USAGE for PID %10d : %.3f" % (disp, pid, memoryUse))
def handle_missing_inplace(dataset):
dataset['name'].fillna(value='missing', inplace=True)
dataset['category_name'].fillna(value='missing', inplace=True)
dataset['brand_name'].fillna(value='missing', inplace=True)
dataset['item_description'].fillna(value='No description yet', inplace=True)
def mix_cat_name(row):
"""
Mixes words in name with categories in the category feature
categories are expected to be in the first field of row and separated by /
name is expected to be in the second field of row
"""
return " ".join([category + "_" + word
for category in row[0].lower().split("/") for word in row[1].lower().split()])
def mix_cat_name_cond(row):
"""
Mixes words in name with categories in the category feature and with the item condition
categories are expected to be in the first field of row and separated by /
name is expected to be in the second field of row
item condition is expected to be in the third field
"""
return " ".join([category + "_" + word + " " + category + "_" + word + "_" + str(row[2])
for category in row[0].lower().split("/") for word in row[1].lower().split()])
def mix_cat_cond(row):
"""
Mixes categories in the category feature with the item condition
categories are expected to be in the first field of row and separated by /
item condition is expected to be in the second field
"""
return " ".join([category + "_" + str(row[2])
for category in row[0].lower().split("/")])
def add_price_statistics_on_train(trn, target, feature=None):
"""
Prices are aggregated by brand to compute statistics
These stats are then merged back into train and test datasets
@author: Kueipo @address: https://www.kaggle.com/kueipo
@param: trn: training data taht is expected to contain a 'price' feature
@param: sub: test data
"""
train = trn[[feature]].copy()
train["price"] = target
train = train[train[feature].notnull()]
stats = train.groupby(feature)['price'].agg({'median', "mean", 'std', 'min', 'max'}).reset_index()
stats["std"].fillna(0, inplace=True)
stats.columns = [feature, feature + "_median", feature + "_mean",
feature + "_std", feature + "_min", feature + "_max"]
trn = pd.merge(trn, stats, how='left', on=feature)
# Now set unknown values to the overall median, std, min or max
trn.loc[trn[feature + "_median"].isnull(), feature + "_median"] = np.median(target)
trn.loc[trn[feature + "_mean"].isnull(), feature + "_mean"] = np.mean(target)
trn.loc[trn[feature + "_std"].isnull(), feature + "_std"] = np.std(target)
trn.loc[trn[feature + "_min"].isnull(), feature + "_min"] = np.min(target)
trn.loc[trn[feature + "_max"].isnull(), feature + "_max"] = np.max(target)
del train
gc.collect()
return trn, stats
def add_price_statistics_on_test(sub, stats, target, feature=None):
"""
Prices are aggregated by brand to compute statistics
These stats are then merged back into train and test datasets
@author: Kueipo @address: https://www.kaggle.com/kueipo
@param: trn: training data taht is expected to contain a 'price' feature
@param: sub: test data
"""
sub = pd.merge(sub, stats, how='left', on=feature)
# Now set unknown values to the overall median, std, min or max
sub.loc[sub[feature + "_median"].isnull(), feature + "_median"] = np.median(target)
sub.loc[sub[feature + "_mean"].isnull(), feature + "_mean"] = np.mean(target)
sub.loc[sub[feature + "_std"].isnull(), feature + "_std"] = np.std(target)
sub.loc[sub[feature + "_min"].isnull(), feature + "_min"] = np.min(target)
sub.loc[sub[feature + "_max"].isnull(), feature + "_max"] = np.max(target)
return sub
def string_len(x):
""" Simple function that returns the len of a string """
try:
return len(str(x))
except:
return 0
def word_count(x, sep=None):
""" Simple function that returns the number of words in a string """
try:
return len(str(x).split(sep))
except:
return 0
def add_character_and_word_lengths(data, app_series_man_):
"""
@author: Olivier @address: https://www.kaggle.com/ogrellier
Function used to create additional features.
All of this is parallelized using process pooling
"""
# Apply description length in parallel
data["desc_len"] = app_series_man_.apply(data_=data["item_description"].fillna("missing"), func_=string_len)
data["desc_word_len"] = app_series_man_.apply(data_=data["item_description"].fillna("missing"),
func_=functools.partial(word_count, sep=None))
data["nb_categories"] = app_series_man_.apply(data_=data["category_name"].fillna("missing"),
func_=functools.partial(word_count, sep="/"))
data["name_len"] = app_series_man_.apply(data_=data["name"].fillna("missing"), func_=string_len)
data["name_word_len"] = app_series_man_.apply(data_=data["name"].fillna("missing"),
func_=functools.partial(word_count, sep=None))
# Add ratios
# data["ratio_1"] = data["name_len"] / (data["name_word_len"] + 1)
# data["ratio_2"] = data["desc_len"] / (data["desc_word_len"] + 1)
# data["ratio_3"] = data["name_len"] / (data["desc_len"] + 1)
# data["ratio_4"] = data["name_word_len"] / (data["desc_word_len"] + 1)
def add_combination_category_name(data, app_man_):
data["mix_cat_name"] = app_man_.apply(df=data[["category_name", "name"]].fillna("missing"),
func=mix_cat_name,
axis=1,
raw=True)
def add_categories_and_mix_with_condition(df):
for i in range(3):
# Create new features
df["category_name_" + str(i)] = df["category_name"].str.split("/").str[i].fillna("no_cat")
df["cat_cond_" + str(i)] = df["category_name_" + str(i)] + '|' + df["item_condition_id"].apply(lambda x: str(x))
def preprocess_text_features(df, app_series_man_):
"""
Utility function to apply text pre-processing by Kueipo to name, brand and description
but in parallel
"""
df["item_description"] = app_series_man_.apply(data_=df["item_description"].fillna("missing"), func_=preprocess)
df["name"] = app_series_man_.apply(data_=df["name"].fillna("missing"), func_=preprocess)
df["brand_name"] = app_series_man_.apply(data_=df["brand_name"].fillna("missing"), func_=simple_preprocess)
df["category_name"] = app_series_man_.apply(data_=df["category_name"].fillna("missing"), func_=simple_preprocess)
df["shipping"] = app_series_man_.apply(data_=df["shipping"].fillna(-1), func_=process_shipping)
df["item_condition_id"] = app_series_man_.apply(data_=df["item_condition_id"].fillna(-1), func_=process_cond_id)
def add_d(text):
"""
Simple text modification used on description to ensure
words in description are not hashed in the same space as name
"""
return " ".join(["d_" + w for w in TweetTokenizer().tokenize(text)])
def add_b(text):
"""
Simple text modification used brand to ensure
brands are not hashed in the same space as name and description
"""
return " ".join(["b_" + w for w in text.split()])
# def get_hashing_features(train, test, Hash_binary, start_time):
def get_hashing_features(df, hash_binary, start_time, app_series_man_, app_man_, hash_man_):
# df = pd.concat([train, test])
dim = 24
cv_name = HashingVectorizer(
n_features=2 ** dim,
ngram_range=(1, 2),
norm=None,
alternate_sign=False,
tokenizer=TweetTokenizer().tokenize,
binary=hash_binary
)
X_name = hash_man_.apply(data_=df["name"], hashing_vectorizer_=cv_name)
cv_cat_name = HashingVectorizer(
n_features=2 ** dim,
ngram_range=(1, 2),
norm=None,
alternate_sign=False,
tokenizer=None, # TweetTokenizer().tokenize,
binary=hash_binary
)
add_combination_category_name(df, app_man_)
X_name += hash_man_.apply(data_=df["mix_cat_name"], hashing_vectorizer_=cv_cat_name)
desc_hash = HashingVectorizer(n_features=2 ** dim,
norm=None,
alternate_sign=False,
tokenizer=None, # TweetTokenizer().tokenize,
binary=hash_binary
# stop_words='english'
)
df["get_desc_hash_out"] = app_series_man_.apply(data_=df["item_description"].fillna("missing"), func_=add_d)
X_name += hash_man_.apply(data_=df["get_desc_hash_out"], hashing_vectorizer_=desc_hash)
df.drop("get_desc_hash_out", axis=1, inplace=True)
gc.collect()
df["get_brand_hash_out"] = app_series_man_.apply(data_=df["brand_name"].fillna("missing"), func_=add_b)
brd_hash = HashingVectorizer(n_features=2 ** dim,
norm=None,
alternate_sign=False,
binary=hash_binary
)
X_name += hash_man_.apply(data_=df["get_brand_hash_out"], hashing_vectorizer_=brd_hash)
df.drop("get_brand_hash_out", axis=1, inplace=True)
gc.collect()
print('[{}] Finished hashing dataset'.format(time.time() - start_time))
return X_name
def get_tfidf_features_for_train(train, hash_man_):
# Create wordbatch tfidf
wb = HashingVectorizer(
n_features=2 ** 20,
ngram_range=(1, 1),
norm=None,
alternate_sign=False,
tokenizer=TweetTokenizer().tokenize,
binary=Hash_binary
)
X_name = hash_man_.apply(data_=train["name"], hashing_vectorizer_=wb)
# print("Wordbatch hashing done")
# Remove features with document frequency <=1
# This is not a stateless step
# If clipping is an np.array it will take a massive amount of memory
# clipping = np.array(np.clip(X_name.getnnz(axis=0) - 1, 0, 1), dtype=bool)
clipping = np.array((X_name.sum(axis=0) >= 1))[0]
# cpuStats()
print("Clipping computed")
X_name = X_name[:, clipping]
gc.collect()
# cpuStats()
print("X_name reduced")
# return matrix and wordbatch for future use
return X_name, wb, clipping
def get_tfidf_features_for_test(test, wb, clipping, hash_man_):
X_name = hash_man_.apply(data_=test["name"], hashing_vectorizer_=wb)
X_name = X_name[:, clipping]
return X_name
class OHEManager(object):
def __init__(self, feature_name=None, min_df=5):
self.name = feature_name
self.indexer = None
self.ohe = OneHotEncoder(handle_unknown='ignore')
self.indices = None
self.cols = None
self.min_df = min_df
def add_factorized_feature_on_train(self, trn):
trn["fact_" + self.name], self.indexer = pd.factorize(trn[self.name])
def add_factorized_feature_on_test(self, sub):
if self.indexer is None:
raise ValueError("indexer has not been fitted yet")
sub["fact_" + self.name] = self.indexer.get_indexer(sub[self.name])
def get_feature_for_sgd_train(self, trn):
dummies = self.ohe.fit_transform(trn[["fact_" + self.name]].replace(-1, 999))
self.indices = np.arange(dummies.shape[1])
self.cols = np.array((dummies.sum(axis=0) >= self.min_df))[0]
return dummies[:, self.indices[self.cols]]
def get_feature_for_sgd_test(self, sub):
dummies = self.ohe.transform(sub[["fact_" + self.name]].replace(-1, 999))
return dummies[:, self.indices[self.cols]]
def get_numerical_features_for_sgd(df):
# Factors cannot be used by linear models
numericals = [
"fact_category_name_0", "fact_category_name_1", "fact_category_name_2",
"fact_cat_cond_0", "fact_cat_cond_1", "fact_cat_cond_2",
"fact_brand_name",
"item_condition_id",
"shipping",
"desc_len", "desc_word_len", "name_len", "name_word_len", "nb_categories",
"brand_name_median", "brand_name_std", "brand_name_min", "brand_name_max", "distance",
"category_name_median", "category_name_std", "category_name_min", "category_name_max",
"ratio_1", "ratio_2", "ratio_3", "ratio_4",
]
return [f_ for f_ in numericals if f_ in df]
def get_numerical_features_for_lgb(df):
numericals = [
"fact_category_name_0", "fact_category_name_1", "fact_category_name_2",
"fact_cat_cond_0", "fact_cat_cond_1", "fact_cat_cond_2",
"fact_brand_name",
"item_condition_id", "shipping",
"desc_len", "desc_word_len", "name_len", "name_word_len", "nb_categories",
"brand_name_median", "brand_name_std", "brand_name_min", "brand_name_max", "distance",
"category_name_median", "category_name_std", "category_name_min", "category_name_max",
"sgd_liblinear", "sgd_ridge", "liblinear_ridge",
"fact_name_0", "fact_name_1", "fact_name_2", "fact_name_3", "fact_name_4", "fact_name_5",
"ratio_1", "ratio_2", "ratio_3", "ratio_4",
]
return [f_ for f_ in numericals if f_ in df]
def get_numerical_features(df, numericals=None,
gaussian=True, rank=False,
minmax_skl=None):
num_feats = [f_ for f_ in numericals if f_ in df]
# print(num_feats)
if gaussian:
if rank:
num_df = df[num_feats].copy()
for f_ in num_feats:
num_df[f_] = (num_df[f_].rank() - num_df.shape[0] * .5) / (num_df.shape[0] * .5)
num_df[num_df >= 1.0] = 0.99999
num_df[num_df <= -1.0] = -0.99999
else:
if minmax_skl is None:
minmax_skl = MinMaxScaler(feature_range=(-1 + 1e-6, 1 - 1e-6)).fit(df[num_feats])
num_df = pd.DataFrame(data=minmax_skl.transform(df[num_feats]),
columns=num_feats)
# minmax_skl can be used on data with min max different
# than the data it used to fit on, so we need to clip it
num_df = np.clip(a=num_df, a_min=-1 + 1e-6, a_max=1 - 1e-6)
# Use Inverse of error function to shape like gaussian
for f_ in num_feats:
num_df[f_] = erfinv(num_df[f_].values)
the_mean = num_df[f_].mean()
num_df[f_] -= the_mean
# print(f_, the_mean)
return csr_matrix(num_df[num_feats].values), minmax_skl
else:
return csr_matrix(df[num_feats].values)
PROD = "production"
PROD_OOF = "production_with_oof"
VALID_TRN = "train_only_validation"
FAST_VALID = "fast_validation_set"
STAGE2_OOF = "stage2_with_OOF_validation"
STAGE2_PROD = "Complete_Stage2_rehearsal"
class DataManager(object):
def __init__(self, mode, ratio):
self.mode = mode
self.idx = None
self.ratio = ratio
def get_train_data(self):
if self.mode in [PROD, PROD_OOF]:
train = pd.read_table('../input/train.tsv', engine='c').rename(columns={"train_id": "id"})
train.ix[train.brand_name == 'PINK', 'brand_name'] = 'PINKBRAND'
elif self.mode in [STAGE2_OOF, STAGE2_PROD]:
train = pd.read_table('../input/train.tsv', engine='c').head(500000).rename(columns={"train_id": "id"})
train.ix[train.brand_name == 'PINK', 'brand_name'] = 'PINKBRAND'
elif self.mode == FAST_VALID:
np.random.seed(0)
data = pd.read_table('../input/train.tsv', engine='c')
if self.idx is None:
self.idx = np.arange(data.shape[0])
np.random.shuffle(self.idx)
data = data.iloc[self.idx]
train = data.head(int(data.shape[0] * (1 - self.ratio) / 10)).rename(columns={"train_id": "id"})
# test = data.tail(int(data.shape[0] *self. ratio / 10)).rename(columns={"train_id": "id"})
del data
gc.collect()
else:
# Use train for train and test
# Used to check the whole process fully works and scores are fine
# in particular makes sure train and test matrices in all steps are in sync
np.random.seed(0)
data = pd.read_table('../input/train.tsv', engine='c')
if self.idx is None:
self.idx = np.arange(data.shape[0])
np.random.shuffle(self.idx)
data = data.iloc[self.idx]
train = data.head(int(data.shape[0] * (1 - self.ratio))).rename(columns={"train_id": "id"})
del data
gc.collect()
return train
def get_test_data(self):
if self.mode in [PROD, PROD_OOF]:
test = pd.read_table('../input/test.tsv', engine='c').rename(columns={"test_id": "id"})
test.ix[test.brand_name == 'PINK', 'brand_name'] = 'PINKBRAND'
elif self.mode in [STAGE2_OOF, STAGE2_PROD]:
test = pd.read_table('../input/test.tsv', engine='c').rename(columns={"test_id": "id"})
test.ix[test.brand_name == 'PINK', 'brand_name'] = 'PINKBRAND'
test = simulate_test(test)
elif self.mode == FAST_VALID:
np.random.seed(0)
data = pd.read_table('../input/train.tsv', engine='c')
if self.idx is None:
self.idx = np.arange(data.shape[0])
np.random.shuffle(self.idx)
data = data.iloc[self.idx]
test = data.tail(int(data.shape[0] * self.ratio / 10)).rename(columns={"train_id": "id"})
del data
gc.collect()