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.html 108 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
  6. <meta name="generator" content="pdoc 0.10.0" />
  7. <link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
  8. <link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
  9. <link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
  10. <style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
  11. <style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
  12. <style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
  13. <script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
  14. <script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
  15. </head>
  16. <body>
  17. <main>
  18. <article id="content">
  19. <section id="section-intro">
  20. <details class="source">
  21. <summary>
  22. <span>Expand source code</span>
  23. </summary>
  24. <pre><code class="python">import numbers
  25. import numpy as np
  26. import pandas as pd
  27. from pandas.api.types import is_numeric_dtype
  28. from sklearn.base import BaseEstimator, TransformerMixin
  29. from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
  30. from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder
  31. from sklearn.utils.validation import check_is_fitted, check_array
  32. &#34;&#34;&#34;
  33. The classes below (BasicDiscretizer and RFDiscretizer) provide
  34. additional functionalities and wrappers around KBinsDiscretizer
  35. from sklearn. In particular, the following AbstractDiscretizer classes
  36. - take a data frame as input and output a data frame
  37. - allow for discretization of a subset of columns in the data
  38. frame and returns the full data frame with both the
  39. discretized and non-discretized columns
  40. - allow quantile bins to be a single point if necessary
  41. &#34;&#34;&#34;
  42. class AbstractDiscretizer(TransformerMixin, BaseEstimator):
  43. &#34;&#34;&#34;
  44. Discretize numeric data into bins. Base class.
  45. Params
  46. ------
  47. n_bins : int or array-like of shape (len(dcols),), default=2
  48. Number of bins to discretize each feature into.
  49. dcols : list of strings
  50. The names of the columns to be discretized; by default,
  51. discretize all float and int columns in X.
  52. encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  53. Method used to encode the transformed result.
  54. onehot
  55. Encode the transformed result with one-hot encoding and
  56. return a dense array.
  57. ordinal
  58. Return the bin identifier encoded as an integer value.
  59. strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  60. Strategy used to define the widths of the bins.
  61. uniform
  62. All bins in each feature have identical widths.
  63. quantile
  64. All bins in each feature have the same number of points.
  65. kmeans
  66. Values in each bin have the same nearest center of a 1D
  67. k-means cluster.
  68. onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  69. Specifies a methodology to use to drop one of the categories
  70. per feature when encode = &#34;onehot&#34;.
  71. None
  72. Retain all features (the default).
  73. ‘first’
  74. Drop the first y_str in each feature. If only one y_str
  75. is present, the feature will be dropped entirely.
  76. ‘if_binary’
  77. Drop the first y_str in each feature with two categories.
  78. Features with 1 or more than 2 categories are left intact.
  79. &#34;&#34;&#34;
  80. def __init__(self, n_bins=2, dcols=[],
  81. encode=&#39;onehot&#39;, strategy=&#39;quantile&#39;,
  82. onehot_drop=&#39;if_binary&#39;):
  83. self.n_bins = n_bins
  84. self.encode = encode
  85. self.strategy = strategy
  86. self.dcols = dcols
  87. if encode == &#39;onehot&#39;:
  88. self.onehot_drop = onehot_drop
  89. def _validate_n_bins(self):
  90. &#34;&#34;&#34;
  91. Check if n_bins argument is valid.
  92. &#34;&#34;&#34;
  93. orig_bins = self.n_bins
  94. n_features = len(self.dcols_)
  95. if isinstance(orig_bins, numbers.Number):
  96. if not isinstance(orig_bins, numbers.Integral):
  97. raise ValueError(
  98. &#34;{} received an invalid n_bins type. &#34;
  99. &#34;Received {}, expected int.&#34;.format(
  100. AbstractDiscretizer.__name__, type(orig_bins).__name__
  101. )
  102. )
  103. if orig_bins &lt; 2:
  104. raise ValueError(
  105. &#34;{} received an invalid number &#34;
  106. &#34;of bins. Received {}, expected at least 2.&#34;.format(
  107. AbstractDiscretizer.__name__, orig_bins
  108. )
  109. )
  110. self.n_bins = np.full(n_features, orig_bins, dtype=int)
  111. else:
  112. n_bins = check_array(orig_bins, dtype=int,
  113. copy=True, ensure_2d=False)
  114. if n_bins.ndim &gt; 1 or n_bins.shape[0] != n_features:
  115. raise ValueError(
  116. &#34;n_bins must be a scalar or array of shape (n_features,).&#34;)
  117. bad_nbins_value = (n_bins &lt; 2) | (n_bins != orig_bins)
  118. violating_indices = np.where(bad_nbins_value)[0]
  119. if violating_indices.shape[0] &gt; 0:
  120. indices = &#34;, &#34;.join(str(i) for i in violating_indices)
  121. raise ValueError(
  122. &#34;{} received an invalid number &#34;
  123. &#34;of bins at indices {}. Number of bins &#34;
  124. &#34;must be at least 2, and must be an int.&#34;.format(
  125. AbstractDiscretizer.__name__, indices
  126. )
  127. )
  128. self.n_bins = n_bins
  129. def _validate_dcols(self, X):
  130. &#34;&#34;&#34;
  131. Check if dcols argument is valid.
  132. &#34;&#34;&#34;
  133. for col in self.dcols_:
  134. if col not in X.columns:
  135. raise ValueError(&#34;{} is not a column in X.&#34;.format(col))
  136. if not is_numeric_dtype(X[col].dtype):
  137. raise ValueError(&#34;Cannot discretize non-numeric columns.&#34;)
  138. def _validate_args(self):
  139. &#34;&#34;&#34;
  140. Check if encode, strategy arguments are valid.
  141. &#34;&#34;&#34;
  142. valid_encode = (&#39;onehot&#39;, &#39;ordinal&#39;)
  143. if self.encode not in valid_encode:
  144. raise ValueError(&#34;Valid options for &#39;encode&#39; are {}. Got encode={!r} instead.&#34;
  145. .format(valid_encode, self.encode))
  146. valid_strategy = (&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;)
  147. if (self.strategy not in valid_strategy):
  148. raise ValueError(&#34;Valid options for &#39;strategy&#39; are {}. Got strategy={!r} instead.&#34;
  149. .format(valid_strategy, self.strategy))
  150. def _discretize_to_bins(self, x, bin_edges,
  151. keep_pointwise_bins=False):
  152. &#34;&#34;&#34;
  153. Discretize data into bins of the form [a, b) given bin
  154. edges/boundaries
  155. Parameters
  156. ----------
  157. x : array-like of shape (n_samples,)
  158. Data vector to be discretized.
  159. bin_edges : array-like
  160. Values to serve as bin edges; should include min and
  161. max values for the range of x
  162. keep_pointwise_bins : boolean
  163. If True, treat duplicate bin_edges as a pointwise bin,
  164. i.e., [a, a]. If False, these bins are in effect ignored.
  165. Returns
  166. -------
  167. xd: array of shape (n_samples,) where x has been
  168. transformed to the binned space
  169. &#34;&#34;&#34;
  170. # ignore min and max values in bin generation
  171. unique_edges = np.unique(bin_edges[1:-1])
  172. if keep_pointwise_bins:
  173. # note: min and max values are used to define pointwise bins
  174. pointwise_bins = np.unique(
  175. bin_edges[pd.Series(bin_edges).duplicated()])
  176. else:
  177. pointwise_bins = np.array([])
  178. xd = np.zeros_like(x)
  179. i = 1
  180. for idx, split in enumerate(unique_edges):
  181. if idx == (len(unique_edges) - 1): # uppermost bin
  182. if (idx == 0) &amp; (split in pointwise_bins):
  183. # two bins total: (-inf, a], (a, inf)
  184. indicator = x &gt; split
  185. else:
  186. indicator = x &gt;= split # uppermost bin: [a, inf)
  187. else:
  188. if split in pointwise_bins:
  189. # create two bins: [a, a], (a, b)
  190. indicator = (x &gt; split) &amp; (x &lt; unique_edges[idx + 1]) #
  191. if idx != 0:
  192. xd[x == split] = i
  193. i += 1
  194. else:
  195. # create bin: [a, b)
  196. indicator = (x &gt;= split) &amp; (x &lt; unique_edges[idx + 1])
  197. xd[indicator] = i
  198. i += 1
  199. return xd.astype(int)
  200. def _fit_preprocessing(self, X):
  201. &#34;&#34;&#34;
  202. Initial checks before fitting the estimator.
  203. Parameters
  204. ----------
  205. X : data frame of shape (n_samples, n_features)
  206. (Training) data to be discretized.
  207. Returns
  208. -------
  209. self
  210. &#34;&#34;&#34;
  211. # by default, discretize all numeric columns
  212. if len(self.dcols) == 0:
  213. numeric_cols = [
  214. col for col in X.columns if is_numeric_dtype(X[col].dtype)]
  215. self.dcols_ = numeric_cols
  216. # error checking
  217. self._validate_n_bins()
  218. self._validate_args()
  219. self._validate_dcols(X)
  220. def _transform_postprocessing(self, discretized_df, X):
  221. &#34;&#34;&#34;
  222. Final processing in transform method. Does one-hot encoding
  223. (if specified) and joins discretized columns to the
  224. un-transformed columns in X.
  225. Parameters
  226. ----------
  227. discretized_df : data frame of shape (n_sample, len(dcols))
  228. Discretized data in the transformed bin space.
  229. X : data frame of shape (n_samples, n_features)
  230. Data to be discretized.
  231. Returns
  232. -------
  233. X_discretized : data frame
  234. Data with features in dcols transformed to the
  235. binned space. All other features remain unchanged.
  236. Encoded either as ordinal or one-hot.
  237. &#34;&#34;&#34;
  238. discretized_df = discretized_df[self.dcols_]
  239. # return onehot encoded X if specified
  240. if self.encode == &#34;onehot&#34;:
  241. colnames = [str(col) for col in self.dcols_]
  242. try:
  243. onehot_col_names = self.onehot_.get_feature_names_out(colnames)
  244. except:
  245. onehot_col_names = self.onehot_.get_feature_names(
  246. colnames) # older versions of sklearn
  247. discretized_df = self.onehot_.transform(discretized_df.astype(str))
  248. discretized_df = pd.DataFrame(discretized_df,
  249. columns=onehot_col_names,
  250. index=X.index).astype(int)
  251. # join discretized columns with rest of X
  252. cols = [col for col in X.columns if col not in self.dcols_]
  253. X_discretized = pd.concat([discretized_df, X[cols]], axis=1)
  254. return X_discretized
  255. class ExtraBasicDiscretizer(TransformerMixin):
  256. &#34;&#34;&#34;
  257. Discretize provided columns into bins and return in one-hot format.
  258. Generates meaningful column names based on bin edges.
  259. Wraps KBinsDiscretizer from sklearn.
  260. Params
  261. ------
  262. dcols : list of strings
  263. The names of the columns to be discretized.
  264. n_bins : int or array-like of shape (len(dcols),), default=4
  265. Number of bins to discretize each feature into.
  266. strategy : {&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;}, default=&#39;quantile&#39;
  267. Strategy used to define the widths of the bins.
  268. uniform
  269. All bins in each feature have identical widths.
  270. quantile
  271. All bins in each feature have the same number of points.
  272. kmeans
  273. Values in each bin have the same nearest center of a 1D
  274. k-means cluster.
  275. onehot_drop : {&#39;first&#39;, &#39;if_binary&#39;} or a array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  276. Specifies a methodology to use to drop one of the categories
  277. per feature when encode = &#34;onehot&#34;.
  278. None
  279. Retain all features (the default).
  280. &#39;first&#39;
  281. Drop the first y_str in each feature. If only one y_str
  282. is present, the feature will be dropped entirely.
  283. &#39;if_binary&#39;
  284. Drop the first y_str in each feature with two categories.
  285. Features with 1 or more than 2 categories are left intact.
  286. Attributes
  287. ----------
  288. discretizer_ : object of class KBinsDiscretizer()
  289. Primary discretization method used to bin numeric data
  290. Examples
  291. --------
  292. &#34;&#34;&#34;
  293. def __init__(self,
  294. dcols,
  295. n_bins=4,
  296. strategy=&#39;quantile&#39;,
  297. onehot_drop=&#39;if_binary&#39;):
  298. self.dcols = dcols
  299. self.n_bins = n_bins
  300. self.strategy = strategy
  301. self.onehot_drop = onehot_drop
  302. def fit(self, X, y=None):
  303. &#34;&#34;&#34;
  304. Fit the estimator.
  305. Parameters
  306. ----------
  307. X : data frame of shape (n_samples, n_features)
  308. (Training) data to be discretized.
  309. y : Ignored. This parameter exists only for compatibility with
  310. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  311. Returns
  312. -------
  313. self
  314. &#34;&#34;&#34;
  315. # Fit KBinsDiscretizer to the selected columns
  316. discretizer = KBinsDiscretizer(
  317. n_bins=self.n_bins, strategy=self.strategy, encode=&#39;ordinal&#39;)
  318. discretizer.fit(X[self.dcols])
  319. self.discretizer_ = discretizer
  320. # Fit OneHotEncoder to the ordinal output of KBinsDiscretizer
  321. disc_ordinal_np = discretizer.transform(X[self.dcols])
  322. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  323. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  324. encoder = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  325. encoder.fit(disc_ordinal_df_str)
  326. self.encoder_ = encoder
  327. return self
  328. def transform(self, X):
  329. &#34;&#34;&#34;
  330. Discretize the data.
  331. Parameters
  332. ----------
  333. X : data frame of shape (n_samples, n_features)
  334. Data to be discretized.
  335. Returns
  336. -------
  337. X_discretized : data frame
  338. Data with features in dcols transformed to the
  339. binned space. All other features remain unchanged.
  340. &#34;&#34;&#34;
  341. # Apply discretizer transform to get ordinally coded DF
  342. disc_ordinal_np = self.discretizer_.transform(X[self.dcols])
  343. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  344. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  345. # One-hot encode the ordinal DF
  346. disc_onehot_np = self.encoder_.transform(disc_ordinal_df_str)
  347. disc_onehot = pd.DataFrame(
  348. disc_onehot_np, columns=self.encoder_.get_feature_names_out())
  349. # Name columns after the interval they represent (e.g. 0.1_to_0.5)
  350. for col, bin_edges in zip(self.dcols, self.discretizer_.bin_edges_):
  351. bin_edges = bin_edges.astype(str)
  352. for ordinal_value in disc_ordinal_df_str[col].unique():
  353. bin_lb = bin_edges[int(ordinal_value)]
  354. bin_ub = bin_edges[int(ordinal_value) + 1]
  355. interval_string = f&#39;{bin_lb}_to_{bin_ub}&#39;
  356. disc_onehot = disc_onehot.rename(
  357. columns={f&#39;{col}_{ordinal_value}&#39;: f&#39;{col}_&#39; + interval_string})
  358. # Join discretized columns with rest of X
  359. non_dcols = [col for col in X.columns if col not in self.dcols]
  360. X_discretized = pd.concat([disc_onehot, X[non_dcols]], axis=1)
  361. return X_discretized
  362. class BasicDiscretizer(AbstractDiscretizer):
  363. &#34;&#34;&#34;
  364. Discretize numeric data into bins. Provides a wrapper around
  365. KBinsDiscretizer from sklearn
  366. Params
  367. ------
  368. n_bins : int or array-like of shape (len(dcols),), default=2
  369. Number of bins to discretize each feature into.
  370. dcols : list of strings
  371. The names of the columns to be discretized; by default,
  372. discretize all float and int columns in X.
  373. encode : {&#39;onehot&#39;, &#39;ordinal&#39;}, default=&#39;onehot&#39;
  374. Method used to encode the transformed result.
  375. onehot
  376. Encode the transformed result with one-hot encoding and
  377. return a dense array.
  378. ordinal
  379. Return the bin identifier encoded as an integer value.
  380. strategy : {&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;}, default=&#39;quantile&#39;
  381. Strategy used to define the widths of the bins.
  382. uniform
  383. All bins in each feature have identical widths.
  384. quantile
  385. All bins in each feature have the same number of points.
  386. kmeans
  387. Values in each bin have the same nearest center of a 1D
  388. k-means cluster.
  389. onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  390. Specifies a methodology to use to drop one of the categories
  391. per feature when encode = &#34;onehot&#34;.
  392. None
  393. Retain all features (the default).
  394. ‘first’
  395. Drop the first y_str in each feature. If only one y_str
  396. is present, the feature will be dropped entirely.
  397. ‘if_binary’
  398. Drop the first y_str in each feature with two categories.
  399. Features with 1 or more than 2 categories are left intact.
  400. Attributes
  401. ----------
  402. discretizer_ : object of class KBinsDiscretizer()
  403. Primary discretization method used to bin numeric data
  404. manual_discretizer_ : dictionary
  405. Provides bin_edges to feed into _quantile_discretization()
  406. and do quantile discretization manually for features where
  407. KBinsDiscretizer() failed. Ignored if strategy != &#39;quantile&#39;
  408. or no errors in KBinsDiscretizer().
  409. onehot_ : object of class OneHotEncoder()
  410. One hot encoding fit. Ignored if encode != &#39;onehot&#39;
  411. Examples
  412. --------
  413. &#34;&#34;&#34;
  414. def __init__(self, n_bins=2, dcols=[],
  415. encode=&#39;onehot&#39;, strategy=&#39;quantile&#39;,
  416. onehot_drop=&#39;if_binary&#39;):
  417. super().__init__(n_bins=n_bins, dcols=dcols,
  418. encode=encode, strategy=strategy,
  419. onehot_drop=onehot_drop)
  420. def fit(self, X, y=None):
  421. &#34;&#34;&#34;
  422. Fit the estimator.
  423. Parameters
  424. ----------
  425. X : data frame of shape (n_samples, n_features)
  426. (Training) data to be discretized.
  427. y : Ignored. This parameter exists only for compatibility with
  428. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  429. Returns
  430. -------
  431. self
  432. &#34;&#34;&#34;
  433. # initialization and error checking
  434. self._fit_preprocessing(X)
  435. # apply KBinsDiscretizer to the selected columns
  436. discretizer = KBinsDiscretizer(n_bins=self.n_bins,
  437. encode=&#39;ordinal&#39;,
  438. strategy=self.strategy)
  439. discretizer.fit(X[self.dcols_])
  440. self.discretizer_ = discretizer
  441. if (self.encode == &#39;onehot&#39;) | (self.strategy == &#39;quantile&#39;):
  442. discretized_df = discretizer.transform(X[self.dcols_])
  443. discretized_df = pd.DataFrame(discretized_df,
  444. columns=self.dcols_,
  445. index=X.index).astype(int)
  446. # fix KBinsDiscretizer errors if any when strategy = &#34;quantile&#34;
  447. if self.strategy == &#34;quantile&#34;:
  448. err_idx = np.where(discretized_df.nunique() != self.n_bins)[0]
  449. self.manual_discretizer_ = dict()
  450. for idx in err_idx:
  451. col = self.dcols_[idx]
  452. if X[col].nunique() &gt; 1:
  453. q_values = np.linspace(0, 1, self.n_bins[idx] + 1)
  454. bin_edges = np.quantile(X[col], q_values)
  455. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  456. keep_pointwise_bins=True)
  457. self.manual_discretizer_[col] = bin_edges
  458. # fit onehot encoded X if specified
  459. if self.encode == &#34;onehot&#34;:
  460. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  461. onehot.fit(discretized_df.astype(str))
  462. self.onehot_ = onehot
  463. return self
  464. def transform(self, X):
  465. &#34;&#34;&#34;
  466. Discretize the data.
  467. Parameters
  468. ----------
  469. X : data frame of shape (n_samples, n_features)
  470. Data to be discretized.
  471. Returns
  472. -------
  473. X_discretized : data frame
  474. Data with features in dcols transformed to the
  475. binned space. All other features remain unchanged.
  476. &#34;&#34;&#34;
  477. check_is_fitted(self)
  478. # transform using KBinsDiscretizer
  479. discretized_df = self.discretizer_.transform(
  480. X[self.dcols_]).astype(int)
  481. discretized_df = pd.DataFrame(discretized_df,
  482. columns=self.dcols_,
  483. index=X.index)
  484. # fix KBinsDiscretizer errors (if any) when strategy = &#34;quantile&#34;
  485. if self.strategy == &#34;quantile&#34;:
  486. for col in self.manual_discretizer_.keys():
  487. bin_edges = self.manual_discretizer_[col]
  488. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  489. keep_pointwise_bins=True)
  490. # return onehot encoded data if specified and
  491. # join discretized columns with rest of X
  492. X_discretized = self._transform_postprocessing(discretized_df, X)
  493. return X_discretized
  494. class RFDiscretizer(AbstractDiscretizer):
  495. &#34;&#34;&#34;
  496. Discretize numeric data into bins using RF splits.
  497. Parameters
  498. ----------
  499. rf_model : RandomForestClassifer() or RandomForestRegressor()
  500. RF model from which to extract splits for discretization.
  501. Default is RandomForestClassifer(n_estimators = 500) or
  502. RandomForestRegressor(n_estimators = 500)
  503. classification : boolean; default=False
  504. Used only if rf_model=None. If True,
  505. rf_model=RandomForestClassifier(n_estimators = 500).
  506. Else, rf_model=RandomForestRegressor(n_estimators = 500)
  507. n_bins : int or array-like of shape (len(dcols),), default=2
  508. Number of bins to discretize each feature into.
  509. dcols : list of strings
  510. The names of the columns to be discretized; by default,
  511. discretize all float and int columns in X.
  512. encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  513. Method used to encode the transformed result.
  514. onehot - Encode the transformed result with one-hot encoding and
  515. return a dense array.
  516. ordinal - Return the bin identifier encoded as an integer value.
  517. strategy : {‘uniform’, ‘quantile’}, default=’quantile’
  518. Strategy used to choose RF split points.
  519. uniform - RF split points chosen to be uniformly spaced out.
  520. quantile - RF split points chosen based on equally-spaced quantiles.
  521. backup_strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  522. Strategy used to define the widths of the bins if no rf splits exist for
  523. that feature. Used in KBinsDiscretizer.
  524. uniform
  525. All bins in each feature have identical widths.
  526. quantile
  527. All bins in each feature have the same number of points.
  528. kmeans
  529. Values in each bin have the same nearest center of a 1D
  530. k-means cluster.
  531. onehot_drop : {‘first’, ‘if_binary’} or array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  532. Specifies a methodology to use to drop one of the categories
  533. per feature when encode = &#34;onehot&#34;.
  534. None
  535. Retain all features (the default).
  536. ‘first’
  537. Drop the first y_str in each feature. If only one y_str
  538. is present, the feature will be dropped entirely.
  539. ‘if_binary’
  540. Drop the first y_str in each feature with two categories.
  541. Features with 1 or more than 2 categories are left intact.
  542. Attributes
  543. ----------
  544. rf_splits : dictionary where
  545. key = feature name
  546. value = array of all RF split threshold values
  547. bin_edges_ : dictionary where
  548. key = feature name
  549. value = array of bin edges used for discretization, taken from
  550. RF split values
  551. missing_rf_cols_ : array-like
  552. List of features that were not used in RF
  553. backup_discretizer_ : object of class BasicDiscretizer()
  554. Discretization method used to bin numeric data for features
  555. in missing_rf_cols_
  556. onehot_ : object of class OneHotEncoder()
  557. One hot encoding fit. Ignored if encode != &#39;onehot&#39;
  558. &#34;&#34;&#34;
  559. def __init__(self, rf_model=None, classification=False,
  560. n_bins=2, dcols=[], encode=&#39;onehot&#39;,
  561. strategy=&#39;quantile&#39;, backup_strategy=&#39;quantile&#39;,
  562. onehot_drop=&#39;if_binary&#39;):
  563. super().__init__(n_bins=n_bins, dcols=dcols,
  564. encode=encode, strategy=strategy,
  565. onehot_drop=onehot_drop)
  566. self.backup_strategy = backup_strategy
  567. self.rf_model = rf_model
  568. if rf_model is None:
  569. self.classification = classification
  570. def _validate_args(self):
  571. &#34;&#34;&#34;
  572. Check if encode, strategy, backup_strategy arguments are valid.
  573. &#34;&#34;&#34;
  574. super()._validate_args()
  575. valid_backup_strategy = (&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;)
  576. if (self.backup_strategy not in valid_backup_strategy):
  577. raise ValueError(&#34;Valid options for &#39;strategy&#39; are {}. Got strategy={!r} instead.&#34;
  578. .format(valid_backup_strategy, self.backup_strategy))
  579. def _get_rf_splits(self, col_names):
  580. &#34;&#34;&#34;
  581. Get all splits in random forest ensemble
  582. Parameters
  583. ----------
  584. col_names : array-like of shape (n_features,)
  585. Column names for X used to train rf_model
  586. Returns
  587. -------
  588. rule_dict : dictionary where
  589. key = feature name
  590. value = array of all RF split threshold values
  591. &#34;&#34;&#34;
  592. rule_dict = {}
  593. for model in self.rf_model.estimators_:
  594. tree = model.tree_
  595. tree_it = enumerate(zip(tree.children_left,
  596. tree.children_right,
  597. tree.feature,
  598. tree.threshold))
  599. for node_idx, data in tree_it:
  600. left, right, feature, th = data
  601. if (left != -1) | (right != -1):
  602. feature = col_names[feature]
  603. if feature in rule_dict:
  604. rule_dict[feature].append(th)
  605. else:
  606. rule_dict[feature] = [th]
  607. return rule_dict
  608. def _fit_rf(self, X, y=None):
  609. &#34;&#34;&#34;
  610. Fit random forest (if necessary) and obtain RF split thresholds
  611. Parameters
  612. ----------
  613. X : data frame of shape (n_samples, n_features)
  614. Training data used to fit RF
  615. y : array-like of shape (n_samples,)
  616. Training response vector used to fit RF
  617. Returns
  618. -------
  619. rf_splits : dictionary where
  620. key = feature name
  621. value = array of all RF split threshold values
  622. &#34;&#34;&#34;
  623. # If no rf_model given, train default random forest model
  624. if self.rf_model is None:
  625. if y is None:
  626. raise ValueError(&#34;Must provide y if rf_model is not given.&#34;)
  627. if self.classification:
  628. self.rf_model = RandomForestClassifier(n_estimators=500)
  629. else:
  630. self.rf_model = RandomForestRegressor(n_estimators=500)
  631. self.rf_model.fit(X, y)
  632. else:
  633. # provided rf model has not yet been trained
  634. if not check_is_fitted(self.rf_model):
  635. if y is None:
  636. raise ValueError(
  637. &#34;Must provide y if rf_model has not been trained.&#34;)
  638. self.rf_model.fit(X, y)
  639. # get all random forest split points
  640. self.rf_splits = self._get_rf_splits(list(X.columns))
  641. def reweight_n_bins(self, X, y=None, by=&#34;nsplits&#34;):
  642. &#34;&#34;&#34;
  643. Reallocate number of bins per feature.
  644. Parameters
  645. ----------
  646. X : data frame of shape (n_samples, n_features)
  647. (Training) data to be discretized.
  648. y : array-like of shape (n_samples,)
  649. (Training) response vector. Required only if
  650. rf_model = None or rf_model has not yet been fitted
  651. by : {&#39;nsplits&#39;}, default=&#39;nsplits&#39;
  652. Specifies how to reallocate number of bins per feature.
  653. nsplits
  654. Reallocate number of bins so that each feature
  655. in dcols get at a minimum of 2 bins with the
  656. remaining bins distributed proportionally to the
  657. number of RF splits using that feature
  658. Returns
  659. -------
  660. self.n_bins : array of shape (len(dcols),)
  661. number of bins per feature reallocated according to
  662. &#39;by&#39; argument
  663. &#34;&#34;&#34;
  664. # initialization and error checking
  665. self._fit_preprocessing(X)
  666. # get all random forest split points
  667. self._fit_rf(X=X, y=y)
  668. # get total number of bins to reallocate
  669. total_bins = self.n_bins.sum()
  670. # reweight n_bins
  671. if by == &#34;nsplits&#34;:
  672. # each col gets at least 2 bins; remaining bins get
  673. # reallocated based on number of RF splits using that feature
  674. n_rules = np.array([len(self.rf_splits[col])
  675. for col in self.dcols_])
  676. self.n_bins = np.round(n_rules / n_rules.sum() *
  677. (total_bins - 2 * len(self.dcols_))) + 2
  678. else:
  679. valid_by = (&#39;nsplits&#39;)
  680. raise ValueError(&#34;Valid options for &#39;by&#39; are {}. Got by={!r} instead.&#34;
  681. .format(valid_by, by))
  682. def fit(self, X, y=None):
  683. &#34;&#34;&#34;
  684. Fit the estimator.
  685. Parameters
  686. ----------
  687. X : data frame of shape (n_samples, n_features)
  688. (Training) data to be discretized.
  689. y : array-like of shape (n_samples,)
  690. (Training) response vector. Required only if
  691. rf_model = None or rf_model has not yet been fitted
  692. Returns
  693. -------
  694. self
  695. &#34;&#34;&#34;
  696. # initialization and error checking
  697. self._fit_preprocessing(X)
  698. # get all random forest split points
  699. self._fit_rf(X=X, y=y)
  700. # features that were not used in the rf but need to be discretized
  701. self.missing_rf_cols_ = list(set(self.dcols_) -
  702. set(self.rf_splits.keys()))
  703. if len(self.missing_rf_cols_) &gt; 0:
  704. print(&#34;{} did not appear in random forest so were discretized via {} discretization&#34;
  705. .format(self.missing_rf_cols_, self.strategy))
  706. missing_n_bins = np.array([self.n_bins[np.array(self.dcols_) == col][0]
  707. for col in self.missing_rf_cols_])
  708. backup_discretizer = BasicDiscretizer(n_bins=missing_n_bins,
  709. dcols=self.missing_rf_cols_,
  710. encode=&#39;ordinal&#39;,
  711. strategy=self.backup_strategy)
  712. backup_discretizer.fit(X[self.missing_rf_cols_])
  713. self.backup_discretizer_ = backup_discretizer
  714. else:
  715. self.backup_discretizer_ = None
  716. if self.encode == &#39;onehot&#39;:
  717. if len(self.missing_rf_cols_) &gt; 0:
  718. discretized_df = backup_discretizer.transform(
  719. X[self.missing_rf_cols_])
  720. else:
  721. discretized_df = pd.DataFrame({}, index=X.index)
  722. # do discretization based on rf split thresholds
  723. self.bin_edges_ = dict()
  724. for col in self.dcols_:
  725. if col in self.rf_splits.keys():
  726. b = self.n_bins[np.array(self.dcols_) == col]
  727. if self.strategy == &#34;quantile&#34;:
  728. q_values = np.linspace(0, 1, int(b) + 1)
  729. bin_edges = np.quantile(self.rf_splits[col], q_values)
  730. elif self.strategy == &#34;uniform&#34;:
  731. width = (max(self.rf_splits[col]) -
  732. min(self.rf_splits[col])) / b
  733. bin_edges = width * \
  734. np.arange(0, b + 1) + min(self.rf_splits[col])
  735. self.bin_edges_[col] = bin_edges
  736. if self.encode == &#39;onehot&#39;:
  737. discretized_df[col] = self._discretize_to_bins(
  738. X[col], bin_edges)
  739. # fit onehot encoded X if specified
  740. if self.encode == &#34;onehot&#34;:
  741. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  742. onehot.fit(discretized_df[self.dcols_].astype(str))
  743. self.onehot_ = onehot
  744. return self
  745. def transform(self, X):
  746. &#34;&#34;&#34;
  747. Discretize the data.
  748. Parameters
  749. ----------
  750. X : data frame of shape (n_samples, n_features)
  751. Data to be discretized.
  752. Returns
  753. -------
  754. X_discretized : data frame
  755. Data with features in dcols transformed to the
  756. binned space. All other features remain unchanged.
  757. &#34;&#34;&#34;
  758. check_is_fitted(self)
  759. # transform features that did not appear in RF
  760. if len(self.missing_rf_cols_) &gt; 0:
  761. discretized_df = self.backup_discretizer_.transform(
  762. X[self.missing_rf_cols_])
  763. discretized_df = pd.DataFrame(discretized_df,
  764. columns=self.missing_rf_cols_,
  765. index=X.index)
  766. else:
  767. discretized_df = pd.DataFrame({}, index=X.index)
  768. # do discretization based on rf split thresholds
  769. for col in self.bin_edges_.keys():
  770. discretized_df[col] = self._discretize_to_bins(
  771. X[col], self.bin_edges_[col])
  772. # return onehot encoded data if specified and
  773. # join discretized columns with rest of X
  774. X_discretized = self._transform_postprocessing(discretized_df, X)
  775. return X_discretized</code></pre>
  776. </details>
  777. </section>
  778. <section>
  779. </section>
  780. <section>
  781. </section>
  782. <section>
  783. </section>
  784. <section>
  785. <h2 class="section-title" id="header-classes">Classes</h2>
  786. <dl>
  787. <dt id="imodels.discretization.discretizer.AbstractDiscretizer"><code class="flex name class">
  788. <span>class <span class="ident">AbstractDiscretizer</span></span>
  789. <span>(</span><span>n_bins=2, dcols=[], encode='onehot', strategy='quantile', onehot_drop='if_binary')</span>
  790. </code></dt>
  791. <dd>
  792. <div class="desc"><p>Discretize numeric data into bins. Base class.</p>
  793. <h2 id="params">Params</h2>
  794. <p>n_bins : int or array-like of shape (len(dcols),), default=2
  795. Number of bins to discretize each feature into.</p>
  796. <p>dcols : list of strings
  797. The names of the columns to be discretized; by default,
  798. discretize all float and int columns in X.</p>
  799. <p>encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  800. Method used to encode the transformed result.</p>
  801. <pre><code>onehot
  802. Encode the transformed result with one-hot encoding and
  803. return a dense array.
  804. ordinal
  805. Return the bin identifier encoded as an integer value.
  806. </code></pre>
  807. <p>strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  808. Strategy used to define the widths of the bins.</p>
  809. <pre><code>uniform
  810. All bins in each feature have identical widths.
  811. quantile
  812. All bins in each feature have the same number of points.
  813. kmeans
  814. Values in each bin have the same nearest center of a 1D
  815. k-means cluster.
  816. </code></pre>
  817. <p>onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default='if_binary'
  818. Specifies a methodology to use to drop one of the categories
  819. per feature when encode = "onehot".</p>
  820. <pre><code>None
  821. Retain all features (the default).
  822. ‘first’
  823. Drop the first y_str in each feature. If only one y_str
  824. is present, the feature will be dropped entirely.
  825. ‘if_binary’
  826. Drop the first y_str in each feature with two categories.
  827. Features with 1 or more than 2 categories are left intact.
  828. </code></pre></div>
  829. <details class="source">
  830. <summary>
  831. <span>Expand source code</span>
  832. </summary>
  833. <pre><code class="python">class AbstractDiscretizer(TransformerMixin, BaseEstimator):
  834. &#34;&#34;&#34;
  835. Discretize numeric data into bins. Base class.
  836. Params
  837. ------
  838. n_bins : int or array-like of shape (len(dcols),), default=2
  839. Number of bins to discretize each feature into.
  840. dcols : list of strings
  841. The names of the columns to be discretized; by default,
  842. discretize all float and int columns in X.
  843. encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  844. Method used to encode the transformed result.
  845. onehot
  846. Encode the transformed result with one-hot encoding and
  847. return a dense array.
  848. ordinal
  849. Return the bin identifier encoded as an integer value.
  850. strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  851. Strategy used to define the widths of the bins.
  852. uniform
  853. All bins in each feature have identical widths.
  854. quantile
  855. All bins in each feature have the same number of points.
  856. kmeans
  857. Values in each bin have the same nearest center of a 1D
  858. k-means cluster.
  859. onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  860. Specifies a methodology to use to drop one of the categories
  861. per feature when encode = &#34;onehot&#34;.
  862. None
  863. Retain all features (the default).
  864. ‘first’
  865. Drop the first y_str in each feature. If only one y_str
  866. is present, the feature will be dropped entirely.
  867. ‘if_binary’
  868. Drop the first y_str in each feature with two categories.
  869. Features with 1 or more than 2 categories are left intact.
  870. &#34;&#34;&#34;
  871. def __init__(self, n_bins=2, dcols=[],
  872. encode=&#39;onehot&#39;, strategy=&#39;quantile&#39;,
  873. onehot_drop=&#39;if_binary&#39;):
  874. self.n_bins = n_bins
  875. self.encode = encode
  876. self.strategy = strategy
  877. self.dcols = dcols
  878. if encode == &#39;onehot&#39;:
  879. self.onehot_drop = onehot_drop
  880. def _validate_n_bins(self):
  881. &#34;&#34;&#34;
  882. Check if n_bins argument is valid.
  883. &#34;&#34;&#34;
  884. orig_bins = self.n_bins
  885. n_features = len(self.dcols_)
  886. if isinstance(orig_bins, numbers.Number):
  887. if not isinstance(orig_bins, numbers.Integral):
  888. raise ValueError(
  889. &#34;{} received an invalid n_bins type. &#34;
  890. &#34;Received {}, expected int.&#34;.format(
  891. AbstractDiscretizer.__name__, type(orig_bins).__name__
  892. )
  893. )
  894. if orig_bins &lt; 2:
  895. raise ValueError(
  896. &#34;{} received an invalid number &#34;
  897. &#34;of bins. Received {}, expected at least 2.&#34;.format(
  898. AbstractDiscretizer.__name__, orig_bins
  899. )
  900. )
  901. self.n_bins = np.full(n_features, orig_bins, dtype=int)
  902. else:
  903. n_bins = check_array(orig_bins, dtype=int,
  904. copy=True, ensure_2d=False)
  905. if n_bins.ndim &gt; 1 or n_bins.shape[0] != n_features:
  906. raise ValueError(
  907. &#34;n_bins must be a scalar or array of shape (n_features,).&#34;)
  908. bad_nbins_value = (n_bins &lt; 2) | (n_bins != orig_bins)
  909. violating_indices = np.where(bad_nbins_value)[0]
  910. if violating_indices.shape[0] &gt; 0:
  911. indices = &#34;, &#34;.join(str(i) for i in violating_indices)
  912. raise ValueError(
  913. &#34;{} received an invalid number &#34;
  914. &#34;of bins at indices {}. Number of bins &#34;
  915. &#34;must be at least 2, and must be an int.&#34;.format(
  916. AbstractDiscretizer.__name__, indices
  917. )
  918. )
  919. self.n_bins = n_bins
  920. def _validate_dcols(self, X):
  921. &#34;&#34;&#34;
  922. Check if dcols argument is valid.
  923. &#34;&#34;&#34;
  924. for col in self.dcols_:
  925. if col not in X.columns:
  926. raise ValueError(&#34;{} is not a column in X.&#34;.format(col))
  927. if not is_numeric_dtype(X[col].dtype):
  928. raise ValueError(&#34;Cannot discretize non-numeric columns.&#34;)
  929. def _validate_args(self):
  930. &#34;&#34;&#34;
  931. Check if encode, strategy arguments are valid.
  932. &#34;&#34;&#34;
  933. valid_encode = (&#39;onehot&#39;, &#39;ordinal&#39;)
  934. if self.encode not in valid_encode:
  935. raise ValueError(&#34;Valid options for &#39;encode&#39; are {}. Got encode={!r} instead.&#34;
  936. .format(valid_encode, self.encode))
  937. valid_strategy = (&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;)
  938. if (self.strategy not in valid_strategy):
  939. raise ValueError(&#34;Valid options for &#39;strategy&#39; are {}. Got strategy={!r} instead.&#34;
  940. .format(valid_strategy, self.strategy))
  941. def _discretize_to_bins(self, x, bin_edges,
  942. keep_pointwise_bins=False):
  943. &#34;&#34;&#34;
  944. Discretize data into bins of the form [a, b) given bin
  945. edges/boundaries
  946. Parameters
  947. ----------
  948. x : array-like of shape (n_samples,)
  949. Data vector to be discretized.
  950. bin_edges : array-like
  951. Values to serve as bin edges; should include min and
  952. max values for the range of x
  953. keep_pointwise_bins : boolean
  954. If True, treat duplicate bin_edges as a pointwise bin,
  955. i.e., [a, a]. If False, these bins are in effect ignored.
  956. Returns
  957. -------
  958. xd: array of shape (n_samples,) where x has been
  959. transformed to the binned space
  960. &#34;&#34;&#34;
  961. # ignore min and max values in bin generation
  962. unique_edges = np.unique(bin_edges[1:-1])
  963. if keep_pointwise_bins:
  964. # note: min and max values are used to define pointwise bins
  965. pointwise_bins = np.unique(
  966. bin_edges[pd.Series(bin_edges).duplicated()])
  967. else:
  968. pointwise_bins = np.array([])
  969. xd = np.zeros_like(x)
  970. i = 1
  971. for idx, split in enumerate(unique_edges):
  972. if idx == (len(unique_edges) - 1): # uppermost bin
  973. if (idx == 0) &amp; (split in pointwise_bins):
  974. # two bins total: (-inf, a], (a, inf)
  975. indicator = x &gt; split
  976. else:
  977. indicator = x &gt;= split # uppermost bin: [a, inf)
  978. else:
  979. if split in pointwise_bins:
  980. # create two bins: [a, a], (a, b)
  981. indicator = (x &gt; split) &amp; (x &lt; unique_edges[idx + 1]) #
  982. if idx != 0:
  983. xd[x == split] = i
  984. i += 1
  985. else:
  986. # create bin: [a, b)
  987. indicator = (x &gt;= split) &amp; (x &lt; unique_edges[idx + 1])
  988. xd[indicator] = i
  989. i += 1
  990. return xd.astype(int)
  991. def _fit_preprocessing(self, X):
  992. &#34;&#34;&#34;
  993. Initial checks before fitting the estimator.
  994. Parameters
  995. ----------
  996. X : data frame of shape (n_samples, n_features)
  997. (Training) data to be discretized.
  998. Returns
  999. -------
  1000. self
  1001. &#34;&#34;&#34;
  1002. # by default, discretize all numeric columns
  1003. if len(self.dcols) == 0:
  1004. numeric_cols = [
  1005. col for col in X.columns if is_numeric_dtype(X[col].dtype)]
  1006. self.dcols_ = numeric_cols
  1007. # error checking
  1008. self._validate_n_bins()
  1009. self._validate_args()
  1010. self._validate_dcols(X)
  1011. def _transform_postprocessing(self, discretized_df, X):
  1012. &#34;&#34;&#34;
  1013. Final processing in transform method. Does one-hot encoding
  1014. (if specified) and joins discretized columns to the
  1015. un-transformed columns in X.
  1016. Parameters
  1017. ----------
  1018. discretized_df : data frame of shape (n_sample, len(dcols))
  1019. Discretized data in the transformed bin space.
  1020. X : data frame of shape (n_samples, n_features)
  1021. Data to be discretized.
  1022. Returns
  1023. -------
  1024. X_discretized : data frame
  1025. Data with features in dcols transformed to the
  1026. binned space. All other features remain unchanged.
  1027. Encoded either as ordinal or one-hot.
  1028. &#34;&#34;&#34;
  1029. discretized_df = discretized_df[self.dcols_]
  1030. # return onehot encoded X if specified
  1031. if self.encode == &#34;onehot&#34;:
  1032. colnames = [str(col) for col in self.dcols_]
  1033. try:
  1034. onehot_col_names = self.onehot_.get_feature_names_out(colnames)
  1035. except:
  1036. onehot_col_names = self.onehot_.get_feature_names(
  1037. colnames) # older versions of sklearn
  1038. discretized_df = self.onehot_.transform(discretized_df.astype(str))
  1039. discretized_df = pd.DataFrame(discretized_df,
  1040. columns=onehot_col_names,
  1041. index=X.index).astype(int)
  1042. # join discretized columns with rest of X
  1043. cols = [col for col in X.columns if col not in self.dcols_]
  1044. X_discretized = pd.concat([discretized_df, X[cols]], axis=1)
  1045. return X_discretized</code></pre>
  1046. </details>
  1047. <h3>Ancestors</h3>
  1048. <ul class="hlist">
  1049. <li>sklearn.base.TransformerMixin</li>
  1050. <li>sklearn.utils._set_output._SetOutputMixin</li>
  1051. <li>sklearn.base.BaseEstimator</li>
  1052. <li>sklearn.utils._estimator_html_repr._HTMLDocumentationLinkMixin</li>
  1053. <li>sklearn.utils._metadata_requests._MetadataRequester</li>
  1054. </ul>
  1055. <h3>Subclasses</h3>
  1056. <ul class="hlist">
  1057. <li><a title="imodels.discretization.discretizer.BasicDiscretizer" href="#imodels.discretization.discretizer.BasicDiscretizer">BasicDiscretizer</a></li>
  1058. <li><a title="imodels.discretization.discretizer.RFDiscretizer" href="#imodels.discretization.discretizer.RFDiscretizer">RFDiscretizer</a></li>
  1059. </ul>
  1060. </dd>
  1061. <dt id="imodels.discretization.discretizer.BasicDiscretizer"><code class="flex name class">
  1062. <span>class <span class="ident">BasicDiscretizer</span></span>
  1063. <span>(</span><span>n_bins=2, dcols=[], encode='onehot', strategy='quantile', onehot_drop='if_binary')</span>
  1064. </code></dt>
  1065. <dd>
  1066. <div class="desc"><p>Discretize numeric data into bins. Provides a wrapper around
  1067. KBinsDiscretizer from sklearn</p>
  1068. <h2 id="params">Params</h2>
  1069. <p>n_bins : int or array-like of shape (len(dcols),), default=2
  1070. Number of bins to discretize each feature into.</p>
  1071. <p>dcols : list of strings
  1072. The names of the columns to be discretized; by default,
  1073. discretize all float and int columns in X.</p>
  1074. <p>encode : {'onehot', 'ordinal'}, default='onehot'
  1075. Method used to encode the transformed result.</p>
  1076. <pre><code>onehot
  1077. Encode the transformed result with one-hot encoding and
  1078. return a dense array.
  1079. ordinal
  1080. Return the bin identifier encoded as an integer value.
  1081. </code></pre>
  1082. <p>strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile'
  1083. Strategy used to define the widths of the bins.</p>
  1084. <pre><code>uniform
  1085. All bins in each feature have identical widths.
  1086. quantile
  1087. All bins in each feature have the same number of points.
  1088. kmeans
  1089. Values in each bin have the same nearest center of a 1D
  1090. k-means cluster.
  1091. </code></pre>
  1092. <p>onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape
  1093. (len(dcols),), default='if_binary'
  1094. Specifies a methodology to use to drop one of the categories
  1095. per feature when encode = "onehot".</p>
  1096. <pre><code>None
  1097. Retain all features (the default).
  1098. ‘first’
  1099. Drop the first y_str in each feature. If only one y_str
  1100. is present, the feature will be dropped entirely.
  1101. ‘if_binary’
  1102. Drop the first y_str in each feature with two categories.
  1103. Features with 1 or more than 2 categories are left intact.
  1104. </code></pre>
  1105. <h2 id="attributes">Attributes</h2>
  1106. <dl>
  1107. <dt><strong><code>discretizer_</code></strong> :&ensp;<code>object</code> of <code>class KBinsDiscretizer()</code></dt>
  1108. <dd>Primary discretization method used to bin numeric data</dd>
  1109. <dt><strong><code>manual_discretizer_</code></strong> :&ensp;<code>dictionary</code></dt>
  1110. <dd>Provides bin_edges to feed into _quantile_discretization()
  1111. and do quantile discretization manually for features where
  1112. KBinsDiscretizer() failed. Ignored if strategy != 'quantile'
  1113. or no errors in KBinsDiscretizer().</dd>
  1114. <dt><strong><code>onehot_</code></strong> :&ensp;<code>object</code> of <code>class OneHotEncoder()</code></dt>
  1115. <dd>One hot encoding fit. Ignored if encode != 'onehot'</dd>
  1116. </dl>
  1117. <h2 id="examples">Examples</h2></div>
  1118. <details class="source">
  1119. <summary>
  1120. <span>Expand source code</span>
  1121. </summary>
  1122. <pre><code class="python">class BasicDiscretizer(AbstractDiscretizer):
  1123. &#34;&#34;&#34;
  1124. Discretize numeric data into bins. Provides a wrapper around
  1125. KBinsDiscretizer from sklearn
  1126. Params
  1127. ------
  1128. n_bins : int or array-like of shape (len(dcols),), default=2
  1129. Number of bins to discretize each feature into.
  1130. dcols : list of strings
  1131. The names of the columns to be discretized; by default,
  1132. discretize all float and int columns in X.
  1133. encode : {&#39;onehot&#39;, &#39;ordinal&#39;}, default=&#39;onehot&#39;
  1134. Method used to encode the transformed result.
  1135. onehot
  1136. Encode the transformed result with one-hot encoding and
  1137. return a dense array.
  1138. ordinal
  1139. Return the bin identifier encoded as an integer value.
  1140. strategy : {&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;}, default=&#39;quantile&#39;
  1141. Strategy used to define the widths of the bins.
  1142. uniform
  1143. All bins in each feature have identical widths.
  1144. quantile
  1145. All bins in each feature have the same number of points.
  1146. kmeans
  1147. Values in each bin have the same nearest center of a 1D
  1148. k-means cluster.
  1149. onehot_drop : {‘first’, ‘if_binary’} or a array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  1150. Specifies a methodology to use to drop one of the categories
  1151. per feature when encode = &#34;onehot&#34;.
  1152. None
  1153. Retain all features (the default).
  1154. ‘first’
  1155. Drop the first y_str in each feature. If only one y_str
  1156. is present, the feature will be dropped entirely.
  1157. ‘if_binary’
  1158. Drop the first y_str in each feature with two categories.
  1159. Features with 1 or more than 2 categories are left intact.
  1160. Attributes
  1161. ----------
  1162. discretizer_ : object of class KBinsDiscretizer()
  1163. Primary discretization method used to bin numeric data
  1164. manual_discretizer_ : dictionary
  1165. Provides bin_edges to feed into _quantile_discretization()
  1166. and do quantile discretization manually for features where
  1167. KBinsDiscretizer() failed. Ignored if strategy != &#39;quantile&#39;
  1168. or no errors in KBinsDiscretizer().
  1169. onehot_ : object of class OneHotEncoder()
  1170. One hot encoding fit. Ignored if encode != &#39;onehot&#39;
  1171. Examples
  1172. --------
  1173. &#34;&#34;&#34;
  1174. def __init__(self, n_bins=2, dcols=[],
  1175. encode=&#39;onehot&#39;, strategy=&#39;quantile&#39;,
  1176. onehot_drop=&#39;if_binary&#39;):
  1177. super().__init__(n_bins=n_bins, dcols=dcols,
  1178. encode=encode, strategy=strategy,
  1179. onehot_drop=onehot_drop)
  1180. def fit(self, X, y=None):
  1181. &#34;&#34;&#34;
  1182. Fit the estimator.
  1183. Parameters
  1184. ----------
  1185. X : data frame of shape (n_samples, n_features)
  1186. (Training) data to be discretized.
  1187. y : Ignored. This parameter exists only for compatibility with
  1188. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  1189. Returns
  1190. -------
  1191. self
  1192. &#34;&#34;&#34;
  1193. # initialization and error checking
  1194. self._fit_preprocessing(X)
  1195. # apply KBinsDiscretizer to the selected columns
  1196. discretizer = KBinsDiscretizer(n_bins=self.n_bins,
  1197. encode=&#39;ordinal&#39;,
  1198. strategy=self.strategy)
  1199. discretizer.fit(X[self.dcols_])
  1200. self.discretizer_ = discretizer
  1201. if (self.encode == &#39;onehot&#39;) | (self.strategy == &#39;quantile&#39;):
  1202. discretized_df = discretizer.transform(X[self.dcols_])
  1203. discretized_df = pd.DataFrame(discretized_df,
  1204. columns=self.dcols_,
  1205. index=X.index).astype(int)
  1206. # fix KBinsDiscretizer errors if any when strategy = &#34;quantile&#34;
  1207. if self.strategy == &#34;quantile&#34;:
  1208. err_idx = np.where(discretized_df.nunique() != self.n_bins)[0]
  1209. self.manual_discretizer_ = dict()
  1210. for idx in err_idx:
  1211. col = self.dcols_[idx]
  1212. if X[col].nunique() &gt; 1:
  1213. q_values = np.linspace(0, 1, self.n_bins[idx] + 1)
  1214. bin_edges = np.quantile(X[col], q_values)
  1215. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  1216. keep_pointwise_bins=True)
  1217. self.manual_discretizer_[col] = bin_edges
  1218. # fit onehot encoded X if specified
  1219. if self.encode == &#34;onehot&#34;:
  1220. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  1221. onehot.fit(discretized_df.astype(str))
  1222. self.onehot_ = onehot
  1223. return self
  1224. def transform(self, X):
  1225. &#34;&#34;&#34;
  1226. Discretize the data.
  1227. Parameters
  1228. ----------
  1229. X : data frame of shape (n_samples, n_features)
  1230. Data to be discretized.
  1231. Returns
  1232. -------
  1233. X_discretized : data frame
  1234. Data with features in dcols transformed to the
  1235. binned space. All other features remain unchanged.
  1236. &#34;&#34;&#34;
  1237. check_is_fitted(self)
  1238. # transform using KBinsDiscretizer
  1239. discretized_df = self.discretizer_.transform(
  1240. X[self.dcols_]).astype(int)
  1241. discretized_df = pd.DataFrame(discretized_df,
  1242. columns=self.dcols_,
  1243. index=X.index)
  1244. # fix KBinsDiscretizer errors (if any) when strategy = &#34;quantile&#34;
  1245. if self.strategy == &#34;quantile&#34;:
  1246. for col in self.manual_discretizer_.keys():
  1247. bin_edges = self.manual_discretizer_[col]
  1248. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  1249. keep_pointwise_bins=True)
  1250. # return onehot encoded data if specified and
  1251. # join discretized columns with rest of X
  1252. X_discretized = self._transform_postprocessing(discretized_df, X)
  1253. return X_discretized</code></pre>
  1254. </details>
  1255. <h3>Ancestors</h3>
  1256. <ul class="hlist">
  1257. <li><a title="imodels.discretization.discretizer.AbstractDiscretizer" href="#imodels.discretization.discretizer.AbstractDiscretizer">AbstractDiscretizer</a></li>
  1258. <li>sklearn.base.TransformerMixin</li>
  1259. <li>sklearn.utils._set_output._SetOutputMixin</li>
  1260. <li>sklearn.base.BaseEstimator</li>
  1261. <li>sklearn.utils._estimator_html_repr._HTMLDocumentationLinkMixin</li>
  1262. <li>sklearn.utils._metadata_requests._MetadataRequester</li>
  1263. </ul>
  1264. <h3>Methods</h3>
  1265. <dl>
  1266. <dt id="imodels.discretization.discretizer.BasicDiscretizer.fit"><code class="name flex">
  1267. <span>def <span class="ident">fit</span></span>(<span>self, X, y=None)</span>
  1268. </code></dt>
  1269. <dd>
  1270. <div class="desc"><p>Fit the estimator.</p>
  1271. <h2 id="parameters">Parameters</h2>
  1272. <dl>
  1273. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  1274. <dd>(Training) data to be discretized.</dd>
  1275. <dt><strong><code>y</code></strong> :&ensp;<code>Ignored. This parameter exists only for compatibility with</code></dt>
  1276. <dd>:class:<code>~sklearn.pipeline.Pipeline</code> and fit_transform method</dd>
  1277. </dl>
  1278. <h2 id="returns">Returns</h2>
  1279. <dl>
  1280. <dt><code>self</code></dt>
  1281. <dd>&nbsp;</dd>
  1282. </dl></div>
  1283. <details class="source">
  1284. <summary>
  1285. <span>Expand source code</span>
  1286. </summary>
  1287. <pre><code class="python">def fit(self, X, y=None):
  1288. &#34;&#34;&#34;
  1289. Fit the estimator.
  1290. Parameters
  1291. ----------
  1292. X : data frame of shape (n_samples, n_features)
  1293. (Training) data to be discretized.
  1294. y : Ignored. This parameter exists only for compatibility with
  1295. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  1296. Returns
  1297. -------
  1298. self
  1299. &#34;&#34;&#34;
  1300. # initialization and error checking
  1301. self._fit_preprocessing(X)
  1302. # apply KBinsDiscretizer to the selected columns
  1303. discretizer = KBinsDiscretizer(n_bins=self.n_bins,
  1304. encode=&#39;ordinal&#39;,
  1305. strategy=self.strategy)
  1306. discretizer.fit(X[self.dcols_])
  1307. self.discretizer_ = discretizer
  1308. if (self.encode == &#39;onehot&#39;) | (self.strategy == &#39;quantile&#39;):
  1309. discretized_df = discretizer.transform(X[self.dcols_])
  1310. discretized_df = pd.DataFrame(discretized_df,
  1311. columns=self.dcols_,
  1312. index=X.index).astype(int)
  1313. # fix KBinsDiscretizer errors if any when strategy = &#34;quantile&#34;
  1314. if self.strategy == &#34;quantile&#34;:
  1315. err_idx = np.where(discretized_df.nunique() != self.n_bins)[0]
  1316. self.manual_discretizer_ = dict()
  1317. for idx in err_idx:
  1318. col = self.dcols_[idx]
  1319. if X[col].nunique() &gt; 1:
  1320. q_values = np.linspace(0, 1, self.n_bins[idx] + 1)
  1321. bin_edges = np.quantile(X[col], q_values)
  1322. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  1323. keep_pointwise_bins=True)
  1324. self.manual_discretizer_[col] = bin_edges
  1325. # fit onehot encoded X if specified
  1326. if self.encode == &#34;onehot&#34;:
  1327. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  1328. onehot.fit(discretized_df.astype(str))
  1329. self.onehot_ = onehot
  1330. return self</code></pre>
  1331. </details>
  1332. </dd>
  1333. <dt id="imodels.discretization.discretizer.BasicDiscretizer.transform"><code class="name flex">
  1334. <span>def <span class="ident">transform</span></span>(<span>self, X)</span>
  1335. </code></dt>
  1336. <dd>
  1337. <div class="desc"><p>Discretize the data.</p>
  1338. <h2 id="parameters">Parameters</h2>
  1339. <dl>
  1340. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  1341. <dd>Data to be discretized.</dd>
  1342. </dl>
  1343. <h2 id="returns">Returns</h2>
  1344. <dl>
  1345. <dt><strong><code>X_discretized</code></strong> :&ensp;<code>data frame</code></dt>
  1346. <dd>Data with features in dcols transformed to the
  1347. binned space. All other features remain unchanged.</dd>
  1348. </dl></div>
  1349. <details class="source">
  1350. <summary>
  1351. <span>Expand source code</span>
  1352. </summary>
  1353. <pre><code class="python">def transform(self, X):
  1354. &#34;&#34;&#34;
  1355. Discretize the data.
  1356. Parameters
  1357. ----------
  1358. X : data frame of shape (n_samples, n_features)
  1359. Data to be discretized.
  1360. Returns
  1361. -------
  1362. X_discretized : data frame
  1363. Data with features in dcols transformed to the
  1364. binned space. All other features remain unchanged.
  1365. &#34;&#34;&#34;
  1366. check_is_fitted(self)
  1367. # transform using KBinsDiscretizer
  1368. discretized_df = self.discretizer_.transform(
  1369. X[self.dcols_]).astype(int)
  1370. discretized_df = pd.DataFrame(discretized_df,
  1371. columns=self.dcols_,
  1372. index=X.index)
  1373. # fix KBinsDiscretizer errors (if any) when strategy = &#34;quantile&#34;
  1374. if self.strategy == &#34;quantile&#34;:
  1375. for col in self.manual_discretizer_.keys():
  1376. bin_edges = self.manual_discretizer_[col]
  1377. discretized_df[col] = self._discretize_to_bins(X[col], bin_edges,
  1378. keep_pointwise_bins=True)
  1379. # return onehot encoded data if specified and
  1380. # join discretized columns with rest of X
  1381. X_discretized = self._transform_postprocessing(discretized_df, X)
  1382. return X_discretized</code></pre>
  1383. </details>
  1384. </dd>
  1385. </dl>
  1386. </dd>
  1387. <dt id="imodels.discretization.discretizer.ExtraBasicDiscretizer"><code class="flex name class">
  1388. <span>class <span class="ident">ExtraBasicDiscretizer</span></span>
  1389. <span>(</span><span>dcols, n_bins=4, strategy='quantile', onehot_drop='if_binary')</span>
  1390. </code></dt>
  1391. <dd>
  1392. <div class="desc"><p>Discretize provided columns into bins and return in one-hot format.
  1393. Generates meaningful column names based on bin edges.
  1394. Wraps KBinsDiscretizer from sklearn.</p>
  1395. <h2 id="params">Params</h2>
  1396. <p>dcols : list of strings
  1397. The names of the columns to be discretized.</p>
  1398. <p>n_bins : int or array-like of shape (len(dcols),), default=4
  1399. Number of bins to discretize each feature into.</p>
  1400. <p>strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile'
  1401. Strategy used to define the widths of the bins.</p>
  1402. <pre><code>uniform
  1403. All bins in each feature have identical widths.
  1404. quantile
  1405. All bins in each feature have the same number of points.
  1406. kmeans
  1407. Values in each bin have the same nearest center of a 1D
  1408. k-means cluster.
  1409. </code></pre>
  1410. <p>onehot_drop : {'first', 'if_binary'} or a array-like of shape
  1411. (len(dcols),), default='if_binary'
  1412. Specifies a methodology to use to drop one of the categories
  1413. per feature when encode = "onehot".</p>
  1414. <pre><code>None
  1415. Retain all features (the default).
  1416. 'first'
  1417. Drop the first y_str in each feature. If only one y_str
  1418. is present, the feature will be dropped entirely.
  1419. 'if_binary'
  1420. Drop the first y_str in each feature with two categories.
  1421. Features with 1 or more than 2 categories are left intact.
  1422. </code></pre>
  1423. <h2 id="attributes">Attributes</h2>
  1424. <dl>
  1425. <dt><strong><code>discretizer_</code></strong> :&ensp;<code>object</code> of <code>class KBinsDiscretizer()</code></dt>
  1426. <dd>Primary discretization method used to bin numeric data</dd>
  1427. </dl>
  1428. <h2 id="examples">Examples</h2></div>
  1429. <details class="source">
  1430. <summary>
  1431. <span>Expand source code</span>
  1432. </summary>
  1433. <pre><code class="python">class ExtraBasicDiscretizer(TransformerMixin):
  1434. &#34;&#34;&#34;
  1435. Discretize provided columns into bins and return in one-hot format.
  1436. Generates meaningful column names based on bin edges.
  1437. Wraps KBinsDiscretizer from sklearn.
  1438. Params
  1439. ------
  1440. dcols : list of strings
  1441. The names of the columns to be discretized.
  1442. n_bins : int or array-like of shape (len(dcols),), default=4
  1443. Number of bins to discretize each feature into.
  1444. strategy : {&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;}, default=&#39;quantile&#39;
  1445. Strategy used to define the widths of the bins.
  1446. uniform
  1447. All bins in each feature have identical widths.
  1448. quantile
  1449. All bins in each feature have the same number of points.
  1450. kmeans
  1451. Values in each bin have the same nearest center of a 1D
  1452. k-means cluster.
  1453. onehot_drop : {&#39;first&#39;, &#39;if_binary&#39;} or a array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  1454. Specifies a methodology to use to drop one of the categories
  1455. per feature when encode = &#34;onehot&#34;.
  1456. None
  1457. Retain all features (the default).
  1458. &#39;first&#39;
  1459. Drop the first y_str in each feature. If only one y_str
  1460. is present, the feature will be dropped entirely.
  1461. &#39;if_binary&#39;
  1462. Drop the first y_str in each feature with two categories.
  1463. Features with 1 or more than 2 categories are left intact.
  1464. Attributes
  1465. ----------
  1466. discretizer_ : object of class KBinsDiscretizer()
  1467. Primary discretization method used to bin numeric data
  1468. Examples
  1469. --------
  1470. &#34;&#34;&#34;
  1471. def __init__(self,
  1472. dcols,
  1473. n_bins=4,
  1474. strategy=&#39;quantile&#39;,
  1475. onehot_drop=&#39;if_binary&#39;):
  1476. self.dcols = dcols
  1477. self.n_bins = n_bins
  1478. self.strategy = strategy
  1479. self.onehot_drop = onehot_drop
  1480. def fit(self, X, y=None):
  1481. &#34;&#34;&#34;
  1482. Fit the estimator.
  1483. Parameters
  1484. ----------
  1485. X : data frame of shape (n_samples, n_features)
  1486. (Training) data to be discretized.
  1487. y : Ignored. This parameter exists only for compatibility with
  1488. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  1489. Returns
  1490. -------
  1491. self
  1492. &#34;&#34;&#34;
  1493. # Fit KBinsDiscretizer to the selected columns
  1494. discretizer = KBinsDiscretizer(
  1495. n_bins=self.n_bins, strategy=self.strategy, encode=&#39;ordinal&#39;)
  1496. discretizer.fit(X[self.dcols])
  1497. self.discretizer_ = discretizer
  1498. # Fit OneHotEncoder to the ordinal output of KBinsDiscretizer
  1499. disc_ordinal_np = discretizer.transform(X[self.dcols])
  1500. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  1501. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  1502. encoder = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  1503. encoder.fit(disc_ordinal_df_str)
  1504. self.encoder_ = encoder
  1505. return self
  1506. def transform(self, X):
  1507. &#34;&#34;&#34;
  1508. Discretize the data.
  1509. Parameters
  1510. ----------
  1511. X : data frame of shape (n_samples, n_features)
  1512. Data to be discretized.
  1513. Returns
  1514. -------
  1515. X_discretized : data frame
  1516. Data with features in dcols transformed to the
  1517. binned space. All other features remain unchanged.
  1518. &#34;&#34;&#34;
  1519. # Apply discretizer transform to get ordinally coded DF
  1520. disc_ordinal_np = self.discretizer_.transform(X[self.dcols])
  1521. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  1522. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  1523. # One-hot encode the ordinal DF
  1524. disc_onehot_np = self.encoder_.transform(disc_ordinal_df_str)
  1525. disc_onehot = pd.DataFrame(
  1526. disc_onehot_np, columns=self.encoder_.get_feature_names_out())
  1527. # Name columns after the interval they represent (e.g. 0.1_to_0.5)
  1528. for col, bin_edges in zip(self.dcols, self.discretizer_.bin_edges_):
  1529. bin_edges = bin_edges.astype(str)
  1530. for ordinal_value in disc_ordinal_df_str[col].unique():
  1531. bin_lb = bin_edges[int(ordinal_value)]
  1532. bin_ub = bin_edges[int(ordinal_value) + 1]
  1533. interval_string = f&#39;{bin_lb}_to_{bin_ub}&#39;
  1534. disc_onehot = disc_onehot.rename(
  1535. columns={f&#39;{col}_{ordinal_value}&#39;: f&#39;{col}_&#39; + interval_string})
  1536. # Join discretized columns with rest of X
  1537. non_dcols = [col for col in X.columns if col not in self.dcols]
  1538. X_discretized = pd.concat([disc_onehot, X[non_dcols]], axis=1)
  1539. return X_discretized</code></pre>
  1540. </details>
  1541. <h3>Ancestors</h3>
  1542. <ul class="hlist">
  1543. <li>sklearn.base.TransformerMixin</li>
  1544. <li>sklearn.utils._set_output._SetOutputMixin</li>
  1545. </ul>
  1546. <h3>Methods</h3>
  1547. <dl>
  1548. <dt id="imodels.discretization.discretizer.ExtraBasicDiscretizer.fit"><code class="name flex">
  1549. <span>def <span class="ident">fit</span></span>(<span>self, X, y=None)</span>
  1550. </code></dt>
  1551. <dd>
  1552. <div class="desc"><p>Fit the estimator.</p>
  1553. <h2 id="parameters">Parameters</h2>
  1554. <dl>
  1555. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  1556. <dd>(Training) data to be discretized.</dd>
  1557. <dt><strong><code>y</code></strong> :&ensp;<code>Ignored. This parameter exists only for compatibility with</code></dt>
  1558. <dd>:class:<code>~sklearn.pipeline.Pipeline</code> and fit_transform method</dd>
  1559. </dl>
  1560. <h2 id="returns">Returns</h2>
  1561. <dl>
  1562. <dt><code>self</code></dt>
  1563. <dd>&nbsp;</dd>
  1564. </dl></div>
  1565. <details class="source">
  1566. <summary>
  1567. <span>Expand source code</span>
  1568. </summary>
  1569. <pre><code class="python">def fit(self, X, y=None):
  1570. &#34;&#34;&#34;
  1571. Fit the estimator.
  1572. Parameters
  1573. ----------
  1574. X : data frame of shape (n_samples, n_features)
  1575. (Training) data to be discretized.
  1576. y : Ignored. This parameter exists only for compatibility with
  1577. :class:`~sklearn.pipeline.Pipeline` and fit_transform method
  1578. Returns
  1579. -------
  1580. self
  1581. &#34;&#34;&#34;
  1582. # Fit KBinsDiscretizer to the selected columns
  1583. discretizer = KBinsDiscretizer(
  1584. n_bins=self.n_bins, strategy=self.strategy, encode=&#39;ordinal&#39;)
  1585. discretizer.fit(X[self.dcols])
  1586. self.discretizer_ = discretizer
  1587. # Fit OneHotEncoder to the ordinal output of KBinsDiscretizer
  1588. disc_ordinal_np = discretizer.transform(X[self.dcols])
  1589. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  1590. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  1591. encoder = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  1592. encoder.fit(disc_ordinal_df_str)
  1593. self.encoder_ = encoder
  1594. return self</code></pre>
  1595. </details>
  1596. </dd>
  1597. <dt id="imodels.discretization.discretizer.ExtraBasicDiscretizer.transform"><code class="name flex">
  1598. <span>def <span class="ident">transform</span></span>(<span>self, X)</span>
  1599. </code></dt>
  1600. <dd>
  1601. <div class="desc"><p>Discretize the data.</p>
  1602. <h2 id="parameters">Parameters</h2>
  1603. <dl>
  1604. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  1605. <dd>Data to be discretized.</dd>
  1606. </dl>
  1607. <h2 id="returns">Returns</h2>
  1608. <dl>
  1609. <dt><strong><code>X_discretized</code></strong> :&ensp;<code>data frame</code></dt>
  1610. <dd>Data with features in dcols transformed to the
  1611. binned space. All other features remain unchanged.</dd>
  1612. </dl></div>
  1613. <details class="source">
  1614. <summary>
  1615. <span>Expand source code</span>
  1616. </summary>
  1617. <pre><code class="python">def transform(self, X):
  1618. &#34;&#34;&#34;
  1619. Discretize the data.
  1620. Parameters
  1621. ----------
  1622. X : data frame of shape (n_samples, n_features)
  1623. Data to be discretized.
  1624. Returns
  1625. -------
  1626. X_discretized : data frame
  1627. Data with features in dcols transformed to the
  1628. binned space. All other features remain unchanged.
  1629. &#34;&#34;&#34;
  1630. # Apply discretizer transform to get ordinally coded DF
  1631. disc_ordinal_np = self.discretizer_.transform(X[self.dcols])
  1632. disc_ordinal_df = pd.DataFrame(disc_ordinal_np, columns=self.dcols)
  1633. disc_ordinal_df_str = disc_ordinal_df.astype(int).astype(str)
  1634. # One-hot encode the ordinal DF
  1635. disc_onehot_np = self.encoder_.transform(disc_ordinal_df_str)
  1636. disc_onehot = pd.DataFrame(
  1637. disc_onehot_np, columns=self.encoder_.get_feature_names_out())
  1638. # Name columns after the interval they represent (e.g. 0.1_to_0.5)
  1639. for col, bin_edges in zip(self.dcols, self.discretizer_.bin_edges_):
  1640. bin_edges = bin_edges.astype(str)
  1641. for ordinal_value in disc_ordinal_df_str[col].unique():
  1642. bin_lb = bin_edges[int(ordinal_value)]
  1643. bin_ub = bin_edges[int(ordinal_value) + 1]
  1644. interval_string = f&#39;{bin_lb}_to_{bin_ub}&#39;
  1645. disc_onehot = disc_onehot.rename(
  1646. columns={f&#39;{col}_{ordinal_value}&#39;: f&#39;{col}_&#39; + interval_string})
  1647. # Join discretized columns with rest of X
  1648. non_dcols = [col for col in X.columns if col not in self.dcols]
  1649. X_discretized = pd.concat([disc_onehot, X[non_dcols]], axis=1)
  1650. return X_discretized</code></pre>
  1651. </details>
  1652. </dd>
  1653. </dl>
  1654. </dd>
  1655. <dt id="imodels.discretization.discretizer.RFDiscretizer"><code class="flex name class">
  1656. <span>class <span class="ident">RFDiscretizer</span></span>
  1657. <span>(</span><span>rf_model=None, classification=False, n_bins=2, dcols=[], encode='onehot', strategy='quantile', backup_strategy='quantile', onehot_drop='if_binary')</span>
  1658. </code></dt>
  1659. <dd>
  1660. <div class="desc"><p>Discretize numeric data into bins using RF splits.</p>
  1661. <h2 id="parameters">Parameters</h2>
  1662. <dl>
  1663. <dt><strong><code>rf_model</code></strong> :&ensp;<code>RandomForestClassifer()</code> or <code>RandomForestRegressor()</code></dt>
  1664. <dd>RF model from which to extract splits for discretization.
  1665. Default is RandomForestClassifer(n_estimators = 500) or
  1666. RandomForestRegressor(n_estimators = 500)</dd>
  1667. <dt><strong><code>classification</code></strong> :&ensp;<code>boolean; default=False</code></dt>
  1668. <dd>Used only if rf_model=None. If True,
  1669. rf_model=RandomForestClassifier(n_estimators = 500).
  1670. Else, rf_model=RandomForestRegressor(n_estimators = 500)</dd>
  1671. <dt><strong><code>n_bins</code></strong> :&ensp;<code>int</code> or <code>array-like</code> of <code>shape (len(dcols),)</code>, default=<code>2</code></dt>
  1672. <dd>Number of bins to discretize each feature into.</dd>
  1673. <dt><strong><code>dcols</code></strong> :&ensp;<code>list</code> of <code>strings</code></dt>
  1674. <dd>The names of the columns to be discretized; by default,
  1675. discretize all float and int columns in X.</dd>
  1676. <dt><strong><code>encode</code></strong> :&ensp;<code>{‘onehot’, ‘ordinal’}</code>, default=<code>’onehot’</code></dt>
  1677. <dd>
  1678. <p>Method used to encode the transformed result.</p>
  1679. <p>onehot - Encode the transformed result with one-hot encoding and
  1680. return a dense array.
  1681. ordinal - Return the bin identifier encoded as an integer value.</p>
  1682. </dd>
  1683. <dt><strong><code>strategy</code></strong> :&ensp;<code>{‘uniform’, ‘quantile’}</code>, default=<code>’quantile’</code></dt>
  1684. <dd>Strategy used to choose RF split points.
  1685. uniform - RF split points chosen to be uniformly spaced out.
  1686. quantile - RF split points chosen based on equally-spaced quantiles.</dd>
  1687. <dt><strong><code>backup_strategy</code></strong> :&ensp;<code>{‘uniform’, ‘quantile’, ‘kmeans’}</code>, default=<code>’quantile’</code></dt>
  1688. <dd>Strategy used to define the widths of the bins if no rf splits exist for
  1689. that feature. Used in KBinsDiscretizer.
  1690. uniform
  1691. All bins in each feature have identical widths.
  1692. quantile
  1693. All bins in each feature have the same number of points.
  1694. kmeans
  1695. Values in each bin have the same nearest center of a 1D
  1696. k-means cluster.</dd>
  1697. <dt><strong><code>onehot_drop</code></strong> :&ensp;<code>{‘first’, ‘if_binary’}</code> or <code>array-like</code> of <code>shape
  1698. (len(dcols),)</code>, default=<code>'if_binary'</code></dt>
  1699. <dd>Specifies a methodology to use to drop one of the categories
  1700. per feature when encode = "onehot".
  1701. None
  1702. Retain all features (the default).
  1703. ‘first’
  1704. Drop the first y_str in each feature. If only one y_str
  1705. is present, the feature will be dropped entirely.
  1706. ‘if_binary’
  1707. Drop the first y_str in each feature with two categories.
  1708. Features with 1 or more than 2 categories are left intact.</dd>
  1709. </dl>
  1710. <h2 id="attributes">Attributes</h2>
  1711. <dl>
  1712. <dt><strong><code>rf_splits</code></strong> :&ensp;<code>dictionary where</code></dt>
  1713. <dd>key = feature name
  1714. value = array of all RF split threshold values</dd>
  1715. <dt><strong><code>bin_edges_</code></strong> :&ensp;<code>dictionary where</code></dt>
  1716. <dd>key = feature name
  1717. value = array of bin edges used for discretization, taken from
  1718. RF split values</dd>
  1719. <dt><strong><code>missing_rf_cols_</code></strong> :&ensp;<code>array-like</code></dt>
  1720. <dd>List of features that were not used in RF</dd>
  1721. <dt><strong><code>backup_discretizer_</code></strong> :&ensp;<code>object</code> of <code>class <a title="imodels.discretization.discretizer.BasicDiscretizer" href="#imodels.discretization.discretizer.BasicDiscretizer">BasicDiscretizer</a></code></dt>
  1722. <dd>Discretization method used to bin numeric data for features
  1723. in missing_rf_cols_</dd>
  1724. <dt><strong><code>onehot_</code></strong> :&ensp;<code>object</code> of <code>class OneHotEncoder()</code></dt>
  1725. <dd>One hot encoding fit. Ignored if encode != 'onehot'</dd>
  1726. </dl></div>
  1727. <details class="source">
  1728. <summary>
  1729. <span>Expand source code</span>
  1730. </summary>
  1731. <pre><code class="python">class RFDiscretizer(AbstractDiscretizer):
  1732. &#34;&#34;&#34;
  1733. Discretize numeric data into bins using RF splits.
  1734. Parameters
  1735. ----------
  1736. rf_model : RandomForestClassifer() or RandomForestRegressor()
  1737. RF model from which to extract splits for discretization.
  1738. Default is RandomForestClassifer(n_estimators = 500) or
  1739. RandomForestRegressor(n_estimators = 500)
  1740. classification : boolean; default=False
  1741. Used only if rf_model=None. If True,
  1742. rf_model=RandomForestClassifier(n_estimators = 500).
  1743. Else, rf_model=RandomForestRegressor(n_estimators = 500)
  1744. n_bins : int or array-like of shape (len(dcols),), default=2
  1745. Number of bins to discretize each feature into.
  1746. dcols : list of strings
  1747. The names of the columns to be discretized; by default,
  1748. discretize all float and int columns in X.
  1749. encode : {‘onehot’, ‘ordinal’}, default=’onehot’
  1750. Method used to encode the transformed result.
  1751. onehot - Encode the transformed result with one-hot encoding and
  1752. return a dense array.
  1753. ordinal - Return the bin identifier encoded as an integer value.
  1754. strategy : {‘uniform’, ‘quantile’}, default=’quantile’
  1755. Strategy used to choose RF split points.
  1756. uniform - RF split points chosen to be uniformly spaced out.
  1757. quantile - RF split points chosen based on equally-spaced quantiles.
  1758. backup_strategy : {‘uniform’, ‘quantile’, ‘kmeans’}, default=’quantile’
  1759. Strategy used to define the widths of the bins if no rf splits exist for
  1760. that feature. Used in KBinsDiscretizer.
  1761. uniform
  1762. All bins in each feature have identical widths.
  1763. quantile
  1764. All bins in each feature have the same number of points.
  1765. kmeans
  1766. Values in each bin have the same nearest center of a 1D
  1767. k-means cluster.
  1768. onehot_drop : {‘first’, ‘if_binary’} or array-like of shape (len(dcols),), default=&#39;if_binary&#39;
  1769. Specifies a methodology to use to drop one of the categories
  1770. per feature when encode = &#34;onehot&#34;.
  1771. None
  1772. Retain all features (the default).
  1773. ‘first’
  1774. Drop the first y_str in each feature. If only one y_str
  1775. is present, the feature will be dropped entirely.
  1776. ‘if_binary’
  1777. Drop the first y_str in each feature with two categories.
  1778. Features with 1 or more than 2 categories are left intact.
  1779. Attributes
  1780. ----------
  1781. rf_splits : dictionary where
  1782. key = feature name
  1783. value = array of all RF split threshold values
  1784. bin_edges_ : dictionary where
  1785. key = feature name
  1786. value = array of bin edges used for discretization, taken from
  1787. RF split values
  1788. missing_rf_cols_ : array-like
  1789. List of features that were not used in RF
  1790. backup_discretizer_ : object of class BasicDiscretizer()
  1791. Discretization method used to bin numeric data for features
  1792. in missing_rf_cols_
  1793. onehot_ : object of class OneHotEncoder()
  1794. One hot encoding fit. Ignored if encode != &#39;onehot&#39;
  1795. &#34;&#34;&#34;
  1796. def __init__(self, rf_model=None, classification=False,
  1797. n_bins=2, dcols=[], encode=&#39;onehot&#39;,
  1798. strategy=&#39;quantile&#39;, backup_strategy=&#39;quantile&#39;,
  1799. onehot_drop=&#39;if_binary&#39;):
  1800. super().__init__(n_bins=n_bins, dcols=dcols,
  1801. encode=encode, strategy=strategy,
  1802. onehot_drop=onehot_drop)
  1803. self.backup_strategy = backup_strategy
  1804. self.rf_model = rf_model
  1805. if rf_model is None:
  1806. self.classification = classification
  1807. def _validate_args(self):
  1808. &#34;&#34;&#34;
  1809. Check if encode, strategy, backup_strategy arguments are valid.
  1810. &#34;&#34;&#34;
  1811. super()._validate_args()
  1812. valid_backup_strategy = (&#39;uniform&#39;, &#39;quantile&#39;, &#39;kmeans&#39;)
  1813. if (self.backup_strategy not in valid_backup_strategy):
  1814. raise ValueError(&#34;Valid options for &#39;strategy&#39; are {}. Got strategy={!r} instead.&#34;
  1815. .format(valid_backup_strategy, self.backup_strategy))
  1816. def _get_rf_splits(self, col_names):
  1817. &#34;&#34;&#34;
  1818. Get all splits in random forest ensemble
  1819. Parameters
  1820. ----------
  1821. col_names : array-like of shape (n_features,)
  1822. Column names for X used to train rf_model
  1823. Returns
  1824. -------
  1825. rule_dict : dictionary where
  1826. key = feature name
  1827. value = array of all RF split threshold values
  1828. &#34;&#34;&#34;
  1829. rule_dict = {}
  1830. for model in self.rf_model.estimators_:
  1831. tree = model.tree_
  1832. tree_it = enumerate(zip(tree.children_left,
  1833. tree.children_right,
  1834. tree.feature,
  1835. tree.threshold))
  1836. for node_idx, data in tree_it:
  1837. left, right, feature, th = data
  1838. if (left != -1) | (right != -1):
  1839. feature = col_names[feature]
  1840. if feature in rule_dict:
  1841. rule_dict[feature].append(th)
  1842. else:
  1843. rule_dict[feature] = [th]
  1844. return rule_dict
  1845. def _fit_rf(self, X, y=None):
  1846. &#34;&#34;&#34;
  1847. Fit random forest (if necessary) and obtain RF split thresholds
  1848. Parameters
  1849. ----------
  1850. X : data frame of shape (n_samples, n_features)
  1851. Training data used to fit RF
  1852. y : array-like of shape (n_samples,)
  1853. Training response vector used to fit RF
  1854. Returns
  1855. -------
  1856. rf_splits : dictionary where
  1857. key = feature name
  1858. value = array of all RF split threshold values
  1859. &#34;&#34;&#34;
  1860. # If no rf_model given, train default random forest model
  1861. if self.rf_model is None:
  1862. if y is None:
  1863. raise ValueError(&#34;Must provide y if rf_model is not given.&#34;)
  1864. if self.classification:
  1865. self.rf_model = RandomForestClassifier(n_estimators=500)
  1866. else:
  1867. self.rf_model = RandomForestRegressor(n_estimators=500)
  1868. self.rf_model.fit(X, y)
  1869. else:
  1870. # provided rf model has not yet been trained
  1871. if not check_is_fitted(self.rf_model):
  1872. if y is None:
  1873. raise ValueError(
  1874. &#34;Must provide y if rf_model has not been trained.&#34;)
  1875. self.rf_model.fit(X, y)
  1876. # get all random forest split points
  1877. self.rf_splits = self._get_rf_splits(list(X.columns))
  1878. def reweight_n_bins(self, X, y=None, by=&#34;nsplits&#34;):
  1879. &#34;&#34;&#34;
  1880. Reallocate number of bins per feature.
  1881. Parameters
  1882. ----------
  1883. X : data frame of shape (n_samples, n_features)
  1884. (Training) data to be discretized.
  1885. y : array-like of shape (n_samples,)
  1886. (Training) response vector. Required only if
  1887. rf_model = None or rf_model has not yet been fitted
  1888. by : {&#39;nsplits&#39;}, default=&#39;nsplits&#39;
  1889. Specifies how to reallocate number of bins per feature.
  1890. nsplits
  1891. Reallocate number of bins so that each feature
  1892. in dcols get at a minimum of 2 bins with the
  1893. remaining bins distributed proportionally to the
  1894. number of RF splits using that feature
  1895. Returns
  1896. -------
  1897. self.n_bins : array of shape (len(dcols),)
  1898. number of bins per feature reallocated according to
  1899. &#39;by&#39; argument
  1900. &#34;&#34;&#34;
  1901. # initialization and error checking
  1902. self._fit_preprocessing(X)
  1903. # get all random forest split points
  1904. self._fit_rf(X=X, y=y)
  1905. # get total number of bins to reallocate
  1906. total_bins = self.n_bins.sum()
  1907. # reweight n_bins
  1908. if by == &#34;nsplits&#34;:
  1909. # each col gets at least 2 bins; remaining bins get
  1910. # reallocated based on number of RF splits using that feature
  1911. n_rules = np.array([len(self.rf_splits[col])
  1912. for col in self.dcols_])
  1913. self.n_bins = np.round(n_rules / n_rules.sum() *
  1914. (total_bins - 2 * len(self.dcols_))) + 2
  1915. else:
  1916. valid_by = (&#39;nsplits&#39;)
  1917. raise ValueError(&#34;Valid options for &#39;by&#39; are {}. Got by={!r} instead.&#34;
  1918. .format(valid_by, by))
  1919. def fit(self, X, y=None):
  1920. &#34;&#34;&#34;
  1921. Fit the estimator.
  1922. Parameters
  1923. ----------
  1924. X : data frame of shape (n_samples, n_features)
  1925. (Training) data to be discretized.
  1926. y : array-like of shape (n_samples,)
  1927. (Training) response vector. Required only if
  1928. rf_model = None or rf_model has not yet been fitted
  1929. Returns
  1930. -------
  1931. self
  1932. &#34;&#34;&#34;
  1933. # initialization and error checking
  1934. self._fit_preprocessing(X)
  1935. # get all random forest split points
  1936. self._fit_rf(X=X, y=y)
  1937. # features that were not used in the rf but need to be discretized
  1938. self.missing_rf_cols_ = list(set(self.dcols_) -
  1939. set(self.rf_splits.keys()))
  1940. if len(self.missing_rf_cols_) &gt; 0:
  1941. print(&#34;{} did not appear in random forest so were discretized via {} discretization&#34;
  1942. .format(self.missing_rf_cols_, self.strategy))
  1943. missing_n_bins = np.array([self.n_bins[np.array(self.dcols_) == col][0]
  1944. for col in self.missing_rf_cols_])
  1945. backup_discretizer = BasicDiscretizer(n_bins=missing_n_bins,
  1946. dcols=self.missing_rf_cols_,
  1947. encode=&#39;ordinal&#39;,
  1948. strategy=self.backup_strategy)
  1949. backup_discretizer.fit(X[self.missing_rf_cols_])
  1950. self.backup_discretizer_ = backup_discretizer
  1951. else:
  1952. self.backup_discretizer_ = None
  1953. if self.encode == &#39;onehot&#39;:
  1954. if len(self.missing_rf_cols_) &gt; 0:
  1955. discretized_df = backup_discretizer.transform(
  1956. X[self.missing_rf_cols_])
  1957. else:
  1958. discretized_df = pd.DataFrame({}, index=X.index)
  1959. # do discretization based on rf split thresholds
  1960. self.bin_edges_ = dict()
  1961. for col in self.dcols_:
  1962. if col in self.rf_splits.keys():
  1963. b = self.n_bins[np.array(self.dcols_) == col]
  1964. if self.strategy == &#34;quantile&#34;:
  1965. q_values = np.linspace(0, 1, int(b) + 1)
  1966. bin_edges = np.quantile(self.rf_splits[col], q_values)
  1967. elif self.strategy == &#34;uniform&#34;:
  1968. width = (max(self.rf_splits[col]) -
  1969. min(self.rf_splits[col])) / b
  1970. bin_edges = width * \
  1971. np.arange(0, b + 1) + min(self.rf_splits[col])
  1972. self.bin_edges_[col] = bin_edges
  1973. if self.encode == &#39;onehot&#39;:
  1974. discretized_df[col] = self._discretize_to_bins(
  1975. X[col], bin_edges)
  1976. # fit onehot encoded X if specified
  1977. if self.encode == &#34;onehot&#34;:
  1978. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  1979. onehot.fit(discretized_df[self.dcols_].astype(str))
  1980. self.onehot_ = onehot
  1981. return self
  1982. def transform(self, X):
  1983. &#34;&#34;&#34;
  1984. Discretize the data.
  1985. Parameters
  1986. ----------
  1987. X : data frame of shape (n_samples, n_features)
  1988. Data to be discretized.
  1989. Returns
  1990. -------
  1991. X_discretized : data frame
  1992. Data with features in dcols transformed to the
  1993. binned space. All other features remain unchanged.
  1994. &#34;&#34;&#34;
  1995. check_is_fitted(self)
  1996. # transform features that did not appear in RF
  1997. if len(self.missing_rf_cols_) &gt; 0:
  1998. discretized_df = self.backup_discretizer_.transform(
  1999. X[self.missing_rf_cols_])
  2000. discretized_df = pd.DataFrame(discretized_df,
  2001. columns=self.missing_rf_cols_,
  2002. index=X.index)
  2003. else:
  2004. discretized_df = pd.DataFrame({}, index=X.index)
  2005. # do discretization based on rf split thresholds
  2006. for col in self.bin_edges_.keys():
  2007. discretized_df[col] = self._discretize_to_bins(
  2008. X[col], self.bin_edges_[col])
  2009. # return onehot encoded data if specified and
  2010. # join discretized columns with rest of X
  2011. X_discretized = self._transform_postprocessing(discretized_df, X)
  2012. return X_discretized</code></pre>
  2013. </details>
  2014. <h3>Ancestors</h3>
  2015. <ul class="hlist">
  2016. <li><a title="imodels.discretization.discretizer.AbstractDiscretizer" href="#imodels.discretization.discretizer.AbstractDiscretizer">AbstractDiscretizer</a></li>
  2017. <li>sklearn.base.TransformerMixin</li>
  2018. <li>sklearn.utils._set_output._SetOutputMixin</li>
  2019. <li>sklearn.base.BaseEstimator</li>
  2020. <li>sklearn.utils._estimator_html_repr._HTMLDocumentationLinkMixin</li>
  2021. <li>sklearn.utils._metadata_requests._MetadataRequester</li>
  2022. </ul>
  2023. <h3>Methods</h3>
  2024. <dl>
  2025. <dt id="imodels.discretization.discretizer.RFDiscretizer.fit"><code class="name flex">
  2026. <span>def <span class="ident">fit</span></span>(<span>self, X, y=None)</span>
  2027. </code></dt>
  2028. <dd>
  2029. <div class="desc"><p>Fit the estimator.</p>
  2030. <h2 id="parameters">Parameters</h2>
  2031. <dl>
  2032. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  2033. <dd>(Training) data to be discretized.</dd>
  2034. <dt><strong><code>y</code></strong> :&ensp;<code>array-like</code> of <code>shape (n_samples,)</code></dt>
  2035. <dd>(Training) response vector. Required only if
  2036. rf_model = None or rf_model has not yet been fitted</dd>
  2037. </dl>
  2038. <h2 id="returns">Returns</h2>
  2039. <dl>
  2040. <dt><code>self</code></dt>
  2041. <dd>&nbsp;</dd>
  2042. </dl></div>
  2043. <details class="source">
  2044. <summary>
  2045. <span>Expand source code</span>
  2046. </summary>
  2047. <pre><code class="python">def fit(self, X, y=None):
  2048. &#34;&#34;&#34;
  2049. Fit the estimator.
  2050. Parameters
  2051. ----------
  2052. X : data frame of shape (n_samples, n_features)
  2053. (Training) data to be discretized.
  2054. y : array-like of shape (n_samples,)
  2055. (Training) response vector. Required only if
  2056. rf_model = None or rf_model has not yet been fitted
  2057. Returns
  2058. -------
  2059. self
  2060. &#34;&#34;&#34;
  2061. # initialization and error checking
  2062. self._fit_preprocessing(X)
  2063. # get all random forest split points
  2064. self._fit_rf(X=X, y=y)
  2065. # features that were not used in the rf but need to be discretized
  2066. self.missing_rf_cols_ = list(set(self.dcols_) -
  2067. set(self.rf_splits.keys()))
  2068. if len(self.missing_rf_cols_) &gt; 0:
  2069. print(&#34;{} did not appear in random forest so were discretized via {} discretization&#34;
  2070. .format(self.missing_rf_cols_, self.strategy))
  2071. missing_n_bins = np.array([self.n_bins[np.array(self.dcols_) == col][0]
  2072. for col in self.missing_rf_cols_])
  2073. backup_discretizer = BasicDiscretizer(n_bins=missing_n_bins,
  2074. dcols=self.missing_rf_cols_,
  2075. encode=&#39;ordinal&#39;,
  2076. strategy=self.backup_strategy)
  2077. backup_discretizer.fit(X[self.missing_rf_cols_])
  2078. self.backup_discretizer_ = backup_discretizer
  2079. else:
  2080. self.backup_discretizer_ = None
  2081. if self.encode == &#39;onehot&#39;:
  2082. if len(self.missing_rf_cols_) &gt; 0:
  2083. discretized_df = backup_discretizer.transform(
  2084. X[self.missing_rf_cols_])
  2085. else:
  2086. discretized_df = pd.DataFrame({}, index=X.index)
  2087. # do discretization based on rf split thresholds
  2088. self.bin_edges_ = dict()
  2089. for col in self.dcols_:
  2090. if col in self.rf_splits.keys():
  2091. b = self.n_bins[np.array(self.dcols_) == col]
  2092. if self.strategy == &#34;quantile&#34;:
  2093. q_values = np.linspace(0, 1, int(b) + 1)
  2094. bin_edges = np.quantile(self.rf_splits[col], q_values)
  2095. elif self.strategy == &#34;uniform&#34;:
  2096. width = (max(self.rf_splits[col]) -
  2097. min(self.rf_splits[col])) / b
  2098. bin_edges = width * \
  2099. np.arange(0, b + 1) + min(self.rf_splits[col])
  2100. self.bin_edges_[col] = bin_edges
  2101. if self.encode == &#39;onehot&#39;:
  2102. discretized_df[col] = self._discretize_to_bins(
  2103. X[col], bin_edges)
  2104. # fit onehot encoded X if specified
  2105. if self.encode == &#34;onehot&#34;:
  2106. onehot = OneHotEncoder(drop=self.onehot_drop) # , sparse=False)
  2107. onehot.fit(discretized_df[self.dcols_].astype(str))
  2108. self.onehot_ = onehot
  2109. return self</code></pre>
  2110. </details>
  2111. </dd>
  2112. <dt id="imodels.discretization.discretizer.RFDiscretizer.reweight_n_bins"><code class="name flex">
  2113. <span>def <span class="ident">reweight_n_bins</span></span>(<span>self, X, y=None, by='nsplits')</span>
  2114. </code></dt>
  2115. <dd>
  2116. <div class="desc"><p>Reallocate number of bins per feature.</p>
  2117. <h2 id="parameters">Parameters</h2>
  2118. <dl>
  2119. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  2120. <dd>(Training) data to be discretized.</dd>
  2121. <dt><strong><code>y</code></strong> :&ensp;<code>array-like</code> of <code>shape (n_samples,)</code></dt>
  2122. <dd>(Training) response vector. Required only if
  2123. rf_model = None or rf_model has not yet been fitted</dd>
  2124. <dt><strong><code>by</code></strong> :&ensp;<code>{'nsplits'}</code>, default=<code>'nsplits'</code></dt>
  2125. <dd>
  2126. <p>Specifies how to reallocate number of bins per feature.</p>
  2127. <p>nsplits
  2128. Reallocate number of bins so that each feature
  2129. in dcols get at a minimum of 2 bins with the
  2130. remaining bins distributed proportionally to the
  2131. number of RF splits using that feature</p>
  2132. </dd>
  2133. </dl>
  2134. <h2 id="returns">Returns</h2>
  2135. <dl>
  2136. <dt><code>self.n_bins : array</code> of <code>shape (len(dcols),)</code></dt>
  2137. <dd>number of bins per feature reallocated according to
  2138. 'by' argument</dd>
  2139. </dl></div>
  2140. <details class="source">
  2141. <summary>
  2142. <span>Expand source code</span>
  2143. </summary>
  2144. <pre><code class="python">def reweight_n_bins(self, X, y=None, by=&#34;nsplits&#34;):
  2145. &#34;&#34;&#34;
  2146. Reallocate number of bins per feature.
  2147. Parameters
  2148. ----------
  2149. X : data frame of shape (n_samples, n_features)
  2150. (Training) data to be discretized.
  2151. y : array-like of shape (n_samples,)
  2152. (Training) response vector. Required only if
  2153. rf_model = None or rf_model has not yet been fitted
  2154. by : {&#39;nsplits&#39;}, default=&#39;nsplits&#39;
  2155. Specifies how to reallocate number of bins per feature.
  2156. nsplits
  2157. Reallocate number of bins so that each feature
  2158. in dcols get at a minimum of 2 bins with the
  2159. remaining bins distributed proportionally to the
  2160. number of RF splits using that feature
  2161. Returns
  2162. -------
  2163. self.n_bins : array of shape (len(dcols),)
  2164. number of bins per feature reallocated according to
  2165. &#39;by&#39; argument
  2166. &#34;&#34;&#34;
  2167. # initialization and error checking
  2168. self._fit_preprocessing(X)
  2169. # get all random forest split points
  2170. self._fit_rf(X=X, y=y)
  2171. # get total number of bins to reallocate
  2172. total_bins = self.n_bins.sum()
  2173. # reweight n_bins
  2174. if by == &#34;nsplits&#34;:
  2175. # each col gets at least 2 bins; remaining bins get
  2176. # reallocated based on number of RF splits using that feature
  2177. n_rules = np.array([len(self.rf_splits[col])
  2178. for col in self.dcols_])
  2179. self.n_bins = np.round(n_rules / n_rules.sum() *
  2180. (total_bins - 2 * len(self.dcols_))) + 2
  2181. else:
  2182. valid_by = (&#39;nsplits&#39;)
  2183. raise ValueError(&#34;Valid options for &#39;by&#39; are {}. Got by={!r} instead.&#34;
  2184. .format(valid_by, by))</code></pre>
  2185. </details>
  2186. </dd>
  2187. <dt id="imodels.discretization.discretizer.RFDiscretizer.transform"><code class="name flex">
  2188. <span>def <span class="ident">transform</span></span>(<span>self, X)</span>
  2189. </code></dt>
  2190. <dd>
  2191. <div class="desc"><p>Discretize the data.</p>
  2192. <h2 id="parameters">Parameters</h2>
  2193. <dl>
  2194. <dt><strong><code>X</code></strong> :&ensp;<code>data frame</code> of <code>shape (n_samples, n_features)</code></dt>
  2195. <dd>Data to be discretized.</dd>
  2196. </dl>
  2197. <h2 id="returns">Returns</h2>
  2198. <dl>
  2199. <dt><strong><code>X_discretized</code></strong> :&ensp;<code>data frame</code></dt>
  2200. <dd>Data with features in dcols transformed to the
  2201. binned space. All other features remain unchanged.</dd>
  2202. </dl></div>
  2203. <details class="source">
  2204. <summary>
  2205. <span>Expand source code</span>
  2206. </summary>
  2207. <pre><code class="python">def transform(self, X):
  2208. &#34;&#34;&#34;
  2209. Discretize the data.
  2210. Parameters
  2211. ----------
  2212. X : data frame of shape (n_samples, n_features)
  2213. Data to be discretized.
  2214. Returns
  2215. -------
  2216. X_discretized : data frame
  2217. Data with features in dcols transformed to the
  2218. binned space. All other features remain unchanged.
  2219. &#34;&#34;&#34;
  2220. check_is_fitted(self)
  2221. # transform features that did not appear in RF
  2222. if len(self.missing_rf_cols_) &gt; 0:
  2223. discretized_df = self.backup_discretizer_.transform(
  2224. X[self.missing_rf_cols_])
  2225. discretized_df = pd.DataFrame(discretized_df,
  2226. columns=self.missing_rf_cols_,
  2227. index=X.index)
  2228. else:
  2229. discretized_df = pd.DataFrame({}, index=X.index)
  2230. # do discretization based on rf split thresholds
  2231. for col in self.bin_edges_.keys():
  2232. discretized_df[col] = self._discretize_to_bins(
  2233. X[col], self.bin_edges_[col])
  2234. # return onehot encoded data if specified and
  2235. # join discretized columns with rest of X
  2236. X_discretized = self._transform_postprocessing(discretized_df, X)
  2237. return X_discretized</code></pre>
  2238. </details>
  2239. </dd>
  2240. </dl>
  2241. </dd>
  2242. </dl>
  2243. </section>
  2244. </article>
  2245. <nav id="sidebar">
  2246. <h1>Index 🔍</h1>
  2247. <div class="toc">
  2248. <ul></ul>
  2249. </div>
  2250. <ul id="index">
  2251. <li><h3>Super-module</h3>
  2252. <ul>
  2253. <li><code><a title="imodels.discretization" href="index.html">imodels.discretization</a></code></li>
  2254. </ul>
  2255. </li>
  2256. <li><h3><a href="#header-classes">Classes</a></h3>
  2257. <ul>
  2258. <li>
  2259. <h4><code><a title="imodels.discretization.discretizer.AbstractDiscretizer" href="#imodels.discretization.discretizer.AbstractDiscretizer">AbstractDiscretizer</a></code></h4>
  2260. </li>
  2261. <li>
  2262. <h4><code><a title="imodels.discretization.discretizer.BasicDiscretizer" href="#imodels.discretization.discretizer.BasicDiscretizer">BasicDiscretizer</a></code></h4>
  2263. <ul class="">
  2264. <li><code><a title="imodels.discretization.discretizer.BasicDiscretizer.fit" href="#imodels.discretization.discretizer.BasicDiscretizer.fit">fit</a></code></li>
  2265. <li><code><a title="imodels.discretization.discretizer.BasicDiscretizer.transform" href="#imodels.discretization.discretizer.BasicDiscretizer.transform">transform</a></code></li>
  2266. </ul>
  2267. </li>
  2268. <li>
  2269. <h4><code><a title="imodels.discretization.discretizer.ExtraBasicDiscretizer" href="#imodels.discretization.discretizer.ExtraBasicDiscretizer">ExtraBasicDiscretizer</a></code></h4>
  2270. <ul class="">
  2271. <li><code><a title="imodels.discretization.discretizer.ExtraBasicDiscretizer.fit" href="#imodels.discretization.discretizer.ExtraBasicDiscretizer.fit">fit</a></code></li>
  2272. <li><code><a title="imodels.discretization.discretizer.ExtraBasicDiscretizer.transform" href="#imodels.discretization.discretizer.ExtraBasicDiscretizer.transform">transform</a></code></li>
  2273. </ul>
  2274. </li>
  2275. <li>
  2276. <h4><code><a title="imodels.discretization.discretizer.RFDiscretizer" href="#imodels.discretization.discretizer.RFDiscretizer">RFDiscretizer</a></code></h4>
  2277. <ul class="">
  2278. <li><code><a title="imodels.discretization.discretizer.RFDiscretizer.fit" href="#imodels.discretization.discretizer.RFDiscretizer.fit">fit</a></code></li>
  2279. <li><code><a title="imodels.discretization.discretizer.RFDiscretizer.reweight_n_bins" href="#imodels.discretization.discretizer.RFDiscretizer.reweight_n_bins">reweight_n_bins</a></code></li>
  2280. <li><code><a title="imodels.discretization.discretizer.RFDiscretizer.transform" href="#imodels.discretization.discretizer.RFDiscretizer.transform">transform</a></code></li>
  2281. </ul>
  2282. </li>
  2283. </ul>
  2284. </li>
  2285. </ul>
  2286. <p><img align="center" width=100% src="https://csinva.io/imodels/img/anim.gif"> </img></p>
  2287. <!-- add wave animation -->
  2288. </nav>
  2289. </main>
  2290. <footer id="footer">
  2291. </footer>
  2292. </body>
  2293. </html>
  2294. <!-- add github corner -->
  2295. <a href="https://github.com/csinva/imodels" class="github-corner" aria-label="View source on GitHub"><svg width="120" height="120" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="m128.3,109.0 c113.8,99.7 119.0,89.6 119.0,89.6 c122.0,82.7 120.5,78.6 120.5,78.6 c119.2,72.0 123.4,76.3 123.4,76.3 c127.3,80.9 125.5,87.3 125.5,87.3 c122.9,97.6 130.6,101.9 134.4,103.2" fill="currentcolor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  2296. <!-- add wave animation stylesheet -->
  2297. <link rel="stylesheet" href="github.css">
Tip!

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

Comments

Loading...