generated from Y-oHr-N/python-package-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
estimators.py
2096 lines (1649 loc) · 51.2 KB
/
estimators.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
"""Estimators."""
import itertools
import logging
from typing import Any
from typing import Dict
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import Union
import numpy as np
import pandas as pd
import sklearn
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.base import RegressorMixin
from sklearn.base import clone
from sklearn.base import TransformerMixin
from sklearn.compose._column_transformer import _get_transformer_list
from sklearn.model_selection import train_test_split
from sklearn.model_selection import BaseCrossValidator
from sklearn.model_selection import check_cv
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import check_random_state
from sklearn.utils.multiclass import type_of_target
from tqdm import trange
if sklearn.__version__ >= "0.22":
from sklearn.feature_selection._from_model import _calculate_threshold
from sklearn.feature_selection._from_model import _get_feature_importances
else:
from sklearn.feature_selection.from_model import _calculate_threshold
from sklearn.feature_selection.from_model import _get_feature_importances
from ..utils import check_X
from ..utils import get_categorical_cols
from ..utils import get_numerical_cols
from ..utils import get_time_cols
from ..utils import get_unknown_cols
from ..utils import sigmoid
MAX_INT = np.iinfo(np.int32).max
def make_modified_column_transformer(
*transformers: Tuple,
) -> "ModifiedColumnTransformer":
"""Make ModifedColumnTransformer.
Examples
--------
>>> from pretools.sklearn.estimators import make_modified_column_transformer # noqa
>>> transformers = [("passthrough", [0])]
>>> est = make_modified_column_transformer(*transformers)
"""
transformer_list = _get_transformer_list(transformers)
return ModifiedColumnTransformer(transformer_list)
class Astype(BaseEstimator, TransformerMixin):
"""Astype.
Examples
--------
>>> from pretools.sklearn.estimators import Astype
>>> from sklearn.datasets import load_iris
>>> X, _ = load_iris(return_X_y=True)
>>> est = Astype()
>>> Xt = est.fit_transform(X)
"""
def __init__(self, copy: bool = True) -> None:
self.copy = copy
def fit(self, X: pd.DataFrame, y: Optional[pd.Series] = None) -> "Astype":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.
Returns
-------
Xt
Transformed data.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
if self.copy:
X = X.copy()
numerical_cols = get_numerical_cols(X, labels=True)
unknown_cols = get_unknown_cols(X, labels=True)
if len(numerical_cols) > 0:
X[numerical_cols] = X[numerical_cols].astype("float32")
if len(unknown_cols) > 0:
X[unknown_cols] = X[unknown_cols].astype("category")
return X
class CalendarFeatures(BaseEstimator, TransformerMixin):
"""Calendar features.
Examples
--------
>>> import datetime
>>> from pretools.sklearn.estimators import CalendarFeatures
>>> X = [
... [datetime.datetime(2000, 1, 1, 0, 0, 0)],
... [np.nan],
... [datetime.datetime(2010, 10, 10, 10, 0, 0)]
... ]
>>> est = CalendarFeatures()
>>> Xt = est.fit_transform(X)
"""
def __init__(
self,
dtype: Union[str, Type] = "float64",
encode: bool = False,
include_unixtime: bool = False,
) -> None:
self.dtype = dtype
self.encode = encode
self.include_unixtime = include_unixtime
def fit(
self, X: pd.DataFrame, y: Optional[pd.Series] = None
) -> "CalendarFeatures":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
secondsinminute = 60.0
secondsinhour = 60.0 * secondsinminute
secondsinday = 24.0 * secondsinhour
secondsinweekday = 7.0 * secondsinday
secondsinmonth = 30.4167 * secondsinday
secondsinyear = 12.0 * secondsinmonth
self.attributes_ = {}
for col in X:
s = X[col]
duration = s.max() - s.min()
duration = duration.total_seconds()
attrs = []
if duration >= 2.0 * secondsinyear:
# if s.dt.dayofyear.nunique() > 1:
# attrs.append("dayofyear")
# if s.dt.weekofyear.nunique() > 1:
# attrs.append("weekofyear")
# if s.dt.quarter.nunique() > 1:
# attrs.append("quarter")
if s.dt.month.nunique() > 1:
attrs.append("month")
if duration >= 2.0 * secondsinmonth and s.dt.day.nunique() > 1:
attrs.append("day")
if (
duration >= 2.0 * secondsinweekday
and s.dt.weekday.nunique() > 1
):
attrs.append("weekday")
if duration >= 2.0 * secondsinday and s.dt.hour.nunique() > 1:
attrs.append("hour")
# if (
# duration >= 2.0 * secondsinhour
# and s.dt.minute.nunique() > 1
# ):
# attrs.append("minute")
# if (
# duration >= 2.0 * secondsinminute
# and s.dt.second.nunique() > 1
# ):
# attrs.append("second")
self.attributes_[col] = attrs
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.
Returns
-------
Xt
Transformed data.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
Xt = pd.DataFrame()
for col in X:
s = X[col]
if self.include_unixtime:
unixtime = 1e-09 * s.astype("int64")
unixtime = unixtime.astype(self.dtype)
Xt["{}_unixtime".format(col)] = unixtime
for attr in self.attributes_[col]:
x = getattr(s.dt, attr)
if not self.encode:
x = x.astype("category")
Xt["{}_{}".format(col, attr)] = x
continue
# if attr == "dayofyear":
# period = np.where(s.dt.is_leap_year, 366.0, 365.0)
# elif attr == "weekofyear":
# period = 52.1429
# elif attr == "quarter":
# period = 4.0
elif attr == "month":
period = 12.0
elif attr == "day":
period = s.dt.daysinmonth
elif attr == "weekday":
period = 7.0
elif attr == "hour":
x += s.dt.minute / 60.0 + s.dt.second / 60.0
period = 24.0
# elif attr in ["minute", "second"]:
# period = 60.0
theta = 2.0 * np.pi * x / period
sin_theta = np.sin(theta)
sin_theta = sin_theta.astype(self.dtype)
cos_theta = np.cos(theta)
cos_theta = cos_theta.astype(self.dtype)
Xt["{}_{}_sin".format(col, attr)] = sin_theta
Xt["{}_{}_cos".format(col, attr)] = cos_theta
logger = logging.getLogger(__name__)
_, n_created_features = Xt.shape
logger.info(
"{} created {} features.".format(
self.__class__.__name__, n_created_features
)
)
return Xt
class ClippedFeatures(BaseEstimator, TransformerMixin):
"""Clipped features.
Examples
--------
>>> from pretools.sklearn.estimators import ClippedFeatures
>>> X = [[10, np.nan, 4], [0, 2, 1]]
>>> est = ClippedFeatures()
>>> Xt = est.fit_transform(X)
"""
def __init__(
self, copy: bool = True, high: float = 0.99, low: float = 0.01,
) -> None:
self.copy = copy
self.high = high
self.low = low
def fit(
self, X: pd.DataFrame, y: Optional[pd.Series] = None
) -> "ClippedFeatures":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(X, estimator=self, force_all_finite="allow-nan")
self.data_max_ = X.quantile(q=self.high)
self.data_min_ = X.quantile(q=self.low)
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.
Returns
-------
Xt
Transformed data.
"""
X = check_X(X, estimator=self, force_all_finite="allow-nan")
if self.copy:
X = X.copy()
X.clip(self.data_min_, self.data_max_, axis=1, inplace=True)
return X
class CombinedFeatures(BaseEstimator, TransformerMixin):
"""Combined Features.
Examples
--------
>>> from pretools.sklearn.estimators import CombinedFeatures
>>> X = [[1, 1], [1, 2], [1, np.nan], [1, -10]]
>>> est = CombinedFeatures()
>>> Xt = est.fit_transform(X)
"""
@property
def _operands(self) -> List[str]:
if self.operands is None:
return [
"add",
"subtract",
"multiply",
"divide",
# "equal",
]
return self.operands
def __init__(
self,
include_data: bool = False,
max_features: Optional[Union[int, str]] = "auto",
operands: Optional[List[str]] = None,
) -> None:
self.include_data = include_data
self.max_features = max_features
self.operands = operands
def _numerical_transform(
self, X: pd.DataFrame, max_features: int,
) -> pd.DataFrame:
Xt = pd.DataFrame()
n_features = 0
for col1, col2 in itertools.combinations(X.columns, 2):
for operand in self._operands:
if n_features >= max_features:
break
func = getattr(np, operand)
Xt["{}_{}_{}".format(operand, col1, col2)] = func(
X[col1], X[col2]
)
n_features += 1
return Xt
def _other_transform(
self, X: pd.DataFrame, max_features: int,
) -> pd.DataFrame:
Xt = pd.DataFrame()
n_features = 0
for col1, col2 in itertools.combinations(X.columns, 2):
for operand in self._operands:
if n_features >= max_features:
break
if operand == "multiply":
func = np.vectorize(lambda x1, x2: "{}*{}".format(x1, x2))
elif operand == "equal":
func = np.equal
else:
continue
try:
feature = func(X[col1], X[col2])
except TypeError:
continue
if operand == "multiply":
feature = pd.Series(feature, index=X.index)
feature = feature.astype("category")
Xt["{}_{}_{}".format(operand, col1, col2)] = feature
n_features += 1
return Xt
def fit(
self, X: pd.DataFrame, y: Optional[pd.Series] = None
) -> "CombinedFeatures":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
self.n_samples_, self.n_features_ = X.shape
if self.max_features is None:
self.max_features_ = np.inf
elif self.max_features == "auto":
if self.include_data:
self.max_features_ = self.n_samples_ - self.n_features_ - 1
else:
self.max_features_ = self.n_samples_ - 1
else:
self.max_features_ = self.max_features
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.
Returns
-------
Xt
Transformed data.
"""
X = check_X(X, dtype=None, force_all_finite="allow-nan")
is_numerical = get_numerical_cols(X)
logger = logging.getLogger(__name__)
Xt_numerical = self._numerical_transform(
X.loc[:, is_numerical], self.max_features_,
)
_, n_created_features = Xt_numerical.shape
Xt_other = self._other_transform(
X.loc[:, ~is_numerical], self.max_features_ - n_created_features,
)
Xt = pd.concat([Xt_numerical, Xt_other], axis=1)
_, n_created_features = Xt.shape
logger.info(
"{} created {} features.".format(
self.__class__.__name__, n_created_features
)
)
if self.include_data:
Xt = pd.concat([X, Xt], axis=1)
return Xt
class DiffFeatures(BaseEstimator, TransformerMixin):
"""Diff features.
Examples
--------
>>> import numpy as np
>>> from pretools.sklearn.estimators import DiffFeatures
>>> est = DiffFeatures()
>>> X = [[1], [np.nan], [1], [10], [1]]
>>> Xt = est.fit_transform(X)
"""
def __init__(self, include_data: bool = False) -> None:
self.include_data = include_data
def fit(
self, X: pd.DataFrame, y: Optional[pd.Series] = None
) -> "DiffFeatures":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.
Returns
-------
Xt
Transformed data.
"""
X = check_X(X, estimator=self, force_all_finite="allow-nan")
Xt = X.diff()
Xt.rename(columns="{}_diff".format, inplace=True)
if self.include_data:
Xt = pd.concat([X, Xt], axis=1)
return Xt
class DropCollinearFeatures(BaseEstimator, TransformerMixin):
"""Feature selector that removes collinear features.
Examples
--------
>>> from pretools.sklearn.estimators import DropCollinearFeatures
>>> X = [[1, 1, 1], [2, 2, 200], [3, 3, 3000], [1, np.nan, 1]]
>>> est = DropCollinearFeatures()
>>> Xt = est.fit_transform(X)
"""
def __init__(
self,
method: Union[Callable, str] = "pearson",
random_state: Optional[Union[int, np.random.RandomState]] = None,
shuffle: bool = True,
subsample: Union[int, float] = 0.75,
threshold: float = 0.95,
) -> None:
self.method = method
self.random_state = random_state
self.shuffle = shuffle
self.subsample = subsample
self.threshold = threshold
def fit(
self, X: pd.DataFrame, y: Optional[pd.Series] = None
) -> "DropCollinearFeatures":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(X, estimator=self, force_all_finite="allow-nan")
if self.subsample < 1.0:
X, _, = train_test_split(
X,
random_state=self.random_state,
train_size=self.subsample,
shuffle=self.shuffle,
)
self.corr_ = X.corr(method=self.method)
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.
Returns
-------
Xt
Transformed data.
"""
X = check_X(X, estimator=self, force_all_finite="allow-nan")
triu = np.triu(self.corr_, k=1)
triu = np.abs(triu)
triu = np.nan_to_num(triu)
logger = logging.getLogger(__name__)
cols = np.all(triu <= self.threshold, axis=0)
_, n_features = X.shape
n_dropped_features = n_features - np.sum(cols)
logger.info(
"{} dropped {} features.".format(
self.__class__.__name__, n_dropped_features
)
)
return X.loc[:, cols]
class ModifiedCatBoostClassifier(BaseEstimator, ClassifierMixin):
"""Modified CatBoostClassifier.
Examples
--------
>>> import pandas as pd
>>> from pretools.sklearn.estimators import ModifiedCatBoostClassifier
>>> X = [["Cat"], ["Cow"], ["Mouse"], ["Lion"]]
>>> X = pd.DataFrame(X)
>>> X = X.astype("category")
>>> y = [0, 1, 1, 0]
>>> est = ModifiedCatBoostClassifier(verbose=0)
>>> est.fit(X, y)
ModifiedCatBoostClassifier(...)
>>> y_pred = est.predict(X)
"""
@property
def classes_(self) -> np.ndarray:
"""Class labels."""
return self._encoder.classes_
@property
def feature_importances_(self) -> np.ndarray:
"""Feature importances."""
return self._model.get_feature_importance()
@property
def predict_proba(self) -> Callable[[np.ndarray], np.ndarray]:
"""Predict class probabilities for data.
Parameters
----------
X
Data.
Returns
-------
p
Class probabilities of data.
"""
return self._model.predict_proba
def __init__(self, **params: Any) -> None:
from catboost import CatBoostClassifier
self._params = params
self._encoder = LabelEncoder()
self._model = CatBoostClassifier(**params)
def get_params(self, deep: bool = True) -> Dict[str, Any]:
"""Get parameters for this estimator.
Parameters
----------
deep
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params
Estimator parameters.
"""
params = self._model.get_params(deep=deep)
params.update(self._params)
return params
def set_params(self, **params: Any) -> "ModifiedCatBoostClassifier":
"""Set the parameters of this estimator.
Parameters
----------
**params
Estimator parameters.
Returns
-------
self
Return self.
"""
for key, value in params.items():
self._params[key] = value
self._model.set_params(**params)
return self
def fit(
self, X: np.ndarray, y: np.ndarray, **fit_params: Any
) -> "ModifiedCatBoostClassifier":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
y = self._encoder.fit_transform(y)
if "cat_features" not in fit_params:
cat_features = get_categorical_cols(X, labels=True)
fit_params["cat_features"] = cat_features
self._model.fit(X, y, **fit_params)
return self
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predict using the fitted model.
Parameters
----------
X
Data.
Returns
-------
y_pred
Predicted values.
"""
y_pred = self._model.predict(X)
y_pred = np.ravel(y_pred)
y_pred = y_pred.astype("int64")
return self._encoder.inverse_transform(y_pred)
class ModifiedCatBoostRegressor(BaseEstimator, RegressorMixin):
"""Modified CatBoostRegressor.
Examples
--------
>>> import pandas as pd
>>> from pretools.sklearn.estimators import ModifiedCatBoostRegressor
>>> X = [["Cat"], ["Cow"], ["Mouse"], ["Lion"]]
>>> X = pd.DataFrame(X)
>>> X = X.astype("category")
>>> y = [0.0, 1.0, 2.0, 0.0]
>>> est = ModifiedCatBoostRegressor(verbose=0)
>>> est.fit(X, y)
ModifiedCatBoostRegressor(...)
>>> y_pred = est.fit(X, y)
"""
@property
def feature_importances_(self) -> np.ndarray:
"""Feature importances."""
return self._model.get_feature_importance()
@property
def predict(self) -> Callable[[np.ndarray], np.ndarray]:
"""Predict using the fitted model.
Parameters
----------
X
Data.
Returns
-------
y_pred
Predicted values.
"""
return self._model.predict
def __init__(self, **params: Any) -> None:
from catboost import CatBoostRegressor
self._params = params
self._model = CatBoostRegressor(**params)
def get_params(self, deep: bool = True) -> Dict[str, Any]:
"""Get parameters for this estimator.
Parameters
----------
deep
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params
Estimator parameters.
"""
params = self._model.get_params(deep=deep)
params.update(self._params)
return params
def set_params(self, **params: Any) -> "ModifiedCatBoostRegressor":
"""Set the parameters of this estimator.
Parameters
----------
**params
Estimator parameters.
Returns
-------
self
Return self.
"""
for key, value in params.items():
self._params[key] = value
self._model.set_params(**params)
return self
def fit(
self, X: np.ndarray, y: np.ndarray, **fit_params: Any
) -> "ModifiedCatBoostRegressor":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
if "cat_features" not in fit_params:
cat_features = get_categorical_cols(X, labels=True)
fit_params["cat_features"] = cat_features
self._model.fit(X, y, **fit_params)
return self
class ModifiedColumnTransformer(BaseEstimator, TransformerMixin):
"""Modified ColumnTransformer.
Examples
--------
>>> from pretools.sklearn.estimators import ModifiedColumnTransformer
>>> from sklearn.datasets import load_iris
>>> X, y = load_iris(return_X_y=True)
>>> est = ModifiedColumnTransformer([("features", "passthrough", [0])])
>>> Xt = est.fit_transform(X)
"""
def __init__(self, transformers: List[Tuple]) -> None:
self.transformers = transformers
def fit(
self, X: pd.DataFrame, y: Optional[pd.Series] = None
) -> "ModifiedColumnTransformer":
"""Fit the model according to the given training data.
Parameters
----------
X
Training data.
y
Target.
Returns
-------
self
Return self.
"""
X = check_X(
X, dtype=None, estimator=self, force_all_finite="allow-nan"
)
self.transformers_ = []
for name, t, cols in self.transformers:
if callable(cols):
cols = cols(X)
if isinstance(t, BaseEstimator):
t = clone(t)
t.fit(X.loc[:, cols], y)
self.transformers_.append((name, t, cols))
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
"""Transform the data.
Parameters
----------
X
Data.