Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

discretizer.py 33 KB

You have to be logged in to leave a comment. Sign In
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
  1. import numbers
  2. import numpy as np
  3. import pandas as pd
  4. from pandas.api.types import is_numeric_dtype
  5. from sklearn.base import BaseEstimator, TransformerMixin
  6. from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
  7. from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder
  8. from sklearn.utils.validation import check_is_fitted, check_array
  9. """
  10. The classes below (BasicDiscretizer and RFDiscretizer) provide
  11. additional functionalities and wrappers around KBinsDiscretizer
  12. from sklearn. In particular, the following AbstractDiscretizer classes
  13. - take a data frame as input and output a data frame
  14. - allow for discretization of a subset of columns in the data
  15. frame and returns the full data frame with both the
  16. discretized and non-discretized columns
  17. - allow quantile bins to be a single point if necessary
  18. """
  19. class AbstractDiscretizer(TransformerMixin, BaseEstimator):
  20. """
  21. Discretize numeric data into bins. Base class.
  22. Params
  23. ------
  24. n_bins : int or array-like of shape (len(dcols),), default=2
  25. Number of bins to discretize each feature into.
  26. dcols : list of strings
  27. The names of the columns to be discretized; by default,
  28. discretize all float and int columns in X.
  29. encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  30. Method used to encode the transformed result.
  31. onehot
  32. Encode the transformed result with one-hot encoding and
  33. return a dense array.
  34. ordinal
  35. Return the bin identifier encoded as an integer value.
  36. strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  37. Strategy used to define the widths of the bins.
  38. uniform
  39. All bins in each feature have identical widths.
  40. quantile
  41. All bins in each feature have the same number of points.
  42. kmeans
  43. Values in each bin have the same nearest center of a 1D
  44. k-means cluster.
  45. onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default='if_binary'
  46. Specifies a methodology to use to drop one of the categories
  47. per feature when encode = "onehot".
  48. None
  49. Retain all features (the default).
  50. ‘first’
  51. Drop the first y_str in each feature. If only one y_str
  52. is present, the feature will be dropped entirely.
  53. ‘if_binary’
  54. Drop the first y_str in each feature with two categories.
  55. Features with 1 or more than 2 categories are left intact.
  56. """
  57. def __init__(self, n_bins=2, dcols=[],
  58. encode='onehot', strategy='quantile',
  59. onehot_drop='if_binary'):
  60. self.n_bins = n_bins
  61. self.encode = encode
  62. self.strategy = strategy
  63. self.dcols = dcols
  64. if encode == 'onehot':
  65. self.onehot_drop = onehot_drop
  66. def _validate_n_bins(self):
  67. """
  68. Check if n_bins argument is valid.
  69. """
  70. orig_bins = self.n_bins
  71. n_features = len(self.dcols_)
  72. if isinstance(orig_bins, numbers.Number):
  73. if not isinstance(orig_bins, numbers.Integral):
  74. raise ValueError(
  75. "{} received an invalid n_bins type. "
  76. "Received {}, expected int.".format(
  77. AbstractDiscretizer.__name__, type(orig_bins).__name__
  78. )
  79. )
  80. if orig_bins < 2:
  81. raise ValueError(
  82. "{} received an invalid number "
  83. "of bins. Received {}, expected at least 2.".format(
  84. AbstractDiscretizer.__name__, orig_bins
  85. )
  86. )
  87. self.n_bins = np.full(n_features, orig_bins, dtype=int)
  88. else:
  89. n_bins = check_array(orig_bins, dtype=int,
  90. copy=True, ensure_2d=False)
  91. if n_bins.ndim > 1 or n_bins.shape[0] != n_features:
  92. raise ValueError(
  93. "n_bins must be a scalar or array of shape (n_features,).")
  94. bad_nbins_value = (n_bins < 2) | (n_bins != orig_bins)
  95. violating_indices = np.where(bad_nbins_value)[0]
  96. if violating_indices.shape[0] > 0:
  97. indices = ", ".join(str(i) for i in violating_indices)
  98. raise ValueError(
  99. "{} received an invalid number "
  100. "of bins at indices {}. Number of bins "
  101. "must be at least 2, and must be an int.".format(
  102. AbstractDiscretizer.__name__, indices
  103. )
  104. )
  105. self.n_bins = n_bins
  106. def _validate_dcols(self, X):
  107. """
  108. Check if dcols argument is valid.
  109. """
  110. for col in self.dcols_:
  111. if col not in X.columns:
  112. raise ValueError("{} is not a column in X.".format(col))
  113. if not is_numeric_dtype(X[col].dtype):
  114. raise ValueError("Cannot discretize non-numeric columns.")
  115. def _validate_args(self):
  116. """
  117. Check if encode, strategy arguments are valid.
  118. """
  119. valid_encode = ('onehot', 'ordinal')
  120. if self.encode not in valid_encode:
  121. raise ValueError("Valid options for 'encode' are {}. Got encode={!r} instead."
  122. .format(valid_encode, self.encode))
  123. valid_strategy = ('uniform', 'quantile', 'kmeans')
  124. if (self.strategy not in valid_strategy):
  125. raise ValueError("Valid options for 'strategy' are {}. Got strategy={!r} instead."
  126. .format(valid_strategy, self.strategy))
  127. def _discretize_to_bins(self, x, bin_edges,
  128. keep_pointwise_bins=False):
  129. """
  130. Discretize data into bins of the form [a, b) given bin
  131. edges/boundaries
  132. Parameters
  133. ----------
  134. x : array-like of shape (n_samples,)
  135. Data vector to be discretized.
  136. bin_edges : array-like
  137. Values to serve as bin edges; should include min and
  138. max values for the range of x
  139. keep_pointwise_bins : boolean
  140. If True, treat duplicate bin_edges as a pointwise bin,
  141. i.e., [a, a]. If False, these bins are in effect ignored.
  142. Returns
  143. -------
  144. xd: array of shape (n_samples,) where x has been
  145. transformed to the binned space
  146. """
  147. # ignore min and max values in bin generation
  148. unique_edges = np.unique(bin_edges[1:-1])
  149. if keep_pointwise_bins:
  150. # note: min and max values are used to define pointwise bins
  151. pointwise_bins = np.unique(
  152. bin_edges[pd.Series(bin_edges).duplicated()])
  153. else:
  154. pointwise_bins = np.array([])
  155. xd = np.zeros_like(x)
  156. i = 1
  157. for idx, split in enumerate(unique_edges):
  158. if idx == (len(unique_edges) - 1): # uppermost bin
  159. if (idx == 0) & (split in pointwise_bins):
  160. # two bins total: (-inf, a], (a, inf)
  161. indicator = x > split
  162. else:
  163. indicator = x >= split # uppermost bin: [a, inf)
  164. else:
  165. if split in pointwise_bins:
  166. # create two bins: [a, a], (a, b)
  167. indicator = (x > split) & (x < unique_edges[idx + 1]) #
  168. if idx != 0:
  169. xd[x == split] = i
  170. i += 1
  171. else:
  172. # create bin: [a, b)
  173. indicator = (x >= split) & (x < unique_edges[idx + 1])
  174. xd[indicator] = i
  175. i += 1
  176. return xd.astype(int)
  177. def _fit_preprocessing(self, X):
  178. """
  179. Initial checks before fitting the estimator.
  180. Parameters
  181. ----------
  182. X : data frame of shape (n_samples, n_features)
  183. (Training) data to be discretized.
  184. Returns
  185. -------
  186. self
  187. """
  188. # by default, discretize all numeric columns
  189. if len(self.dcols) == 0:
  190. numeric_cols = [
  191. col for col in X.columns if is_numeric_dtype(X[col].dtype)]
  192. self.dcols_ = numeric_cols
  193. # error checking
  194. self._validate_n_bins()
  195. self._validate_args()
  196. self._validate_dcols(X)
  197. def _transform_postprocessing(self, discretized_df, X):
  198. """
  199. Final processing in transform method. Does one-hot encoding
  200. (if specified) and joins discretized columns to the
  201. un-transformed columns in X.
  202. Parameters
  203. ----------
  204. discretized_df : data frame of shape (n_sample, len(dcols))
  205. Discretized data in the transformed bin space.
  206. X : data frame of shape (n_samples, n_features)
  207. Data to be discretized.
  208. Returns
  209. -------
  210. X_discretized : data frame
  211. Data with features in dcols transformed to the
  212. binned space. All other features remain unchanged.
  213. Encoded either as ordinal or one-hot.
  214. """
  215. discretized_df = discretized_df[self.dcols_]
  216. # return onehot encoded X if specified
  217. if self.encode == "onehot":
  218. colnames = [str(col) for col in self.dcols_]
  219. try:
  220. onehot_col_names = self.onehot_.get_feature_names_out(colnames)
  221. except:
  222. onehot_col_names = self.onehot_.get_feature_names(
  223. colnames) # older versions of sklearn
  224. discretized_df = self.onehot_.transform(discretized_df.astype(str))
  225. discretized_df = pd.DataFrame(discretized_df,
  226. columns=onehot_col_names,
  227. index=X.index).astype(int)
  228. # join discretized columns with rest of X
  229. cols = [col for col in X.columns if col not in self.dcols_]
  230. X_discretized = pd.concat([discretized_df, X[cols]], axis=1)
  231. return X_discretized
  232. class ExtraBasicDiscretizer(TransformerMixin):
  233. """
  234. Discretize provided columns into bins and return in one-hot format.
  235. Generates meaningful column names based on bin edges.
  236. Wraps KBinsDiscretizer from sklearn.
  237. Params
  238. ------
  239. dcols : list of strings
  240. The names of the columns to be discretized.
  241. n_bins : int or array-like of shape (len(dcols),), default=4
  242. Number of bins to discretize each feature into.
  243. strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile'
  244. Strategy used to define the widths of the bins.
  245. uniform
  246. All bins in each feature have identical widths.
  247. quantile
  248. All bins in each feature have the same number of points.
  249. kmeans
  250. Values in each bin have the same nearest center of a 1D
  251. k-means cluster.
  252. onehot_drop : {'first', 'if_binary'} or a array-like of shape (len(dcols),), default='if_binary'
  253. Specifies a methodology to use to drop one of the categories
  254. per feature when encode = "onehot".
  255. None
  256. Retain all features (the default).
  257. 'first'
  258. Drop the first y_str in each feature. If only one y_str
  259. is present, the feature will be dropped entirely.
  260. 'if_binary'
  261. Drop the first y_str in each feature with two categories.
  262. Features with 1 or more than 2 categories are left intact.
  263. Attributes
  264. ----------
  265. discretizer_ : object of class KBinsDiscretizer()
  266. Primary discretization method used to bin numeric data
  267. Examples
  268. --------
  269. """
  270. def __init__(self,
  271. dcols,
  272. n_bins=4,
  273. strategy='quantile',
  274. onehot_drop='if_binary'):
  275. self.dcols = dcols
  276. self.n_bins = n_bins
  277. self.strategy = strategy
  278. self.onehot_drop = onehot_drop
  279. def fit(self, X, y=None):
  280. """
  281. Fit the estimator.
  282. Parameters
  283. ----------
  284. X : data frame of shape (n_samples, n_features)
  285. (Training) data to be discretized.
  286. y : Ignored. This parameter exists only for compatibility with
  287. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  288. Returns
  289. -------
  290. self
  291. """
  292. # Fit KBinsDiscretizer to the selected columns
  293. discretizer = KBinsDiscretizer(
  294. n_bins=self.n_bins, strategy=self.strategy, encode='ordinal')
  295. discretizer.fit(X[self.dcols])
  296. self.discretizer_ = discretizer
  297. # Fit OneHotEncoder to the ordinal output of KBinsDiscretizer
  298. disc_ordinal_np = discretizer.transform(X[self.dcols])
  299. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  300. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  301. encoder = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  302. encoder.fit(disc_ordinal_df_str)
  303. self.encoder_ = encoder
  304. return self
  305. def transform(self, X):
  306. """
  307. Discretize the data.
  308. Parameters
  309. ----------
  310. X : data frame of shape (n_samples, n_features)
  311. Data to be discretized.
  312. Returns
  313. -------
  314. X_discretized : data frame
  315. Data with features in dcols transformed to the
  316. binned space. All other features remain unchanged.
  317. """
  318. # Apply discretizer transform to get ordinally coded DF
  319. disc_ordinal_np = self.discretizer_.transform(X[self.dcols])
  320. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  321. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  322. # One-hot encode the ordinal DF
  323. disc_onehot_np = self.encoder_.transform(disc_ordinal_df_str)
  324. disc_onehot = pd.DataFrame(
  325. disc_onehot_np, columns=self.encoder_.get_feature_names_out())
  326. # Name columns after the interval they represent (e.g. 0.1_to_0.5)
  327. for col, bin_edges in zip(self.dcols, self.discretizer_.bin_edges_):
  328. bin_edges = bin_edges.astype(str)
  329. for ordinal_value in disc_ordinal_df_str[col].unique():
  330. bin_lb = bin_edges[int(ordinal_value)]
  331. bin_ub = bin_edges[int(ordinal_value) + 1]
  332. interval_string = f'{bin_lb}_to_{bin_ub}'
  333. disc_onehot = disc_onehot.rename(
  334. columns={f'{col}_{ordinal_value}': f'{col}_' + interval_string})
  335. # Join discretized columns with rest of X
  336. non_dcols = [col for col in X.columns if col not in self.dcols]
  337. X_discretized = pd.concat([disc_onehot, X[non_dcols]], axis=1)
  338. return X_discretized
  339. class BasicDiscretizer(AbstractDiscretizer):
  340. """
  341. Discretize numeric data into bins. Provides a wrapper around
  342. KBinsDiscretizer from sklearn
  343. Params
  344. ------
  345. n_bins : int or array-like of shape (len(dcols),), default=2
  346. Number of bins to discretize each feature into.
  347. dcols : list of strings
  348. The names of the columns to be discretized; by default,
  349. discretize all float and int columns in X.
  350. encode : {'onehot', 'ordinal'}, default='onehot'
  351. Method used to encode the transformed result.
  352. onehot
  353. Encode the transformed result with one-hot encoding and
  354. return a dense array.
  355. ordinal
  356. Return the bin identifier encoded as an integer value.
  357. strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile'
  358. Strategy used to define the widths of the bins.
  359. uniform
  360. All bins in each feature have identical widths.
  361. quantile
  362. All bins in each feature have the same number of points.
  363. kmeans
  364. Values in each bin have the same nearest center of a 1D
  365. k-means cluster.
  366. onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default='if_binary'
  367. Specifies a methodology to use to drop one of the categories
  368. per feature when encode = "onehot".
  369. None
  370. Retain all features (the default).
  371. ‘first’
  372. Drop the first y_str in each feature. If only one y_str
  373. is present, the feature will be dropped entirely.
  374. ‘if_binary’
  375. Drop the first y_str in each feature with two categories.
  376. Features with 1 or more than 2 categories are left intact.
  377. Attributes
  378. ----------
  379. discretizer_ : object of class KBinsDiscretizer()
  380. Primary discretization method used to bin numeric data
  381. manual_discretizer_ : dictionary
  382. Provides bin_edges to feed into _quantile_discretization()
  383. and do quantile discretization manually for features where
  384. KBinsDiscretizer() failed. Ignored if strategy != 'quantile'
  385. or no errors in KBinsDiscretizer().
  386. onehot_ : object of class OneHotEncoder()
  387. One hot encoding fit. Ignored if encode != 'onehot'
  388. Examples
  389. --------
  390. """
  391. def __init__(self, n_bins=2, dcols=[],
  392. encode='onehot', strategy='quantile',
  393. onehot_drop='if_binary'):
  394. super().__init__(n_bins=n_bins, dcols=dcols,
  395. encode=encode, strategy=strategy,
  396. onehot_drop=onehot_drop)
  397. def fit(self, X, y=None):
  398. """
  399. Fit the estimator.
  400. Parameters
  401. ----------
  402. X : data frame of shape (n_samples, n_features)
  403. (Training) data to be discretized.
  404. y : Ignored. This parameter exists only for compatibility with
  405. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  406. Returns
  407. -------
  408. self
  409. """
  410. # initialization and error checking
  411. self._fit_preprocessing(X)
  412. # apply KBinsDiscretizer to the selected columns
  413. discretizer = KBinsDiscretizer(n_bins=self.n_bins,
  414. encode='ordinal',
  415. strategy=self.strategy)
  416. discretizer.fit(X[self.dcols_])
  417. self.discretizer_ = discretizer
  418. if (self.encode == 'onehot') | (self.strategy == 'quantile'):
  419. discretized_df = discretizer.transform(X[self.dcols_])
  420. discretized_df = pd.DataFrame(discretized_df,
  421. columns=self.dcols_,
  422. index=X.index).astype(int)
  423. # fix KBinsDiscretizer errors if any when strategy = "quantile"
  424. if self.strategy == "quantile":
  425. err_idx = np.where(discretized_df.nunique() != self.n_bins)[0]
  426. self.manual_discretizer_ = dict()
  427. for idx in err_idx:
  428. col = self.dcols_[idx]
  429. if X[col].nunique() > 1:
  430. q_values = np.linspace(0, 1, self.n_bins[idx] + 1)
  431. bin_edges = np.quantile(X[col], q_values)
  432. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  433. keep_pointwise_bins=True)
  434. self.manual_discretizer_[col] = bin_edges
  435. # fit onehot encoded X if specified
  436. if self.encode == "onehot":
  437. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  438. onehot.fit(discretized_df.astype(str))
  439. self.onehot_ = onehot
  440. return self
  441. def transform(self, X):
  442. """
  443. Discretize the data.
  444. Parameters
  445. ----------
  446. X : data frame of shape (n_samples, n_features)
  447. Data to be discretized.
  448. Returns
  449. -------
  450. X_discretized : data frame
  451. Data with features in dcols transformed to the
  452. binned space. All other features remain unchanged.
  453. """
  454. check_is_fitted(self)
  455. # transform using KBinsDiscretizer
  456. discretized_df = self.discretizer_.transform(
  457. X[self.dcols_]).astype(int)
  458. discretized_df = pd.DataFrame(discretized_df,
  459. columns=self.dcols_,
  460. index=X.index)
  461. # fix KBinsDiscretizer errors (if any) when strategy = "quantile"
  462. if self.strategy == "quantile":
  463. for col in self.manual_discretizer_.keys():
  464. bin_edges = self.manual_discretizer_[col]
  465. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  466. keep_pointwise_bins=True)
  467. # return onehot encoded data if specified and
  468. # join discretized columns with rest of X
  469. X_discretized = self._transform_postprocessing(discretized_df, X)
  470. return X_discretized
  471. class RFDiscretizer(AbstractDiscretizer):
  472. """
  473. Discretize numeric data into bins using RF splits.
  474. Parameters
  475. ----------
  476. rf_model : RandomForestClassifer() or RandomForestRegressor()
  477. RF model from which to extract splits for discretization.
  478. Default is RandomForestClassifer(n_estimators = 500) or
  479. RandomForestRegressor(n_estimators = 500)
  480. classification : boolean; default=False
  481. Used only if rf_model=None. If True,
  482. rf_model=RandomForestClassifier(n_estimators = 500).
  483. Else, rf_model=RandomForestRegressor(n_estimators = 500)
  484. n_bins : int or array-like of shape (len(dcols),), default=2
  485. Number of bins to discretize each feature into.
  486. dcols : list of strings
  487. The names of the columns to be discretized; by default,
  488. discretize all float and int columns in X.
  489. encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  490. Method used to encode the transformed result.
  491. onehot - Encode the transformed result with one-hot encoding and
  492. return a dense array.
  493. ordinal - Return the bin identifier encoded as an integer value.
  494. strategy : {‘uniform’, ‘quantile’}, default=’quantile’
  495. Strategy used to choose RF split points.
  496. uniform - RF split points chosen to be uniformly spaced out.
  497. quantile - RF split points chosen based on equally-spaced quantiles.
  498. backup_strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  499. Strategy used to define the widths of the bins if no rf splits exist for
  500. that feature. Used in KBinsDiscretizer.
  501. uniform
  502. All bins in each feature have identical widths.
  503. quantile
  504. All bins in each feature have the same number of points.
  505. kmeans
  506. Values in each bin have the same nearest center of a 1D
  507. k-means cluster.
  508. onehot_drop : {‘first’, ‘if_binary’} or array-like of shape (len(dcols),), default='if_binary'
  509. Specifies a methodology to use to drop one of the categories
  510. per feature when encode = "onehot".
  511. None
  512. Retain all features (the default).
  513. ‘first’
  514. Drop the first y_str in each feature. If only one y_str
  515. is present, the feature will be dropped entirely.
  516. ‘if_binary’
  517. Drop the first y_str in each feature with two categories.
  518. Features with 1 or more than 2 categories are left intact.
  519. Attributes
  520. ----------
  521. rf_splits : dictionary where
  522. key = feature name
  523. value = array of all RF split threshold values
  524. bin_edges_ : dictionary where
  525. key = feature name
  526. value = array of bin edges used for discretization, taken from
  527. RF split values
  528. missing_rf_cols_ : array-like
  529. List of features that were not used in RF
  530. backup_discretizer_ : object of class BasicDiscretizer()
  531. Discretization method used to bin numeric data for features
  532. in missing_rf_cols_
  533. onehot_ : object of class OneHotEncoder()
  534. One hot encoding fit. Ignored if encode != 'onehot'
  535. """
  536. def __init__(self, rf_model=None, classification=False,
  537. n_bins=2, dcols=[], encode='onehot',
  538. strategy='quantile', backup_strategy='quantile',
  539. onehot_drop='if_binary'):
  540. super().__init__(n_bins=n_bins, dcols=dcols,
  541. encode=encode, strategy=strategy,
  542. onehot_drop=onehot_drop)
  543. self.backup_strategy = backup_strategy
  544. self.rf_model = rf_model
  545. if rf_model is None:
  546. self.classification = classification
  547. def _validate_args(self):
  548. """
  549. Check if encode, strategy, backup_strategy arguments are valid.
  550. """
  551. super()._validate_args()
  552. valid_backup_strategy = ('uniform', 'quantile', 'kmeans')
  553. if (self.backup_strategy not in valid_backup_strategy):
  554. raise ValueError("Valid options for 'strategy' are {}. Got strategy={!r} instead."
  555. .format(valid_backup_strategy, self.backup_strategy))
  556. def _get_rf_splits(self, col_names):
  557. """
  558. Get all splits in random forest ensemble
  559. Parameters
  560. ----------
  561. col_names : array-like of shape (n_features,)
  562. Column names for X used to train rf_model
  563. Returns
  564. -------
  565. rule_dict : dictionary where
  566. key = feature name
  567. value = array of all RF split threshold values
  568. """
  569. rule_dict = {}
  570. for model in self.rf_model.estimators_:
  571. tree = model.tree_
  572. tree_it = enumerate(zip(tree.children_left,
  573. tree.children_right,
  574. tree.feature,
  575. tree.threshold))
  576. for node_idx, data in tree_it:
  577. left, right, feature, th = data
  578. if (left != -1) | (right != -1):
  579. feature = col_names[feature]
  580. if feature in rule_dict:
  581. rule_dict[feature].append(th)
  582. else:
  583. rule_dict[feature] = [th]
  584. return rule_dict
  585. def _fit_rf(self, X, y=None):
  586. """
  587. Fit random forest (if necessary) and obtain RF split thresholds
  588. Parameters
  589. ----------
  590. X : data frame of shape (n_samples, n_features)
  591. Training data used to fit RF
  592. y : array-like of shape (n_samples,)
  593. Training response vector used to fit RF
  594. Returns
  595. -------
  596. rf_splits : dictionary where
  597. key = feature name
  598. value = array of all RF split threshold values
  599. """
  600. # If no rf_model given, train default random forest model
  601. if self.rf_model is None:
  602. if y is None:
  603. raise ValueError("Must provide y if rf_model is not given.")
  604. if self.classification:
  605. self.rf_model = RandomForestClassifier(n_estimators=500)
  606. else:
  607. self.rf_model = RandomForestRegressor(n_estimators=500)
  608. self.rf_model.fit(X, y)
  609. else:
  610. # provided rf model has not yet been trained
  611. if not check_is_fitted(self.rf_model):
  612. if y is None:
  613. raise ValueError(
  614. "Must provide y if rf_model has not been trained.")
  615. self.rf_model.fit(X, y)
  616. # get all random forest split points
  617. self.rf_splits = self._get_rf_splits(list(X.columns))
  618. def reweight_n_bins(self, X, y=None, by="nsplits"):
  619. """
  620. Reallocate number of bins per feature.
  621. Parameters
  622. ----------
  623. X : data frame of shape (n_samples, n_features)
  624. (Training) data to be discretized.
  625. y : array-like of shape (n_samples,)
  626. (Training) response vector. Required only if
  627. rf_model = None or rf_model has not yet been fitted
  628. by : {'nsplits'}, default='nsplits'
  629. Specifies how to reallocate number of bins per feature.
  630. nsplits
  631. Reallocate number of bins so that each feature
  632. in dcols get at a minimum of 2 bins with the
  633. remaining bins distributed proportionally to the
  634. number of RF splits using that feature
  635. Returns
  636. -------
  637. self.n_bins : array of shape (len(dcols),)
  638. number of bins per feature reallocated according to
  639. 'by' argument
  640. """
  641. # initialization and error checking
  642. self._fit_preprocessing(X)
  643. # get all random forest split points
  644. self._fit_rf(X=X, y=y)
  645. # get total number of bins to reallocate
  646. total_bins = self.n_bins.sum()
  647. # reweight n_bins
  648. if by == "nsplits":
  649. # each col gets at least 2 bins; remaining bins get
  650. # reallocated based on number of RF splits using that feature
  651. n_rules = np.array([len(self.rf_splits[col])
  652. for col in self.dcols_])
  653. self.n_bins = np.round(n_rules / n_rules.sum() *
  654. (total_bins - 2 * len(self.dcols_))) + 2
  655. else:
  656. valid_by = ('nsplits')
  657. raise ValueError("Valid options for 'by' are {}. Got by={!r} instead."
  658. .format(valid_by, by))
  659. def fit(self, X, y=None):
  660. """
  661. Fit the estimator.
  662. Parameters
  663. ----------
  664. X : data frame of shape (n_samples, n_features)
  665. (Training) data to be discretized.
  666. y : array-like of shape (n_samples,)
  667. (Training) response vector. Required only if
  668. rf_model = None or rf_model has not yet been fitted
  669. Returns
  670. -------
  671. self
  672. """
  673. # initialization and error checking
  674. self._fit_preprocessing(X)
  675. # get all random forest split points
  676. self._fit_rf(X=X, y=y)
  677. # features that were not used in the rf but need to be discretized
  678. self.missing_rf_cols_ = list(set(self.dcols_) -
  679. set(self.rf_splits.keys()))
  680. if len(self.missing_rf_cols_) > 0:
  681. print("{} did not appear in random forest so were discretized via {} discretization"
  682. .format(self.missing_rf_cols_, self.strategy))
  683. missing_n_bins = np.array([self.n_bins[np.array(self.dcols_) == col][0]
  684. for col in self.missing_rf_cols_])
  685. backup_discretizer = BasicDiscretizer(n_bins=missing_n_bins,
  686. dcols=self.missing_rf_cols_,
  687. encode='ordinal',
  688. strategy=self.backup_strategy)
  689. backup_discretizer.fit(X[self.missing_rf_cols_])
  690. self.backup_discretizer_ = backup_discretizer
  691. else:
  692. self.backup_discretizer_ = None
  693. if self.encode == 'onehot':
  694. if len(self.missing_rf_cols_) > 0:
  695. discretized_df = backup_discretizer.transform(
  696. X[self.missing_rf_cols_])
  697. else:
  698. discretized_df = pd.DataFrame({}, index=X.index)
  699. # do discretization based on rf split thresholds
  700. self.bin_edges_ = dict()
  701. for col in self.dcols_:
  702. if col in self.rf_splits.keys():
  703. b = self.n_bins[np.array(self.dcols_) == col]
  704. if self.strategy == "quantile":
  705. q_values = np.linspace(0, 1, int(b) + 1)
  706. bin_edges = np.quantile(self.rf_splits[col], q_values)
  707. elif self.strategy == "uniform":
  708. width = (max(self.rf_splits[col]) -
  709. min(self.rf_splits[col])) / b
  710. bin_edges = width * \
  711. np.arange(0, b + 1) + min(self.rf_splits[col])
  712. self.bin_edges_[col] = bin_edges
  713. if self.encode == 'onehot':
  714. discretized_df[col] = self._discretize_to_bins(
  715. X[col], bin_edges)
  716. # fit onehot encoded X if specified
  717. if self.encode == "onehot":
  718. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  719. onehot.fit(discretized_df[self.dcols_].astype(str))
  720. self.onehot_ = onehot
  721. return self
  722. def transform(self, X):
  723. """
  724. Discretize the data.
  725. Parameters
  726. ----------
  727. X : data frame of shape (n_samples, n_features)
  728. Data to be discretized.
  729. Returns
  730. -------
  731. X_discretized : data frame
  732. Data with features in dcols transformed to the
  733. binned space. All other features remain unchanged.
  734. """
  735. check_is_fitted(self)
  736. # transform features that did not appear in RF
  737. if len(self.missing_rf_cols_) > 0:
  738. discretized_df = self.backup_discretizer_.transform(
  739. X[self.missing_rf_cols_])
  740. discretized_df = pd.DataFrame(discretized_df,
  741. columns=self.missing_rf_cols_,
  742. index=X.index)
  743. else:
  744. discretized_df = pd.DataFrame({}, index=X.index)
  745. # do discretization based on rf split thresholds
  746. for col in self.bin_edges_.keys():
  747. discretized_df[col] = self._discretize_to_bins(
  748. X[col], self.bin_edges_[col])
  749. # return onehot encoded data if specified and
  750. # join discretized columns with rest of X
  751. X_discretized = self._transform_postprocessing(discretized_df, X)
  752. return X_discretized
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...