-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathlazytransform.py
4436 lines (4204 loc) · 229 KB
/
lazytransform.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
#!/usr/bin/env python
# coding: utf-8
############################################################################################
# Copyright [2022] [Ram Seshadri]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################################
##### LazyTransformer is a simple transformer pipeline for all kinds of ML problems. ######
###########################################################################################
# What does this pipeline do? Here's the major steps:
# 1. Takes categorical variables and encodes them using my special label encoder which can
# handle NaNs and future categories
# 1. Takes integer and float variables and imputes them using a simple imputer (with a default)
# 1. Takes NLP and time series (as string) variables and vectorizes them using TFiDF
# 1. Takes pandas date-time (actual date-time) variables and extracts more features from them
# 1. Completely Normalizes all of the above using AbsMaxScaler which preserves the
# relationship of label encoded vars
# 1. Optionally adds any model to pipeline so the entire pipeline can be fed to a
# cross validation scheme (just set model=any_sklearn_model() when defining the pipeline)
# The initial results from this pipeline in real world data sets is promising indeed.
############################################################################################
####### This Transformer is inspired by Kevin Markham's class on Scikit-Learn pipelines. ###
####### You can sign up for his Data School class here: https://www.dataschool.io/ ######
############################################################################################
import numpy as np
import pandas as pd
np.random.seed(99)
import random
random.seed(42)
################################################################################
import warnings
warnings.filterwarnings("ignore")
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
################################################################################
from sklearn.impute import SimpleImputer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import LabelEncoder, LabelBinarizer
import pdb
from collections import defaultdict, Counter
### These imports give fit_transform method for free ###
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import column_or_1d
from sklearn.base import RegressorMixin, ClassifierMixin
from sklearn.preprocessing import FunctionTransformer
from sklearn.preprocessing import MaxAbsScaler, StandardScaler, MinMaxScaler
from sklearn.preprocessing import RobustScaler
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, HistGradientBoostingClassifier
from sklearn.tree import ExtraTreeRegressor, ExtraTreeClassifier
from sklearn.decomposition import TruncatedSVD
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.metrics import mean_squared_log_error, mean_squared_error,balanced_accuracy_score
import gc
############## These imports are to make trouble shooting easier #####
import time
import copy
import os
import pickle
import scipy
import warnings
warnings.filterwarnings("ignore")
##########################################################
from category_encoders import HashingEncoder, PolynomialEncoder, BackwardDifferenceEncoder
from category_encoders.sum_coding import SumEncoder
from category_encoders.leave_one_out import LeaveOneOutEncoder
from category_encoders import HelmertEncoder, OrdinalEncoder, CountEncoder, BaseNEncoder
from category_encoders import TargetEncoder, CatBoostEncoder, WOEEncoder, JamesSteinEncoder
from category_encoders.glmm import GLMMEncoder
from sklearn.preprocessing import LabelEncoder
from category_encoders.wrapper import PolynomialWrapper
from category_encoders import OneHotEncoder
from sklearn.pipeline import make_pipeline, Pipeline
#from sklearn.preprocessing import OneHotEncoder
from tqdm import tqdm
from sklearn.model_selection import TimeSeriesSplit
import numpy as np
import pandas as pd
################################################################################
import warnings
warnings.filterwarnings("ignore")
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
################################################################################
import math
from collections import Counter
from sklearn.linear_model import Ridge, Lasso, RidgeCV
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, AdaBoostClassifier
from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.multiclass import OneVsRestClassifier, OneVsOneClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold, StratifiedKFold
import time
from sklearn.cluster import KMeans
from matplotlib.pyplot import figure
from sklearn.metrics.cluster import normalized_mutual_info_score
from sklearn.metrics import balanced_accuracy_score
from sklearn.ensemble import VotingRegressor, VotingClassifier
import copy
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
from sklearn.base import ClassifierMixin, RegressorMixin
import lightgbm
from lightgbm import LGBMClassifier, LGBMRegressor
from xgboost import XGBRegressor, XGBClassifier
from sklearn.multioutput import MultiOutputRegressor, MultiOutputClassifier
from sklearn.multioutput import ClassifierChain, RegressorChain
import scipy as sp
import pdb
from sklearn.semi_supervised import LabelPropagation
from sklearn.ensemble import BaggingClassifier, BaggingRegressor
from sklearn.svm import SVR, LinearSVR
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer, MissingIndicator
#from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder
from sklearn.compose import ColumnTransformer
from scipy.stats import uniform as sp_randFloat
from scipy.stats import randint as sp_randInt
from sklearn.metrics import mean_absolute_error, mean_squared_error
from itertools import cycle
import matplotlib.pyplot as plt
#########################################################
class My_LabelEncoder(BaseEstimator, TransformerMixin):
"""
################################################################################################
###### The My_LabelEncoder class works just like sklearn's Label Encoder but better! #######
##### It label encodes any object or category dtype in your dataset. It also handles NaN's.####
## The beauty of this function is that it takes care of encoding unknown (future) values. #####
##################### This is the BEST working version - don't mess with it!! ##################
################################################################################################
Usage:
le = My_LabelEncoder()
le.fit_transform(train[column]) ## this will give your transformed values as an array
le.transform(test[column]) ### this will give your transformed values as an array
Usage in Column Transformers and Pipelines:
No. It cannot be used in pipelines since it need to produce two columns for the next stage in pipeline.
See my other module called My_LabelEncoder_Pipe() to see how it can be used in Pipelines.
"""
def __init__(self):
self.transformer = defaultdict(str)
self.inverse_transformer = defaultdict(str)
self.max_val = 0
def fit(self,testx, y=None):
### Do not change this since Rare class combiner requires this test ##
if isinstance(testx, tuple):
y = testx[1]
testx = testx[0]
## testx must still be a pd.Series for this encoder to work!
if isinstance(testx, pd.Series):
pass
elif isinstance(testx, np.ndarray):
testx = pd.Series(testx)
else:
#### There is no way to transform dataframes since you will get a nested renamer error if you try ###
### But if it is a one-dimensional dataframe, convert it into a Series
#### Do not change this since I have tested it and it works.
if testx.shape[1] == 1:
testx = pd.Series(testx.values.ravel(),name=testx.columns[0])
else:
#### Since it is multi-dimensional, So in this case, just return the object as is
return self
ins = np.unique(testx.factorize()[1]).tolist()
outs = np.unique(testx.factorize()[0]).tolist()
#ins = testx.value_counts(dropna=False).index
if -1 in outs:
# it already has nan if -1 is in outs. No need to add it.
if not np.nan in ins:
ins.insert(0,np.nan)
self.transformer = dict(zip(ins,outs))
self.inverse_transformer = dict(zip(outs,ins))
return self
def transform(self, testx, y=None):
### Do not change this since Rare class combiner requires this test ##
if isinstance(testx, tuple):
y = testx[1]
testx = testx[0]
## testx must still be a pd.Series for this encoder to work!
if isinstance(testx, pd.Series):
pass
elif isinstance(testx, np.ndarray):
testx = pd.Series(testx)
else:
#### There is no way to transform dataframes since you will get a nested renamer error if you try ###
### But if it is a one-dimensional dataframe, convert it into a Series
#### Do not change this since I have tested it and it works.
if testx.shape[1] == 1:
testx = pd.Series(testx.values.ravel(),name=testx.columns[0])
else:
#### Since it is multi-dimensional, So in this case, just return the data as is
#### Do not change this since I have tested it and it works.
return testx
### now convert the input to transformer dictionary values
new_ins = np.unique(testx.factorize()[1]).tolist()
missing = [x for x in new_ins if x not in self.transformer.keys()]
if len(missing) > 0:
for each_missing in missing:
self.transformer[each_missing] = int(self.max_val + 1)
self.inverse_transformer[int(self.max_val+1)] = each_missing
self.max_val = int(self.max_val+1)
else:
self.max_val = np.max(list(self.transformer.values()))
### To handle category dtype you must do the next step #####
#### Do not change this since I have tested it and it works.
testk = testx.map(self.transformer)
if testx.dtype not in [np.int16, np.int32, np.int64, float, bool, object]:
if testx.isnull().sum().sum() > 0:
fillval = self.transformer[np.nan]
testk = testx.cat.add_categories([fillval])
testk = testk.fillna(fillval)
testk = testx.map(self.transformer).values.astype(int)
return testk
else:
testk = testx.map(self.transformer).values.astype(int)
return testk
else:
outs = testx.map(self.transformer).values.astype(int)
return outs
def inverse_transform(self, testx, y=None):
### now convert the input to transformer dictionary values
if isinstance(testx, pd.Series):
outs = testx.map(self.inverse_transformer).values
elif isinstance(testx, np.ndarray):
outs = pd.Series(testx).map(self.inverse_transformer).values
else:
outs = testx[:]
return outs
#################################################################################
class My_LabelEncoder_Pipe(BaseEstimator, TransformerMixin):
"""
################################################################################################
###### The My_LabelEncoder_Pipe class works just like sklearn's Label Encoder but better! #####
##### It label encodes any cat var in your dataset. But it can also be used in Pipelines! #####
## The beauty of this function is that it takes care of NaN's and unknown (future) values.#####
##### Since it produces an unused second column it can be used in sklearn's Pipelines. #####
##### But for that you need to add a drop_second_col() function to this My_LabelEncoder_Pipe ##
##### and then feed the whole pipeline to a Column_Transformer function. It is very easy. #####
##################### This is the BEST working version - don't mess with it!! ##################
################################################################################################
Usage in pipelines:
le = My_LabelEncoder_Pipe()
le.fit_transform(train[column]) ## this will give you two columns - beware!
le.transform(test[column]) ### this will give you two columns - beware!
Usage in Column Transformers:
def drop_second_col(Xt):
### This deletes the 2nd column. Hence col number=1 and axis=1 ###
return np.delete(Xt, 1, 1)
drop_second_col_func = FunctionTransformer(drop_second_col)
le_one = make_pipeline(le, drop_second_col_func)
ct = make_column_transformer(
(le_one, catvars[0]),
(le_one, catvars[1]),
(imp, numvars),
remainder=remainder)
"""
def __init__(self):
self.transformer = defaultdict(str)
self.inverse_transformer = defaultdict(str)
self.max_val = 0
def fit(self,testx, y=None):
### Do not change this since Rare class combiner requires this test ##
if isinstance(testx, tuple):
y = testx[1]
testx = testx[0]
if isinstance(testx, pd.Series):
pass
elif isinstance(testx, np.ndarray):
testx = pd.Series(testx)
else:
#### There is no way to transform dataframes since you will get a nested renamer error if you try ###
### But if it is a one-dimensional dataframe, convert it into a Series
if testx.shape[1] == 1:
testx = pd.Series(testx.values.ravel(),name=testx.columns[0])
else:
#### Since it is multi-dimensional, So in this case, just return the data as is
return self
ins = np.unique(testx.factorize()[1]).tolist()
outs = np.unique(testx.factorize()[0]).tolist()
#ins = testx.value_counts(dropna=False).index
if -1 in outs:
# it already has nan if -1 is in outs. No need to add it.
if not np.nan in ins:
ins.insert(0,np.nan)
self.transformer = dict(zip(ins,outs))
self.inverse_transformer = dict(zip(outs,ins))
return self
def transform(self, testx, y=None):
### Do not change this since Rare class combiner requires this test ##
if isinstance(testx, tuple):
y = testx[1]
testx = testx[0]
## testx must still be a pd.Series for this encoder to work!
if isinstance(testx, pd.Series):
pass
elif isinstance(testx, np.ndarray):
testx = pd.Series(testx)
else:
#### There is no way to transform dataframes since you will get a nested renamer error if you try ###
### But if it is a one-dimensional dataframe, convert it into a Series
#### Do not change this since I have tested it and it works.
if testx.shape[1] == 1:
testx = pd.Series(testx.values.ravel(),name=testx.columns[0])
else:
#### Since it is multi-dimensional, So in this case, just return the data as is
#### Do not change this since I have tested it and it works.
return testx
### now convert the input to transformer dictionary values
new_ins = np.unique(testx.factorize()[1]).tolist()
missing = [x for x in new_ins if x not in self.transformer.keys()]
if len(missing) > 0:
for each_missing in missing:
self.transformer[each_missing] = int(self.max_val + 1)
self.inverse_transformer[int(self.max_val+1)] = each_missing
self.max_val = int(self.max_val+1)
else:
self.max_val = np.max(list(self.transformer.values()))
### To handle category dtype you must do the next step #####
#### Do not change this since I have tested it and it works.
testk = testx.map(self.transformer)
if testx.isnull().sum().sum() > 0:
try:
fillval = self.transformer[np.nan]
except:
fillval = -1
if testx.dtype not in [np.int16, np.int32, np.int64, float, bool, object]:
testk = testk.map(self.transformer).fillna(fillval).values.astype(int)
else:
testk = testk.fillna(fillval)
testk = testx.map(self.transformer).values.astype(int)
return np.c_[testk,np.zeros(shape=testk.shape)].astype(int)
else:
testk = testx.map(self.transformer).values.astype(int)
return np.c_[testk,np.zeros(shape=testk.shape)].astype(int)
def inverse_transform(self, testx, y=None):
### now convert the input to transformer dictionary values
if isinstance(testx, pd.Series):
outs = testx.map(self.inverse_transformer).values
elif isinstance(testx, np.ndarray):
outs = pd.Series(testx).map(self.inverse_transformer).values
else:
outs = testx[:]
return outs
#################################################################################
# ## First you need to classify variables into different types. Only then can you do the correct transformations.
def classify_vars_pandas(df, verbose=0):
"""
################################################################################################
Pandas select_dtypes makes classifying variables a breeze. You should check out the links here:
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.select_dtypes.html
################################################################################################
"""
### number of categories in a column below which it is considered a categorial var ##
category_limit = 30
nlp_threshold = 50
var_dict = defaultdict(list)
#### To select all numeric types, use np.number or 'number'
intvars = df.select_dtypes(include='integer').columns.tolist()
### Because of differences in pandas versions, floats don't get detected easily
### Hence I am forced to write clumsily like this. Don't change the next line!!
floatvars = df.select_dtypes(include='float16').columns.tolist() + df.select_dtypes(
include='float32').columns.tolist() + df.select_dtypes(include='float64').columns.tolist()
inf_cols = EDA_find_remove_columns_with_infinity(df)
numvars = left_subtract(floatvars, inf_cols)
var_dict['continuous_vars'] = floatvars
var_dict['int_vars'] = intvars
#### To select strings you must use the object dtype, but note that this will return all object dtype columns
stringvars = df.select_dtypes(include='object').columns.tolist()
discrete_vars = []
if len(stringvars) > 0:
copy_string_vars = copy.deepcopy(stringvars)
for each_string in copy_string_vars:
if len(df[each_string].unique()) > category_limit:
discrete_vars.append(each_string)
stringvars.remove(each_string)
var_dict['discrete_string_vars'] = discrete_vars
#### To select datetimes, use np.datetime64, 'datetime' or 'datetime64'
datevars = df.select_dtypes(include='datetime').columns.tolist()
var_dict['date_vars'] = datevars
#### To select timedeltas, use np.timedelta64, 'timedelta' or 'timedelta64'
deltavars = df.select_dtypes(include='timedelta').columns.tolist()
var_dict['time_deltas'] = deltavars
#### To select Pandas categorical dtypes, use 'category'
catvars = df.select_dtypes(include='category').columns.tolist()
if len(catvars) > 0:
copy_catvars = copy.deepcopy(catvars)
for each_cat in copy_catvars:
if len(df[each_cat].unique()) > category_limit:
discrete_vars.append(each_cat)
catvars.remove(each_cat)
var_dict['categorical_vars'] = catvars + stringvars
var_dict['discrete_string_vars'] = discrete_vars
#### To select Pandas datetimetz dtypes, use 'datetimetz' (new in 0.20.0) or 'datetime64[ns, tz]'
datezvars = df.select_dtypes(include='datetimetz').columns.tolist()
var_dict['date_zones'] = datezvars
#### check for nlp variables here ####
str_vars = var_dict['discrete_string_vars']
copy_vars = copy.deepcopy(str_vars)
nlp_vars = []
for each_str_var in copy_vars:
try:
mean_str_size = df[each_str_var].fillna('missing').map(len).max()
except:
print('Removing column %s since it is erroring probably due to mixed data types.' %each_str_var)
str_vars.remove(each_str_var)
continue
if mean_str_size >= nlp_threshold:
print(f" since {each_str_var}'s max string size {mean_str_size:.0f} >= {nlp_threshold}, re-classifying it as NLP variable")
nlp_vars.append(each_str_var)
str_vars.remove(each_str_var)
var_dict['nlp_vars'] = nlp_vars ### these are NLP text variables ##########
var_dict['discrete_string_vars'] = str_vars ### these are high cardinality string variables ##
if verbose:
print(f""" Returning dictionary for variable types with following keys:
continuous_vars = {len(floatvars)}, int_vars = {len(intvars)},
discrete_string_vars = {len(str_vars)}, nlp_vars = {len(nlp_vars)},
date_vars = {len(datevars)}, time_deltas = {len(deltavars)},
categorical_vars = {len(catvars)+len(stringvars)}, date_zones = {len(datezvars)}""")
return var_dict
##################################################################################################
def left_subtract(l1,l2):
"""This handy function subtracts one list from another. Probably my most popular function."""
lst = []
for i in l1:
if i not in l2:
lst.append(i)
return lst
############################################################################################
import copy
def convert_mixed_datatypes_to_string(df):
"""
#####################################################################################
Handy function for Feature Transformation: That's why it's included in LazyTransform
########### It converts all mixed data type columns into object columns ############
Inputs:
df : pandas dataframe
Outputs:
df: this is the transformed DataFrame with all mixed data types now as objects
#####################################################################################
"""
df = copy.deepcopy(df)
cols = df.columns.tolist()
copy_cols = copy.deepcopy(cols)
for col in copy_cols:
if len(df[col].apply(type).value_counts()) > 1:
print('Mixed data type detected in %s column. Converting it to object type...' %col)
try:
df[col] = df[col].map(lambda x: x if isinstance(x, str) else str(x)).values
if len(df[col].apply(type).value_counts()) > 1:
df.drop(col,axis=1,inplace=True)
print(' %s still has mixed data types. Dropping it.' %col)
except:
df.drop(col,axis=1,inplace=True)
print(' dropping %s since it gives error.' %col)
return df
############################################################################################
def convert_all_object_columns_to_numeric(train, test=""):
"""
This a handy function for Feature Engineering - That's why I have included it in Lazy Transform
######################################################################################
This is a utility that converts string columns to numeric using MY_LABEL ENCODER.
Make sure test and train have the same number of columns. If you have target in train,
remove it before sending it through this utility. Otherwise, might blow up during test transform.
The beauty of My_LabelEncoder is it handles NA's and future values in test that are not in train.
#######################################################################################
Inputs:
train : pandas dataframe
test: (optional) pandas dataframe
Outputs:
train: this is the transformed DataFrame
test: (optional) this is the transformed test dataframe if given.
######################################################################################
"""
train = copy.deepcopy(train)
test = copy.deepcopy(test)
#### This is to fill all numeric columns with a missing number ##########
nums = train.select_dtypes('number').columns.tolist()
if len(nums) == 0:
pass
else:
if train[nums].isnull().sum().sum() > 0:
null_cols = np.array(nums)[train[nums].isnull().sum()>0].tolist()
for each_col in null_cols:
new_missing_col = each_col + '_Missing_Flag'
train[new_missing_col] = 0
train.loc[train[each_col].isnull(),new_missing_col]=1
train[each_col] = train[each_col].fillna(-9999)
if not train[each_col].dtype in [np.float64,np.float32,np.float16]:
train[each_col] = train[each_col].astype(int)
if not isinstance(test, str):
if test is None:
pass
else:
new_missing_col = each_col + '_Missing_Flag'
test[new_missing_col] = 0
test.loc[test[each_col].isnull(),new_missing_col]=1
test[each_col] = test[each_col].fillna(-9999)
if not test[each_col].dtype in [np.float64,np.float32,np.float16]:
test[each_col] = test[each_col].astype(int)
###### Now we convert all object columns to numeric ##########
lis = []
lis = train.select_dtypes('object').columns.tolist() + train.select_dtypes('category').columns.tolist()
if not isinstance(test, str):
if test is None:
pass
else:
lis_test = test.select_dtypes('object').columns.tolist() + test.select_dtypes('category').columns.tolist()
if len(left_subtract(lis, lis_test)) > 0:
### if there is an extra column in train that is not in test, then remove it from consideration
lis = copy.deepcopy(lis_test)
if not (len(lis)==0):
for everycol in lis:
MLB = My_LabelEncoder()
try:
train[everycol] = MLB.fit_transform(train[everycol])
if not isinstance(test, str):
if test is None:
pass
else:
test[everycol] = MLB.transform(test[everycol])
except:
print('Error converting %s column from string to numeric. Continuing...' %everycol)
continue
return train, test
################################################################################################
def drop_second_col(Xt):
### This deletes the 2nd column. Hence col number=1 and axis=1 ###
return np.delete(Xt, 1, 1)
def change_col_to_string(Xt):
### This converts the input column to a string and returns it ##
return Xt.astype(str)
def create_column_names(Xt, nlpvars=[], catvars=[], discretevars=[], floatvars=[], intvars=[],
datevars=[], onehot_dict={}, colsize_dict={},datesize_dict={}):
cols_nlp = []
### This names all the features created by the NLP column. Hence col number=1 and axis=1 ###
for each_nlp in nlpvars:
colsize = colsize_dict[each_nlp]
nlp_add = [each_nlp+'_'+str(x) for x in range(colsize)]
cols_nlp += nlp_add
### this is for discrete column names ####
cols_discrete = []
for each_discrete in discretevars:
### for anything other than one-hot we should just use label encoding to make it simpler ##
discrete_add = each_discrete+'_encoded'
cols_discrete.append(discrete_add)
## do the same for datevars ###
cols_date = []
for each_date in datevars:
#colsize = datesize_dict[each_date]
#date_add = [each_date+'_'+str(x) for x in range(colsize)]
date_add = datesize_dict[each_date]
cols_date += date_add
#### this is where we put all the column names together #######
cols_names = catvars+cols_discrete+intvars+cols_date
num_vars = cols_nlp+floatvars
num_len = len(num_vars)
### Xt is a Sparse matrix array, we need to convert it to dense array ##
if scipy.sparse.issparse(Xt):
Xt = Xt.toarray()
### Xt is already a dense array, no need to convert it ##
if num_len == 0:
try:
Xint = pd.DataFrame(Xt[:,:], columns = cols_names, dtype=np.int16)
except:
Xint = pd.DataFrame(Xt[:,:], columns = cols_names, dtype=np.int64)
return Xint
else:
try:
Xint = pd.DataFrame(Xt[:,:-num_len], columns = cols_names, dtype=np.int16)
except:
Xint = pd.DataFrame(Xt[:,:-num_len], columns = cols_names, dtype=np.int64)
Xnum = pd.DataFrame(Xt[:,-num_len:], columns = num_vars, dtype=np.float32)
#### this is where we put all the column names together #######
df = pd.concat([Xint, Xnum], axis=1)
return df
#############################################################################################################
import collections
def make_column_names_unique(cols):
ser = pd.Series(cols)
### This function removes all special chars from a list ###
remove_special_chars = lambda x:re.sub('[^A-Za-z0-9_]+', '', x)
newls = ser.map(remove_special_chars).values.tolist()
### there may be duplicates in this list - we need to make them unique by randomly adding strings to name ##
seen = [item for item, count in collections.Counter(newls).items() if count > 1]
cols = [x+str(random.randint(1,1000)) if x in seen else x for x in newls]
return cols
#############################################################################################################
def create_column_names_onehot(Xt, nlpvars=[], catvars=[], discretevars=[], floatvars=[], intvars=[],
datevars=[], onehot_dict={},
colsize_dict={}, datesize_dict={}):
### This names all the features created by the NLP column. Hence col number=1 and axis=1 ###
### Once you get back names of one hot encoded columns, change the column names
cols_cat = []
x_cols = []
for each_cat in catvars:
categs = onehot_dict[each_cat]
if isinstance(categs, str):
if categs == 'label':
cat_add = each_cat+'_encoded'
cols_cat.append(cat_add)
else:
categs = [categs]
cat_add = [each_cat+'_'+str(categs[i]) for i in range(len(categs))]
cols_cat += cat_add
else:
cat_add = [each_cat+'_'+str(categs[i]) for i in range(len(categs))]
cols_cat += cat_add
try:
cols_cat = make_column_names_unique(cols_cat)
except:
print(' Could not check if column names are unique in one-hot. Please double-check.')
cols_discrete = []
discrete_add = []
for each_discrete in discretevars:
### for anything other than one-hot we should just use label encoding to make it simpler ##
try:
categs = onehot_dict[each_discrete]
if isinstance(categs, str):
if categs == 'label':
discrete_add = each_discrete+'_encoded'
cols_discrete.append(discrete_add)
else:
categs = [categs]
discrete_add = [each_discrete+'_'+x for x in categs]
cols_discrete += discrete_add
else:
discrete_add = [each_discrete+'_'+x for x in categs]
cols_discrete += discrete_add
except:
### if there is no new var to be created, just use the existing discrete vars itself ###
cols_discrete.append(each_discrete)
try:
cols_discrete = make_column_names_unique(cols_discrete)
except:
print(' Could not check if column names are unique in one-hot. Please double-check.')
cols_nlp = []
nlp_add = []
for each_nlp in nlpvars:
colsize = colsize_dict[each_nlp]
nlp_add = [each_nlp+'_'+str(x) for x in range(colsize)]
cols_nlp += nlp_add
## do the same for datevars ###
cols_date = []
date_add = []
for each_date in datevars:
#colsize = datesize_dict[each_date]
#date_add = [each_date+'_'+str(x) for x in range(colsize)]
date_add = datesize_dict[each_date]
cols_date += date_add
### Remember don't combine the next 2 lines into one. That will be a disaster.
### Pandas infers data types autmatically and they always are float64. So
### to avoid that I have split the data into two or three types
cols_names = cols_cat+cols_discrete+intvars+cols_date
num_vars = cols_nlp+floatvars
num_len = len(num_vars)
### Xt is a Sparse matrix array, we need to convert it to dense array ##
if scipy.sparse.issparse(Xt):
Xt = Xt.toarray()
### Xt is already a dense array, no need to convert it ##
### Remember don't combine the next 2 lines into one. That will be a disaster.
### Pandas infers data types autmatically and they always are float64. So
### to avoid that I have split the data into two or three types
if num_len == 0:
Xint = pd.DataFrame(Xt[:,:], columns = cols_names, dtype=np.int16)
return Xint
else:
try:
Xint = pd.DataFrame(Xt[:,:-num_len], columns = cols_names, dtype=np.int16)
except:
Xint = pd.DataFrame(Xt[:,:-num_len], columns = cols_names, dtype=np.int64)
Xnum = pd.DataFrame(Xt[:,-num_len:], columns = num_vars, dtype=np.float32)
#### this is where we put all the column names together #######
df = pd.concat([Xint, Xnum], axis=1)
return df
######################################################################################
def find_remove_duplicates(list_of_values):
"""
# Removes duplicates from a list to return unique values - USED ONLY ONCE
"""
output = []
seen = set()
for value in list_of_values:
if value not in seen:
output.append(value)
seen.add(value)
return output
def convert_ce_to_pipe(Xt):
### This converts a series to a dataframe to make category encoders work in sklearn pipelines ###
if str(Xt.dtype) == 'category':
Xtx = Xt.cat.rename_categories(str).values.tolist()
return pd.DataFrame(Xtx, columns=[Xt.name], index=Xt.index)
else:
Xtx = Xt.fillna('missing')
return pd.DataFrame(Xtx)
#####################################################################################
#### Regression or Classification type problem
def analyze_problem_type(y_train, target, verbose=0) :
y_train = copy.deepcopy(y_train)
cat_limit = 30 ### this determines the number of categories to name integers as classification ##
float_limit = 15 ### this limits the number of float variable categories for it to become cat var
if isinstance(target, str):
multi_label = False
string_target = True
else:
if len(target) == 1:
multi_label = False
string_target = False
else:
multi_label = True
string_target = False
#### This is where you detect what kind of problem it is #################
if string_target:
## If target is a string then we should test for dtypes this way #####
if y_train.dtype in ['int64', 'int32','int16']:
if len(np.unique(y_train)) <= 2:
model_class = 'Binary_Classification'
elif len(y_train.unique()) > 2 and len(y_train.unique()) <= cat_limit:
model_class = 'Multi_Classification'
else:
model_class = 'Regression'
elif y_train.dtype in ['float16','float32','float64']:
if len(y_train.unique()) <= 2:
model_class = 'Binary_Classification'
elif len(y_train.unique()) > 2 and len(y_train.unique()) <= float_limit:
model_class = 'Multi_Classification'
else:
model_class = 'Regression'
else:
if len(y_train.unique()) <= 2:
model_class = 'Binary_Classification'
else:
model_class = 'Multi_Classification'
else:
for i in range(y_train.shape[1]):
### if target is a list, then we should test dtypes a different way ###
if y_train.dtypes.values.all() in ['int64', 'int32','int16']:
if len(np.unique(y_train.iloc[:,0])) <= 2:
model_class = 'Binary_Classification'
elif len(np.unique(y_train.iloc[:,0])) > 2 and len(np.unique(y_train.iloc[:,0])) <= cat_limit:
model_class = 'Multi_Classification'
else:
model_class = 'Regression'
elif y_train.dtypes.values.all() in ['float16','float32','float64']:
if len(np.unique(y_train.iloc[:,0])) <= 2:
model_class = 'Binary_Classification'
elif len(np.unique(y_train.iloc[:,0])) > 2 and len(np.unique(y_train.iloc[:,0])) <= float_limit:
model_class = 'Multi_Classification'
else:
model_class = 'Regression'
else:
if len(np.unique(y_train.iloc[:,0])) <= 2:
model_class = 'Binary_Classification'
else:
model_class = 'Multi_Classification'
########### print this for the start of next step ###########
if verbose:
if multi_label:
print(''' %s %s problem ''' %('Multi_Label', model_class))
else:
print(''' %s %s problem ''' %('Single_Label', model_class))
return model_class, multi_label
####################################################################################################
import copy
import time
from dateutil.relativedelta import relativedelta
from datetime import date
def _create_ts_features(df, verbose=0):
"""
This takes in input a dataframe and a date variable.
It then creates time series features using the pandas .dt.weekday kind of syntax.
It also returns the data frame of added features with each variable as an integer variable.
"""
df = copy.deepcopy(df)
tscol = df.name
if isinstance(df, pd.Series):
df = pd.DataFrame(df)
elif isinstance(df, np.ndarray):
print(' input cannot be a numpy array for creating date-time features. Returning')
return df
dt_adds = []
##### This is where we add features one by one #########
try:
df[tscol+'_hour'] = df[tscol].dt.hour.fillna(0).astype(int)
df[tscol+'_minute'] = df[tscol].dt.minute.fillna(0).astype(int)
dt_adds.append(tscol+'_hour')
dt_adds.append(tscol+'_minute')
except:
print(' Error in creating hour-second derived features. Continuing...')
try:
df[tscol+'_dayofweek'] = df[tscol].dt.dayofweek.fillna(0).astype(int)
dt_adds.append(tscol+'_dayofweek')
# day of week Sine and Cos functions
df[tscol+'_dayofweek_sin'] = df[tscol+'_dayofweek'].apply( lambda x: np.sin( x * ( 2. * np.pi/7 ) ) )
df[tscol+'_dayofweek_cos'] = df[tscol+'_dayofweek'].apply( lambda x: np.cos( x * ( 2. * np.pi/7 ) ) )
dt_adds.append(tscol+'_dayofweek_sin')
dt_adds.append(tscol+'_dayofweek_cos')
###### Create some Feature Crosses with day of week ###################
if tscol+'_hour' in dt_adds:
DAYS = dict(zip(range(7),['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']))
df[tscol+'_dayofweek'] = df[tscol+'_dayofweek'].map(DAYS)
df.loc[:,tscol+'_dayofweek_hour_cross'] = df[tscol+'_dayofweek'] +" "+ df[tscol+'_hour'].astype(str)
dt_adds.append(tscol+'_dayofweek_hour_cross')
df[tscol+'_quarter'] = df[tscol].dt.quarter.fillna(0).astype(int)
dt_adds.append(tscol+'_quarter')
df[tscol+'_month'] = df[tscol].dt.month.fillna(0).astype(int)
#### Add some Sine and Cos functions for Month #################
df[tscol+'_month_sin'] = df[tscol+'_month'].apply( lambda x: np.sin( x * ( 2. * np.pi/12 )) )
df[tscol+'_month_cos'] = df[tscol+'_month'].apply( lambda x: np.cos( x * ( 2. * np.pi/12 )) )
dt_adds.append(tscol+'_month_sin')
dt_adds.append(tscol+'_month_cos')
############## Convert Months from numeric to object strings ############
MONTHS = dict(zip(range(1,13),['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec']))
df[tscol+'_month'] = df[tscol+'_month'].map(MONTHS)
dt_adds.append(tscol+'_month')
#### Add some features for months ########################################
festives = ['Oct','Nov','Dec']
name_col = tscol+"_is_festive"
df[name_col] = 0
df[name_col] = df[tscol+'_month'].map(lambda x: 1 if x in festives else 0).values
### Remember that fillna only works at dataframe level! ###
df[[name_col]] = df[[name_col]].fillna(0)
dt_adds.append(name_col)
summer = ['Jun','Jul','Aug']
name_col = tscol+"_is_summer"
df[name_col] = 0
df[name_col] = df[tscol+'_month'].map(lambda x: 1 if x in summer else 0).values
### Remember that fillna only works at dataframe level! ###
df[[name_col]] = df[[name_col]].fillna(0)
dt_adds.append(name_col)
winter = ['Dec','Jan','Feb']
name_col = tscol+"_is_winter"
df[name_col] = 0
df[name_col] = df[tscol+'_month'].map(lambda x: 1 if x in winter else 0).values
### Remember that fillna only works at dataframe level! ###
df[[name_col]] = df[[name_col]].fillna(0)
dt_adds.append(name_col)
cold = ['Oct','Nov','Dec','Jan','Feb','Mar']
name_col = tscol+"_is_cold"
df[name_col] = 0
df[name_col] = df[tscol+'_month'].map(lambda x: 1 if x in cold else 0).values
### Remember that fillna only works at dataframe level! ###
df[[name_col]] = df[[name_col]].fillna(0)
dt_adds.append(name_col)
warm = ['Apr','May','Jun','Jul','Aug','Sep']
name_col = tscol+"_is_warm"
df[name_col] = 0
df[name_col] = df[tscol+'_month'].map(lambda x: 1 if x in warm else 0).values
### Remember that fillna only works at dataframe level! ###
df[[name_col]] = df[[name_col]].fillna(0)
dt_adds.append(name_col)
#########################################################################
if tscol+'_dayofweek' in dt_adds:
df.loc[:,tscol+'_month_dayofweek_cross'] = df[tscol+'_month'] +" "+ df[tscol+'_dayofweek']
dt_adds.append(tscol+'_month_dayofweek_cross')
df[tscol+'_year'] = df[tscol].dt.year.fillna(0).astype(int)
dt_adds.append(tscol+'_year')
today = date.today()
df[tscol+'_age_in_years'] = today.year - df[tscol].dt.year.fillna(0).astype(int)
dt_adds.append(tscol+'_age_in_years')
df[tscol+'_dayofyear'] = df[tscol].dt.dayofyear.fillna(0).astype(int)
dt_adds.append(tscol+'_dayofyear')
df[tscol+'_dayofmonth'] = df[tscol].dt.day.fillna(0).astype(int)
dt_adds.append(tscol+'_dayofmonth')
##### Add Sine and cos functions for Day of Month ##############
df[tscol+'_dayofmonth_sin'] = df[tscol+'_dayofmonth'].apply( lambda x: np.sin( x * ( 2. * np.pi/30 ) ) )
df[tscol+'_dayofmonth_cos'] = df[tscol+'_dayofmonth'].apply( lambda x: np.cos( x * ( 2. * np.pi/30 ) ) )
dt_adds.append(tscol+'_dayofmonth_sin')
dt_adds.append(tscol+'_dayofmonth_cos')
######### Continue with other functions ##########
df[tscol+'_weekofyear'] = df[tscol].dt.weekofyear.fillna(0).astype(int)
dt_adds.append(tscol+'_weekofyear')
weekends = (df[tscol+'_dayofweek'] == 'Sat') | (df[tscol+'_dayofweek'] == 'Sun')
df[tscol+'_typeofday'] = 'weekday'
df.loc[weekends, tscol+'_typeofday'] = 'weekend'
dt_adds.append(tscol+'_typeofday')
if tscol+'_typeofday' in dt_adds:
df.loc[:,tscol+'_month_typeofday_cross'] = df[tscol+'_month'] +" "+ df[tscol+'_typeofday']
dt_adds.append(tscol+'_month_typeofday_cross')
except:
print(' Error in creating date time derived features. Continuing...')
if verbose:
print(' created %d columns from time series %s column' %(len(dt_adds),tscol))
return df[dt_adds]
##################################################################################
### This wrapper was proposed by someone in Stackoverflow which works well #######
### Many thanks to: https://stackoverflow.com/questions/63000388/how-to-include-simpleimputer-before-countvectorizer-in-a-scikit-learn-pipeline
##################################################################################
class Make2D:
"""One dimensional wrapper for sklearn Transformers"""
def __init__(self, transformer):
self.transformer = transformer
def fit(self, X, y=None):
self.transformer.fit(np.array(X).reshape(-1, 1))
return self
def transform(self, X, y=None):
return self.transformer.transform(
np.array(X).reshape(-1, 1)).ravel()
def inverse_transform(self, X, y=None):
return self.transformer.inverse_transform(
np.expand_dims(X, axis=1)).ravel()
##################################################################################
def return_default():
missing_value = "missing_"+str(random.randint(1,1000))
return missing_value
##################################################################################
import pdb
def make_simple_pipeline(X_train, y_train, encoders='auto', scalers='',
date_to_string='', save_flag=False, combine_rare_flag=False, verbose=0):
"""
######################################################################################################################
# # This is the SIMPLEST best pipeline for NLP and Time Series problems - Created by Ram Seshadri
###### This pipeline is inspired by Kevin Markham's class on Scikit-Learn pipelines.
###### You can sign up for his Data School class here: https://www.dataschool.io/
######################################################################################################################
#### What does this pipeline do. Here's the major steps:
# 1. Takes categorical variables and encodes them using my special label encoder which can handle NaNs and future categories
# 2. Takes numeric variables and imputes them using a simple imputer
# 3. Takes NLP and time series (string) variables and vectorizes them using CountVectorizer
# 4. Completely standardizing all of the above using AbsMaxScaler which preserves the relationship of label encoded vars
# 5. Finally adds an RFC or RFR to the pipeline so the entire pipeline can be fed to a cross validation scheme
#### The results are yet to be THOROUGHLY TESTED but preliminary results OF THIS PIPELINE ARE very promising INDEED.
######################################################################################################################
"""
start_time = time.time()
### Now decide which pipeline you want to use ###########
##### Now set up all the encoders ##################
if isinstance(encoders, list):
basic_encoder = encoders[0]
encoder = encoders[1]
if not isinstance(basic_encoder, str) or not isinstance(encoder, str):
print('encoders must be either string or list of strings. Please check your input and try again.')
return
elif isinstance(encoders, str):
if encoders == 'auto':
basic_encoder = 'onehot'
encoder = 'label'
else:
basic_encoder = copy.deepcopy(encoders)
encoder = copy.deepcopy(encoders)
else:
print('encoders must be either string or list of strings. Please check your input and try again.')
return
if isinstance(X_train, np.ndarray):
print('X_train input must be a dataframe since we use column names to build data pipelines. Returning')
return {}, {}